Check whether this matrix is symmetric in relation to the main diagonal - java

Given the number n, not exceeding 10, and a matrix of size n × n.
Check whether this matrix is symmetric in relation to the main diagonal. Output the word “YES”, if it is symmetric and the word “NO” otherwise.
This is my code, it unfortunately does not work. Please, explain to me how to do it correctly :)
public class Main { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
int[][] number = new int[n][n];
boolean ismatch = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
number[i][j] = scanner.nextInt();
}
}
int unevenchecker = (n% 2);
if (unevenchecker != 0) {
for (int k = 0; k < number.length - 1; k++) {
for (int l = 0; l < number.length - 1; l++) {
if (number[k][l] == number[l][k]) {
ismatch = true;
}
}
}
if (ismatch) {
System.out.print("YES");
}
} else {
System.out.print("NO");
}
}
}

The matrix is not symmetric if you find at least 1 symmetric couple where the 2 parts are not equal, so instead of checking for equality inside the loop, check for inequality:
ismatch = true;
for (int k = 0; k < number.length - 1; k++) {
for (int l = 0; l < number.length - 1; l++) {
if (number[k][l] != number[l][k]) {
ismatch = false;
break;
}
}
}

public class Main {
static boolean isSymmetric(int mat[][], int size) {
for (int i = 0; i < size; i++)
for (int j = i + 1; j < size - i; j++)
if (mat[i][j] != mat[j][i])
return false;
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
int[][] number = new int[n][n];
boolean ismatch = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
number[i][j] = scanner.nextInt();
}
}
if (isSymmetric(number, n)) {
System.out.print("YES");
} else {
System.out.print("NO");
}
}
}
Notice that the nested loop into isSymmetric starts from j = i + 1, for not checking twice same condition.

Related

how can i determine all prime numbers smaller than a given input value? [duplicate]

This question already has answers here:
Return all prime numbers smaller than M
(9 answers)
Closed 3 years ago.
Can anyone help me to determine all prime numbers smaller than a given input value using scanner with java8 .
Input: N integer> 0
Output: the table with prime numbers.
Example: for N = 10 the Output is : 2 3 5 7
this is my work so far:
class Main {
public static void main(String[] args) {
int N;
int[] result = null;
try (Scanner scanner = new Scanner(new File(args[0]))) {
N = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < (N/2)+1; i++) {
if (N%i==0)
result[i]=i;
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
}
System.out.println();
}
catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
}
your code problem is int i = 0 start with 0 and next line if (N%i==0) so 10/0 is not possible throw a error something like java.lang.ArithmeticException: / by zero is not possible
and you loop through result.length, you need to loop through i your parent loop and put condition inside if (N%i==0) and you need many changes saw my below answer and debug where you get unexpected output and follow.
brute Force
public static void main(String[] args) {
int N = 50;
List<Integer> result = new ArrayList<>();
for (int i = 1; i < N; i++) {
boolean isPrime = true;
for (int j = 2; j < i - 1; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
optimize one using Math.sqrt reason
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
using BigInteger.isProbablePrime see
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (long i = 1; i <= N; i++) {
BigInteger integer = BigInteger.valueOf(i);
if (integer.isProbablePrime(1)) {
result.add((int) i);
}
}
result.forEach(System.out::println);
}
Updated 1:- that something you want
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] result = new int[N];
int resultIncreamenter = 0;
// here for loop logic can be replaced with above 3 logic
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result[resultIncreamenter++] = i;
}
}
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
You lost the overview, though you have all functionality within reach.
public static boolean isPrime(int n) {
for (int i = 0; i < (n/2)+1; i++) {
if (n%i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
Simply use abstractions like isPrime.
Now for improvements (your results array): use the already found primes instead of all numbers in testing:
public static boolean isPrime(int n, int[] priorPrimes, int primesCount) {
for (int p : priorPrimes) {
if (n%p == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] primes = new int[N];
int primesCount = 0;
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
primes[primesCount] = j;
++primesCount;
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
The algorithm using the Sieve of Eratosthenes taken from here:
private static int findNumberOfPrimes(int length) {
int numberOfPrimes = 1;
if (length == 2) {
return 1;
}
int[] arr = new int[length];
//creating an array of numbers less than 'length'
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
//starting with first prime number 2, all the numbers divisible by 2(and upcoming) is replaced with -1
for (int i = 2; i < arr.length && arr[i] != -1; i++) {
for (int j = i; j < arr.length; j++) {
if (arr[j] % arr[i] == 0) {
arr[j] = -1;
numberOfPrimes += 1;
}
}
}
return numberOfPrimes;
}
Update :
and this is how you list them :
package primelessthanN;
public class Main {
public static void main(String[] args) {
int j;
int n;
n = 10;
for (j = 2; j <=n; j++) {
if (isPrime(j))
System.out.println(j);
}
}
private static boolean isPrime(int m) {
for (int i = 2; i <= sqrt(m); i++) {
if (m % i == 0)
return false;
}
return true;
}
}

How can I check if every single int in a randomly generated array is even and make it create another random array if it's not?

So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}

Why can't the driver find a method in a class?

I made a Magic Square program and it is about done, however, One of the methods in my class can't be called from the main method. I have two methods in the class and only one out of the two is not found. noRep is a method that makes sure the inputted numbers aren't repeated. When I try to use it from the main method, the compiler says
cannot find symbol method noRep (int[][])
Here is the class:
public class MagicClass
{
public static boolean noRep(int[][] square)
{
int[] one = new int[10];
for (int i = 1; i < 10; i++)
one[i] = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (square[i][j] < 1 || square[i][j] > 9)
return false;
one[square[i][j]]++;
}
}
for (int i = 1; i < 10; i++)
if (one[i] != 1)
return false;
return true;
}
public static boolean checkSums(int[][] square)
{
for (int i = 0; i < 3; i++)
{
int sum = 0;
for (int j = 0; j < 3; j++)
sum += square[i][j];
if (sum != 15)
return false;
}
for (int j = 0; j < 3; j++)
{
int sum = 0;
for (int i = 0; i < 3; i++)
sum += square[i][j];
if (sum != 15)
return false;
}
if (square[0][0] + square[1][1] + square[2][2] != 15)
return false;
if (square[0][2] + square[1][1] + square[2][0] != 15)
return false;
return true;
}
}
Here is the main method:
import java.util.*;
import java.util.Scanner;
public class MagicSquares {
public static void main(String[] args) {
int[][] square = new int[3][3];
Scanner input = new Scanner(System.in);
MagicClass MagicSqr = new MagicClass();
//checkFrequency Frequent = new checkFrequency(square); TESTING
//void Fre = MagicClass.checkFrequency (square); TESTING
System.out.println("Please enter your magic square.");
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
square[i][j] = input.nextInt();
if (checkSums(square && noRep(square)))
System.out.println("You have a magic square");
else
System.out.println("Not a magic square");
}
}
You're calling noRep in a different class.
Since it is a static method (class level method), instance is not needed. Call it using the following:
if (MagicClass.checkSums(square) && MagicClass.noRep(square))

trouble with boolean arrays and infinite loops

I working on a project called life, which is supposed to randomly display either a 1 for alive or 0 for dead. When I execute the program, the zeros and ones keep printing. I looked through the code and I couldn't find wrong.
public class Life {
//Makes the first batch of cells
public static boolean firstgen(boolean[][] a)
{
int N = 5;
double cellmaker = Math.random();
//boolean[][] b = new boolean[N][N];
for (int i = 0; i < N; i++)
{
for (int j= 0; j< N;j++)
{
if (cellmaker >0.5)
{
a[i][j]= true;
return true;
}
else
a[i][j]=false;
}
}
return false;
}
public static void main(String[] args)
{
boolean[][] b = new boolean[5][5];
//Placing the cells
for (int i =0;i < 5; i++)
{
for (int j= 0 ; j < 5;i++)
{
if (firstgen(b)== true)
{
System.out.print("1"); //1 is live cell
}
else
System.out.print("0");// 0 is dead cell
}
System.out.println();
}
}
}
In the following in your main method
for (int j= 0 ; j < 5;i++)
you should increment j instead of i.
Your random call is outside of any loop. It is therefore a constant, which will keep you in the loop. Put the random call inside the loop, and you'll be fine.
public static boolean firstgen(boolean[][] a)
{
int N = 5;
//boolean[][] b = new boolean[N][N];
for (int i = 0; i < N; i++)
{
for (int j= 0; j< N;j++)
{
double cellmaker = Math.random();
if (cellmaker >0.5)
{
a[i][j]= true;
return true;
}
else
a[i][j]=false;
}
}
return false;
}
Plus as was pointed out by Bhesh, change the i++ to a j++ here
for (int i =0;i < 5; i++)
{
for (int j= 0 ; j < 5;j++)
{
if (firstgen(b)== true)
{
System.out.print("1"); //1 is live cell
}
else
System.out.print("0");// 0 is dead cell
}
Try These
//Makes the first batch of cells
public static boolean firstgen(boolean[][] a)
{
int N = 5;
double cellmaker = Math.random();
//boolean[][] b = new boolean[N][N];
for (int i = 0; i < N; i++)
{
for (int j= 0; j< N;j++)
{
if (cellmaker >0.5)
{
a[i][j]= true;
return true;
}
else
a[i][j]=false;
}
}
return false;
}
public static void main(String[] args)
{
boolean[][] b = new boolean[5][5];
//Placing the cells
for (int i =0;i < 5; i++)
{
for (int j= 0 ; j < 5;j++)
{
if (firstgen(b))
{
System.out.print("1"); //1 is live cell
}
else
System.out.print("0");// 0 is dead cell
}
System.out.println();
}
}

Get all 1-k tuples in a n-tuple

With n=5 and k=3 the following loop will do it
List<String> l=new ArrayList<String>();
l.add("A");l.add("B");l.add("C");l.add("D");l.add("E");
int broadcastSize = (int) Math.pow(2, l.size());
for (int i = 1; i < broadcastSize; i++) {
StringBuffer buffer = new StringBuffer(50);
int mask = i;
int j = 0;
int size=0;
System.out.println();
while (mask > 0) {
if ((mask & 1) == 1) {
System.out.println(".. "+mask);
buffer.append(l.get(j));
if (++size>3){
buffer = new StringBuffer(50);
break;
}
}
System.out.println(" "+mask);
mask >>= 1;
j++;
}
if (buffer.length()>0)
System.out.println(buffer.toString());
}
but it's not efficient I would like to do it with Banker's sequence and thus explore first singletons, then pairs, then 3-tuple and stop.
I did not find a way do that, but at least this loop should be more efficient:
List<String> l=new ArrayList<String>();
l.add("A");l.add("B");l.add("C");l.add("D");l.add("E");
int broadcastSize = (int) Math.pow(2, l.size());
for (int i = 1; i < broadcastSize; i++) {
StringBuffer buffer = new StringBuffer(50);
int mask = i;
int j = 0;
if (StringUtils.countMatches(Integer.toBinaryString(i), "1") < 4){
while (mask > 0) {
if ((mask & 1) == 1) {
buffer.append(l.get(j));
}
mask >>= 1;
j++;
}
if (buffer.length()>0)
System.out.println(buffer.toString());
}
}
there is also: but k embedded loops looks ugly
//singleton
for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
}
//pairs
for (int i = 0; i < l.size(); i++) {
for (int j = i+1; j < l.size(); j++) {
System.out.println(l.get(i)+l.get(j));
}
}
//3-tuple
for (int i = 0; i < l.size(); i++) {
for (int j = i+1; j < l.size(); j++) {
for (int k = j+1; k < l.size(); k++) {
System.out.println(l.get(i)+l.get(j)+l.get(k));
}
}
}
//...
// k-tuple
This technique is called Gosper's hack. It only works for n <= 32 because it uses the bits of an int, but you can increase it to 64 if you use a long.
int nextCombo(int x) {
// moves to the next combination with the same number of 1 bits
int u = x & (-x);
int v = u + x;
return v + (((v ^ x) / u) >> 2);
}
...
for (int x = (1 << k) - 1; (x >>> n) == 0; x = nextCombo(x)) {
System.out.println(Integer.toBinaryString(x));
}
For n = 5 and k = 3, this prints
111
1011
1101
1110
10011
10101
10110
11001
11010
11100
exactly as you'd expect.
this should be the most efficient way, even if k embedded loops looks ugly
//singleton
for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
}
//pairs
for (int i = 0; i < l.size(); i++) {
for (int j = i+1; j < l.size(); j++) {
System.out.println(l.get(i)+l.get(j));
}
}
//3-tuple
for (int i = 0; i < l.size(); i++) {
for (int j = i+1; j < l.size(); j++) {
for (int k = j+1; k < l.size(); k++) {
System.out.println(l.get(i)+l.get(j)+l.get(k));
}
}
}
// ...
//k-tuple
Apache commons has iterators for subsets of size k, and for permutations.
Here is an iterator that iterates through 1-k tuples of an n-tuple, that combines the two:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections4.iterators.PermutationIterator;
import org.apache.commons.math3.util.Combinations;
public class AllTuplesUpToKIterator implements Iterator<List<Integer>> {
private Iterator<int[]> combinationIterator;
private PermutationIterator<Integer> permutationIterator;
int i;
int k;
int n;
public AllTuplesUpToKIterator(int n, int k) {
this.i = 1;
this.k = k;
this.n = n;
combinationIterator = new Combinations(n, 1).iterator();
permutationIterator = new PermutationIterator<Integer>(intArrayToIntegerList(combinationIterator.next()));
}
#Override
public boolean hasNext() {
if (permutationIterator.hasNext()) {
return true;
} else if (combinationIterator.hasNext()) {
return true;
} else if (i<k) {
return true;
} else {
return false;
}
}
#Override
public List<Integer> next() {
if (!permutationIterator.hasNext()) {
if (!combinationIterator.hasNext()) {
i++;
combinationIterator = new Combinations(n, i).iterator();
}
permutationIterator = new PermutationIterator<Integer>(intArrayToIntegerList(combinationIterator.next()));
}
return permutationIterator.next();
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
public static List<Integer> intArrayToIntegerList(int[] arr) {
List<Integer> result = new ArrayList<Integer>();
for (int i=0; i< arr.length; i++) {
result.add(arr[i]);
}
return result;
}
public static void main(String[] args) {
int n = 4;
int k = 2;
for (AllTuplesUpToKIterator iter= new AllTuplesUpToKIterator(n, k); iter.hasNext();) {
System.out.println(iter.next());
}
}
}

Categories