Void method printing two times - java

Hello I am trying to understand the code I have written and why does it print the output below
public void isSymmetricNow(int[][] matrix){
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
}
}
}
System.out.print("matrix is symmetric \n");
}
prints me
matrix is not symmetric
matrix is not symmetric
matrix is symmetric
ASSUME THAT the given matrix is not symmetric here.
int matrix3[][] = {{1,4,7},{-4,6,6},{7,6,9}};
How can I modify this code to give me back saying if the matrix is symmetric or not only once.

Just a plain return statement will do. It will not execute again if the condition is false.
public void isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
return;
}
}
}
System.out.print("matrix is symmetric \n");
}
Or
You could return a boolean saying it is a Symmetric or not.
public boolean isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}
then call it using your function.
if(isSymmetric(matrix))
System.out.println("Symmetric");
else
System.out.println("Not Symmetric");

First of all, your loops will print "matrix is not symmetric \n" whenever they find i and j for which matrix[i][j] != matrix[j][i], which can happen more than once.
and System.out.print("matrix is symmetric \n"); is always called, so that explains the last line of output.
You probably want your method to have a boolean return value instead of printing this output. This way the loops will only iterate until you find out that the matrix is not symmetric.
public boolean isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}
To do the same without a return value :
public void isSymmetricNow(int[][] matrix){
//Random random = new Random();
boolean isSymmetric = true;
for (int i = 0; i < matrix.length && isSymmetric; i++) {
for (int j = 0; j < matrix.length && isSymmetric; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
isSymmetric = false;
}
}
}
if (isSymmetric)
System.out.print("matrix is symmetric \n");
}

1) As Eran pointed out, i and j aren't equal more than once and hence will keep printing for as long as the loop iterates. I suggest using a break statement to exit out of the loop the very first time it finds that i != j.
2)The last print statement will be called irrespective of how the the loop behaves and whether the matrix is symmetric or not. I suggest printing that the matrix is symmetric by creating another if statement outside the loop to check symmetry.

public void isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
return; //When it does not symetric, return.
}
}
}
System.out.print("matrix is symmetric \n");
}

Related

How to print all pairs of an ArrayList with no duplicates

Just a simple question. I know to print all possible pairs, you do a nested for loop with a few more adjustments to be fancier. In my case, I want to take it a step up where pairs are not allowed to repeat or have 2 of the same integer in a pair.
For example: (0,0) is not allowed, but (0,1) is allowed. If (0,1) is a pair, then (1,0) is not allowed.
If I had integers "0,1,2,3", then my output would be
(0,0)(0,1)(0,2)(0,3)(1,2)(1,3)(2,3)
This is my current code that won't print pairs with 2 same integers, but repeated pairs still print.
for(int a = 0; a < 4;a++) {
numbers.add(a);
}
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(i != j) {
System.out.println("("+i+" , "+j+")");
}
}
}
Thanks
for(int i = 0; i < 4; i++) {
for(int j = i; j < 4; j++) {
if(i != j) {
System.out.println("("+i+" , "+j+")");
}
}
}
or
for(int i = 0; i < 4; i++) {
for(int j = i + 1; j < 4; j++) {
System.out.println("("+i+" , "+j+")");
}
}

Check if simple graph is oriented?

The Task is
"You've got a adjacency matrix (nxn). And simple graph. Print YES, if the graph is undirected and NO otherwise."
My teacher says that the programm is incorrect. Why?
import java.util.Scanner;
public class Graph {
private static Scanner scan;
public static void main(String[] args){
scan = new Scanner(System.in);
final int n = scan.nextInt();
Graph graph = new Graph();
int[][] matrix = graph.createMatrix(n);
boolean truth = graph.checkoriented(matrix);
System.out.println((truth)? "Yes": "No");
scan.close();
}
private boolean checkoriented(int[][] matrix) {
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
if(matrix[i][j] == 1){ //look if element on i pow, j column is "1";
boolean way = (matrix[j][i] == 1)? true: false; //if element on j pow i locumn is 1 also
if(!way) return false; // if element on j pow i locumn is 0 graph is oriented
}
}
}
return true;
}
private int[][] createMatrix(int n) {
int[][] matrix = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
matrix[i][j] = scan.nextInt();
}
}
return matrix;
}
}
I don't know if it is actually a problem, but if your output should be YES or NO you'd better print these instead of Yes and No here System.out.println((truth)? "Yes": "No");.
P. S. If your graph has a way from the vertex to the same one (I mean matrix[i][i] = 1), your algorithm might consider the graph to be undirected, while it is not.
Based on the discussion and A. Yurchenko's inputs, I'm updating my answer for completeness (only).
private boolean checkoriented(int[][] matrix) {
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
if(i == j && matrix[i][j] !=0) {
return false;
}
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}

I am trying this simple sudoku

I am trying a simple sudoku program. i started by taking the values in a 3D
array and then copied them into a 1D array by using mr.serpardum's method.
i know that there is an error at the point where i am trying to find
duplicate elements,because even if i give same numbers as input the output
says "its a sudoku" but i can't to find it...apparently i can't add any
image coz i dont have enough credits
public class SecondAssignment {
#SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
int i = 0, j = 0, k = 0;
boolean result = false;
int arr1[][];
arr1 = new int[3][3];
int arr2[];
arr2 = new int[9];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements in the sudoku block");
//getting elements into array
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr1[i][j] = Integer.parseInt(br.readLine());
}
}
//printing it in matrix form
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
System.out.print(arr1[i][j] + "\t");
}
System.out.println(" ");
}
//copying array1 elements into array 2
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr2[i * 3 + j] = arr1[i][j];
}
}
//finding duplicate elements
for (i = 0; i < arr2.length; i++) {
for (int m = i + 1; m < arr2.length; m++) {
if (arr2[i] == (arr2[m])) {
System.out.println("Not a sudoku");
//result = true;
} else {
System.out.println("Its a sudoku");
//result = false;
}
}
}
}
}
You can update your code to following
//finding duplicate elements
for( i = 0; i < arr2.length; i++){
for(int m = i+1; m < arr2.length; m++){
if(arr2[i] == (arr2[m])){
result = true;
break;
}
}
}
if(result){
System.out.println("\nNot a sudoku");
}
else{
System.out.println("\nIts a sudoku");
}
You should have used break as soon as the match was found.
This code just checks if duplicate element is present in the array (of size 9) or not.

Making a nested for loop into a single for loop

I had an assignment to create an array of random number from 10-100.
Then I need to sout all the numbers not listed in the array.
I did the assignment with a nested for loops, to cross reference the arrays, then I changed all the found numbers in the array into -1. Finally I printed out the elements in the array that were not -1.
My professor told me that is it possible for me to do this assignment with only one for loop and there is no need to do a nested for loop. and make the computer run 10,000 times instead of just 100.
Is that possible? If so how?
Thank you.
package assignment.pkg1;
import java.util.Random;
public class Assignment1 {
static Random ran = new Random();
public static void main(String[] args) {
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (ran.nextInt(90)) + 10;
}
InversingArray(arr);
}
public static void InversingArray(int[] randomArray) {
int[] fullArray = new int[100];
for (int i = 0; i < 100; i++) {
fullArray[i] = i;
}
for (int i = 0; i < 100; i++) {
for (int j = 1; j < 100; j++) {
if (randomArray[j] == fullArray[i]) {
fullArray[i] = -1;
}
}
}
System.out.println("These numbers are not in randomArray: ");
for (int i = 0; i < 100; i++) {
if (fullArray[i] != -1) {
System.out.println(fullArray[i]);
}
}
}
In your code you create an array to hold the possible values. If you think about it, the array index will always be equal to the number stored in the array.
fullArray[i] = i;
This is redundant.
What you are being asked to do is determine which numbers have been used: a boolean test. This means that you should have an array of boolean that is initially false (the default value of booleans in java) and is flipped to true when an equal integer is flipped to true.
Something like
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (ran.nextInt(90)) + 10;
}
// ba starts with all false values
boolean ba[] == new boolean[90]; // note that the instructor said 10-100
for(int i=0; i<90; i++) {
ba[arr[i]] = true;
// lets assume arr[0] == 45
// ba[arr[0]] is the same as ba[45]
// ba[45] = true; will set that bucket of the boolean array to true
}
System.out.println("These numbers are not in randomArray: ");
for (int k = 0; k < 10; k++) {
System.out.println(k);
}
for (int j = 0; j < 90; j++) {
if (!ba[j]) { // shorthand for ba[j]==false
System.out.println(j+10); // The array starts at a base of 10
}
}
Be aware (probably the point of the exercise) that you are working with an array [0..90] that represents the numbers [10..100].
The nested loop currently looks like this:
for (int i = 0; i < 100; i++) {
for (int j = 1; j < 100; j++) {
if (randomArray[j] == fullArray[i]) {
fullArray[i] = -1;
}
}
}
But we know, that fullArray[i] is always the same as i.
So you can rewrite it to:
for (int j = 1; j < 100; j++) {
int i = randomArray[j];
fullArray[i] = -1;
}
Or even shorter:
for (int j = 1; j < 100; j++) {
fullArray[randomArray[j]] = -1;
}

Implementing columnar encryption technique?

I am working on another encryption technique now, the columnar transposition cipher technique.
So far I have only tried to make columns and what I am trying to do is to view the matrix.
But with the code that I have written it is only showing one letter in the matrix:
import java.io.*;
import java.lang.reflect.Array;
public class transCip {
public static void main(String args[]) {
String keys;
String message;
String encrypt;
String decrypt;
message = "encryptiontextbe";
keys = "work";
encrypt = "";
decrypt = "";
char msg[] = message.toCharArray();
char key[] = keys.toCharArray();
int x = msg.length;
int y = key.length;
char temp[][] = new char[y][x];
if (x % y != 0) {
System.out.println("Cannot encrypt string");
}
for (int i = 0; i < (x/y); i++)
{
for (int j = 0; j < y; j++)
{
int k=0;
temp[i][j] = msg[k];
k++;
}
}
System.out.println("Matrix");
for (int i = 0; i < (x/y); i++)
{
for (int j = 0; j < y; j++)
{
System.out.print(temp[i][j]);
}
System.out.println("");
}
}
}
And my current output is as follows:
Matrix
eeee
eeee
eeee
eeee
I can't seem to figure out why this is happening;
I tried solving the run on paper also.
for (int i = 0; i < (x/y); i++)
{
for (int j = 0; j < y; j++)
{
int k=0;
temp[i][j] = msg[k];
k++;
}
}
You reset k to zero in each iteration of the loop, guaranteeing you always get the first letter 'e' of your message string. Try initializing k before the inner loop. This would have been easier to spot with better formatting:
for (int i = 0; i < (x/y); i++) {
for (int j = 0; j < y; j++) {
int k=0;
temp[i][j] = msg[k];
k++;
}
}

Categories

Resources