trouble with boolean arrays and infinite loops - java

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();
}
}

Related

Sudoku check subboxes for duplicates

i have to check the validity of a sudoku as a homework. the rows and cols were no big deal, but i'm stuck at checking the boxes.
i want to loop through the 3x3 sub-boxes and check them for duplicates, with copying the numbers into a smaller 3x3 array, flattening it and then checking it for duplicates.
my while loop doesn't seem to make sense tho, the first iteration works but the second one writes wrong values into my new array. i just don't know where to add my boxcount.
i feel like a noob, if someone can help i'd be thankful
private static boolean isValidSudokuSolution(int[][] sudokuField) {
// TODO: Implementieren Sie hier Ihre Lösung für die Methode
//rows
int row = 0;
while (row < sudokuField.length) {
for (int i = 0; i < sudokuField[row].length; i++) {
for (int j = 0; j < i; j++) {
if (sudokuField[row][i] == sudokuField[row][j]) {
return false;
}
}
}
row++;
}
//cols
int col = 0;
while (col < sudokuField.length) {
for (int i = 0; i < sudokuField[col].length; i++) {
for (int j = 0; j < i; j++) {
if (sudokuField[i][col] == sudokuField[j][col]) {
return false;
}
}
}
col++;
}
//box
int boxCount = 0;
while (boxCount < sudokuField.length) {
//create box array
int[][] box = new int[3][3];
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
box[i][j] = sudokuField[i + boxCount][j];
}
}
//flatten box
int[] flattenedBox = new int[sSize];
int counter = 0;
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
int num = box[i][j];
flattenedBox[counter + j] = num;
}
counter += 3;
}
//look for duplicates
for (int i = 0; i < flattenedBox.length; i++) {
for (int j = 0; j < i; j++) {
if (flattenedBox[i] == flattenedBox[j]) {
return false;
}
}
}
boxCount += 3;
}
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;
}
}

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

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.

My matrix doesn’t change when I try to perform scalar multiplication

we're supposed to multiply every element in the matrix by a number, in this case "k". not sure what i'm doing wrong but it wont work. HELP! i have edited and added the whole project so far.
public class Matrix {
private int r;//rows
private int c;//columns
private int[][] neo; //2D array
public static void main(String[] args) {
Matrix m1 = new Matrix(3,4);
Matrix m2 = new Matrix(3,4);
System.out.println(m2);
try {
Matrix m3 = m1.multiply(m2);
} catch (Exception e) {
e.printStackTrace();
}
m2.scaleMult(k);
}//main
public Matrix(int row, int column) {
r = row;
c = column;
neo = new int[r][c];
for(int i = 0; i < neo.length; i++) {
for (int j = 0; j < neo[i].length; j++) {
neo[i][j] = (int) (1 + Math.random() * 100);
}//forLoop
}//forLoop
System.out.println(Arrays.toString(neo));
}//Matrix
public Matrix copyMatrix(Matrix m) {
Matrix copy = new Matrix(m.r, m.c);
for (int i = 0; i < r; i++) {
System.arraycopy(this.neo[i], 0, copy.neo[i], 0, this.neo[i].length);
}//forLoop
return copy;
}//copyMatrix
public void scaleMult(int k){
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
this.neo[i][j] * k;
}//scaleMult
public boolean equals(Matrix m2) {
if (this.r != m2.r || this.c != m2.c) {
return false;
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (this.neo[i][j] != m2.neo[i][j]) {
return false;
}
}
}
return true;
}//equalsMethod
public Matrix multiply(Matrix m2) throws Exception {
if (this.c != m2.r) {
throw new RuntimeException();
}//if
Matrix m3 = new Matrix(this.r, m2.c);
for (int i = 0; i < this.r; i++) {
for (int j = 0; j < m2.c; j++) {
m3.neo[i][j] = 0;
for (int k = 0; k < this.c; k++) {
m3.neo[i][j] += this.neo[i][k] * m2.neo[k][j];
}//forK
}//forJ
}//forI
return m3;
}//multiplyMethod
}//class
Change your scaleMult method to this and it should work:
public void scaleMult(int k) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
this.neo[i][j] *= k;
// you forgot to assign the value, basically we multiply neo[i][j] by k and make neo[i][j] receive that value
// making this.neo[i][j] = this.neo[i][j] *k; would work as well
}
}
}//scaleMult
Also, based on the example you provided on your main method, your code will launch an exception on the multiply method, because as you specified, you can only multiply two matrixes if one's columns amount is equal to the other's row amount. Other than that, I would advise on creating a new class just for your main method.
If your question is multiply a matrix by a number, then here is a very simple example.
public static void main(String []args){
int[][] a = {{1,2,3},{4,5,6}};
int[][] b=new int[2][3];
int i,j,k=2;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
b[i][j]=a[i][j]*k;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
System.out.println(b[i][j]);
}
There must be some array variable on left which should be assigned the multiplied value.
Do this helped? If not, please post your complete code.

Implementing pacman game issue when moving it up and down

I am trying to build a simple pacman game, and I just got started.
Currently my constructor looks like this:
static String[][] board;
static int pacmanBornHeight;
static int pacmanBornWidth;
public PacmanKata(int height, int width) {
board = new String[height][width];
pacmanBornHeight = (int) Math.floor(height / 2);
pacmanBornWidth = (int) Math.floor(width / 2);
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
board[i][j] = "*";
}
}
board[pacmanBornHeight][pacmanBornWidth] = "V";
}
This constructor set up the board and the pacman will be located at the middle, I used "V" as the symbol.
I try to create two methods currenlty, move up and down.
Here is the setup:
I first called the tickUp method:
public void tickUp(int steps) {
int counter = 1;
int timer = 0;
for (int loop = 0; loop < steps; loop++) {
board[pacmanBornHeight - counter][pacmanBornWidth] = "V";
for (int innerTimer = 0; innerTimer < counter; innerTimer++) {
board[pacmanBornHeight - innerTimer][pacmanBornWidth] = " ";
}
counter++;
timer++;
}
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
System.out.println("-------------------------");
} //end going UP
And I print out this to console(I initialized a 10 by 10 board):
Pacman moved up three steps, as expected, and eat three dots. I slightly modified and created a move down method:
public void tickDown(int steps) {
int counter = 1;
int timer = 0;
for (int loop = 0; loop < steps; loop++) {
board[pacmanBornHeight + counter][pacmanBornWidth] = "V";
for (int innerTimer = 0; innerTimer < counter; innerTimer++) {
board[pacmanBornHeight + innerTimer][pacmanBornWidth] = " ";
}
counter++;
timer++;
}
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
System.out.println("-------------------------");
}//end tickDown
Now I called tickDown and asked it to move down 3 steps, but I got this result:
The trouble I am having is, I do not know how to locate the Pacman last location. The move down method simply created a new Pacman and moved down 3 steps, that is not what I want. How can I fix this?
Change your tickUp and tickDown methods to save the new position of your Pacman:
public void tickDown(int steps) {
int counter = 1;
int timer = 0;
for (int loop = 0; loop < steps; loop++) {
for (int innerTimer = 0; innerTimer < counter; innerTimer++) {
board[pacmanBornHeight + innerTimer][pacmanBornWidth] = " ";
}
pacmanBornHeight += counter;
//Allow for wraparounds:
if (pacmanBornHeight > board.length) {
pacmanBornHeight = 0;
}
board[pacmanBornHeight][pacmanBornWidth] = "V";
timer++;
}
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
System.out.println("-------------------------");
}//end tickDown
I moved the loop to write spaces in the board to the beginning of the outer loop; that way you get the spaces based on the starting position of Pacman. Once you've written the spaces to the array, you update Pacman's position and write it in the array.
Edit:
Here's an example showing how you'd use a one-dimensional array as your board:
public class PacmanKata {
static String[] board;
static int pacmanPosition;
static int boardHeight;
static int boardWidth;
public static void main(String[] args) {
PacmanKata kata = new PacmanKata(10,10);
kata.tickUp(7);
kata.tickRight(9);
}
public PacmanKata(int height, int width) {
boardHeight = height;
boardWidth = width;
board = new String[height*width];
int offset = (width + 1) % 2;
pacmanPosition = (int) Math.floor((height + offset)*width/2);
for (int i = 0; i < board.length; i++) {
board[i] = "*";
}
board[pacmanPosition] = "V";
}
private void printBoard() {
for (int i = 0; i < board.length; i++) {
System.out.print(board[i]);
if ((i+1) % boardWidth == 0) {
System.out.println();
}
}
System.out.println("-------------------------");
}
public void tickUp(int steps) {
int counter = -1 * boardHeight;
for (int loop = 0; loop < steps; loop++) {
//Current position = ' '
board[pacmanPosition] = " ";
//Pacman's position changes:
pacmanPosition += counter;
//Allow for wraparounds:
if (pacmanPosition < 0) {
pacmanPosition += board.length;
}
//Update the board with Pacman's new position:
board[pacmanPosition] = "V";
}
printBoard();
}//end tickUp
public void tickRight(int steps) {
int counter = 1;
for (int loop = 0; loop < steps; loop++) {
//Current position = ' '
board[pacmanPosition] = " ";
//Pacman's position changes:
pacmanPosition += counter;
if (pacmanPosition % boardWidth == 0) {
pacmanPosition -= boardWidth;
}
//Update the board with Pacman's new position:
board[pacmanPosition] = "V";
}
printBoard();
}//end tickUp
}
Instead of having pacmanBornWidth and pacmanBornHeight fields, you should have a field with pacman current position (all fields shouldn't be static):
String[][] board;
java.awt.Point pacmenPos;
public PacmanKata(int height, int width) {
board = new String[height][width];
pacmanPos = new Point((int) width/2, (int) height/2);
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
board[i][j] = "*";
}
}
board[pacmanPos.x][pacmanPos.y] = "V";
}
Now replace all occurrences of pacmanBornWidth and pacmanBornHeight with pacmanPos.x and pacmanPos.y.
And in your tickUp and tickDown methods, just update pacman position:
public void tickUp(int steps) {
...
pacmanPos.translate(0, steps);
...
}
public void tickDown(int steps) {
...
pacmanPos.translate(0, -steps);
...
}
This will also work the same if you add tickLeft and tickRight methods:
public void tickLeft(int steps) {
...
pacmanPos.translate(-steps, 0);
...
}
public void tickRight(int steps) {
...
pacmanPos.translate(steps, 0);
...
}

Categories