Stuck in an endless loop - java

I set a loop condition to be a<b. However it still continues when a>b .I get the loop in input==3
I haven't finished the code, so if you want to run it[input==3] you have to initialize the game size and after that the game .
I tried both while and for loops and im getting the same results.
import java.util.Scanner;
import java.util.Random;
public class Assignment2 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
Random rand = new Random();
int input;
int[][] board = null;
int rows = 0;
int columns = 0;
do {
System.out.println("0. End Program" + "\n" + "1. Initialize Game Size" + "\n" + "2. Initialize Game" + "\n"
+ "3. Print 1 stage Ahead" + "\n" + "4. Print k stage ahead");
input = sc.nextInt();
if (input < 0 || input > 4) {
System.out.println("Wrong menu input");
}
if (input == 0) {
System.out.println("End Program");
break;
}
if (input == 1) { // Setting a game board size
System.out.println("Enter number of rows");
rows = sc.nextInt();
System.out.println("Enter number of columns");
columns = sc.nextInt();
if (rows < 1 || columns < 1) {
System.out.println("Wrong game size");
} else {
board = new int[rows][columns];
System.out.println("set Game size");
}
}
if (input == 2) { // initialize a random game with 1 and 0
if (columns == 0 || rows == 0) {
System.out.println("No game size stored");
} else {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (rand.nextBoolean())
board[i][j] = 1;
else
board[i][j] = 0;
}
}
for (int k = 0; k < board.length; k++) {
for (int j = 0; j < board[k].length; j++) { // loop to check every square in the board
System.out.print(board[k][j] + " ");
}
System.out.println();
}
}
}
if (input == 3) { // 1 movement ahead in the game
for (int k = 0; k < board.length; k++) {
for (int j = 0; j < board[k].length; j++) { // loop to check every square in the board
if (board[k][j] == 1) {
int rowMove = 0; // checks for possible movement
int columnMove = 0; // checks for possible movement
int counter = 0;
for (rowMove = 0; rowMove < rows || columnMove < columns; rowMove++) {
for (columnMove = 0; rowMove < rows || columnMove < columns; columnMove++) {
int difrow = rowMove - rows; // row distance
int difcolumn = columnMove - columns; // column distance
if (difrow < 0) { // absolute number
difrow = -difrow;
}
if (difcolumn < 0) { // absolute number
difcolumn = -difcolumn;
}
if (difcolumn + difrow == 3) {
counter++;
}
}
}
if (counter == 1 || counter == 2) {
board[k][j] = 1;
} else {
board[k][j] = 0;
}
}
}
}
for (int k = 0; k < board.length; k++) {
for (int j = 0; j < board[k].length; j++) { // loop to check every square in the board
System.out.print(board[k][j] + " ");
}
System.out.println();
}
}
} while (input != 0);
}
}

in your inner for loop
for (columnMove = 0; rowMove < rows || columnMove < columns; columnMove++)
the condition is to iterate as long as rowMove < rows || columnMove < columns but only columnMove get advanced, so rowMove < rows is always true

have you tried this :
for (rowMove = 0; rowMove < rows; rowMove++) {
for (columnMove = 0; columnMove < columns; columnMove++)

Related

Count and print even flowers

We have n number of flowers that can be black or white. We have m number of months. At the end of each month, if the number of white flowers is even, we print B for the number of roses that are even, and print F for the rest of the characters.For example:(W=white,B=black)
input:3(n) 2(m)
WBW
BBW
output:FBB
My code just work well just for this example and dont give true answer for other examples.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of flowers: ");
int flower = input.nextInt();
System.out.println("Enter number of months : ");
int month = input.nextInt();
String[] arr = new String[month];
char ch = ' ';
int count = 0;
for (int j = 0; j < month; j++)
arr[j] = input.next();
for (int i = 0; i < month; i++) {
char[] s = arr[i].toCharArray();
for (int j = 0; j < flower; j++) {
if (s[j] == 'W') {
count++;
}
}
if (count % 2 == 0) {
for (int k = 0; k < flower - count; k++) {
System.out.print('F');
}
for (int b = 1; b <= count; b++) {
System.out.print('B');
}
}
}
}
}
In your for loop
for (int j = 0; j < flower; j++) {
if (s[j] == 'W') {
count++;
}
}
We must remember what s is referring to, char[] s = arr[i].toCharArray(); which means that s will not have a length of flower but will have a length of arr[i].length() or s.length.
So if you change the for loop to use that as its control, it should solve the index out of bounds exception that you get.
The fix would look like:
for (int j = 0; j < s.length; j++) {
if (s[j] == 'W') {
count++;
}
}

Java: Sudoku- increase number of empty spaces causes my code to throw an exception

I'm trying to make a Sudoku game for my project but if i increase the number of empty spaces in the Sudoku Grid the code just throws an exception arrayoutofbounds but can't figure out where it's coming from. k is the number of empty spaces in the grid.
I haven't tried anything because can't figure out what can be done at this kind of problem
Here is the code:
package sudoku.puzzle;
import java.util.*;
public class SudokuPuzzle {
int[] mat[];
int N; // number of columns/rows.
int SRN; // square root of N
int K; // No. Of missing digits
// Constructor
SudokuPuzzle(int N, int K) {
this.N = N;
this.K = K;
// Compute square root of N
Double SRNd = Math.sqrt(N);
SRN = SRNd.intValue();
mat = new int[N][N];
}
// Driver code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Select Level Of Difficulty \n 1.Easy\n 2.Medium\n 3.Hard");
String Choice = in .next(); in .close();
if ("1".equals(Choice) || "Easy".equals(Choice) || "easy".equals(Choice) || "e".equals(Choice) || "E".equals(Choice)) {
int N = 9, K = 40;
SudokuPuzzle sudoku = new SudokuPuzzle(N, K);
sudoku.fillValues();
sudoku.printSudoku();
}
if ("2".equals(Choice) || "Medium".equals(Choice) || "medium".equals(Choice) || "m".equals(Choice) || "M".equals(Choice)) {
int N = 9, K = 60;
SudokuPuzzle sudoku = new SudokuPuzzle(N, K);
sudoku.fillValues();
sudoku.printSudoku();
}
if ("3".equals(Choice) || "Hard".equals(Choice) || "hard".equals(Choice) || "h".equals(Choice) || "H".equals(Choice)) {
int N = 9, K = 72;
SudokuPuzzle sudoku = new SudokuPuzzle(N, K);
sudoku.fillValues();
sudoku.printSudoku();
}
}
// Sudoku Generator
public void fillValues() {
// Fill the diagonal of SRN x SRN matrices
fillDiagonal();
// Fill remaining blocks
fillRemaining(0, SRN);
// Remove Randomly K digits to make game
removeKDigits();
}
// Fill the diagonal SRN number of SRN x SRN matrices
void fillDiagonal() {
for (int i = 0; i < N; i = i + SRN)
// for diagonal box, start coordinates->i==j
fillBox(i, i);
}
// Returns false if given 3 x 3 block contains num.
boolean unUsedInBox(int rowStart, int colStart, int num) {
for (int i = 0; i < SRN; i++)
for (int j = 0; j < SRN; j++)
if (mat[rowStart + i][colStart + j] == num)
return false;
return true;
}
// Fill a 3 x 3 matrix.
void fillBox(int row, int col) {
int num;
for (int i = 0; i < SRN; i++) {
for (int j = 0; j < SRN; j++) {
do {
num = randomGenerator(N);
}
while (!unUsedInBox(row, col, num));
mat[row + i][col + j] = num;
}
}
}
// Random generator
int randomGenerator(int num) {
return (int) Math.floor((Math.random() * num + 1));
}
// Check if safe to put in cell
boolean CheckIfSafe(int i, int j, int num) {
return (unUsedInRow(i, num) &&
unUsedInCol(j, num) &&
unUsedInBox(i - i % SRN, j - j % SRN, num));
}
// check in the row for existence
boolean unUsedInRow(int i, int num) {
for (int j = 0; j < N; j++)
if (mat[i][j] == num)
return false;
return true;
}
// check in the row for existence
boolean unUsedInCol(int j, int num) {
for (int i = 0; i < N; i++)
if (mat[i][j] == num)
return false;
return true;
}
// A recursive function to fill remaining
// matrix
boolean fillRemaining(int i, int j) {
// System.out.println(i+" "+j);
if (j >= N && i < N - 1) {
i = i + 1;
j = 0;
}
if (i >= N && j >= N)
return true;
if (i < SRN) {
if (j < SRN)
j = SRN;
} else if (i < N - SRN) {
if (j == (int)(i / SRN) * SRN)
j = j + SRN;
} else {
if (j == N - SRN) {
i = i + 1;
j = 0;
if (i >= N)
return true;
}
}
for (int num = 1; num <= N; num++) {
if (CheckIfSafe(i, j, num)) {
mat[i][j] = num;
if (fillRemaining(i, j + 1))
return true;
mat[i][j] = 0;
}
}
return false;
}
// Remove the K no. of digits to
// complete game
public void removeKDigits() {
int count = K;
while (count != 0) {
int cellId = randomGenerator(N * N);
// System.out.println(cellId);
// extract coordinates i and j
int i = (cellId / N);
int j = cellId % 9;
if (j != 0)
j = j - 1;
// System.out.println(i+" "+j);
if (mat[i][j] != 0) {
count--;
mat[i][j] = 0;
}
}
}
// Print sudoku
public void printSudoku() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
System.out.println();
}
}
What you got is probably a ArrayIndexOutOfBoundsException. That means at some point you try to access a field of an array outside its boundaries.
But I can´t see where K could be responsible for that. Can you provide more information about the error? E.g. at which value you get it or in which line.
EDIT: The variable i int the removeKDigits() function exceeds the boundaries of the array if the random generator spits out the value 81.

different output in conways game of life

I have to create a Java program for Conway's Game Of Life in procedural manner and I'm only one step away from finishing - all I have left to do is figure out how to make the output change itself(something like a GIF). Instead, my program outputs all the results one by one. I'm figuring it should be some kind of a loop, but I'm not sure. Here's the code:
import java.util.Random;
import java.util.Scanner;
class gameOfLife {
public static void main(String[] args) {
//User input
Scanner in = new Scanner(System.in);
System.out.println("How many rows?");
int rows = in.nextInt();
System.out.println("How many columns?");
int cols = in.nextInt();
//Declaring variables and grids
int[][] grid = new int[rows][cols];
int[][] nextGrid = new int[rows][cols];
int[][] temp = new int [rows][cols];
//Initializing first generation
initiateGrid(grid);
printGameBoard(grid);
//Looping through 10 generations
for (int x = 0; x < 20; x++) {
applyTheRules(grid, rows, cols, nextGrid);
temp = nextGrid;
nextGrid = grid;
grid = temp;
printGameBoard(grid);
}
}
//Initiating first generation grid randomly
static void initiateGrid(int[][] grid) {
Random r = new Random();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = r.nextInt(2);
}
}
}
//Printing out the game board
static void printGameBoard(int[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 0)
System.out.print(" . ");
else
System.out.print(" ■ ");
}
System.out.println();
}
System.out.println();
}
//Applying the rules of the game
static void applyTheRules(int [][] grid, int rows, int cols, int [][] nextGrid) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int count = 0;
if(i-1>=0 && i+1<grid.length && j-1>=0 && j+1<grid[i].length) {
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
count += grid[i + x][j + y];
}
}
count -= grid[i][j];
} else{
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
count += 0;
}
}
}
//Alive cell becomes dead, if there are more than
//3 or less than 2 neighbouring cells
if((grid[i][j]==1)&&(count<2)||(count>3))
nextGrid[i][j]=0;
//Dead cell becomes alive if there are exactly 3 neighbouring cells
else if((grid[i][j]==0)&&(count==3))
nextGrid[i][j]=1;
//State stays the same
else
nextGrid[i][j]=grid[i][j];
}
}
}
}

How to check array for possible divisors?

Creating the array, I am letting the user choose the length:
StartNum = scan.nextInt();
int[] NumBox = new int[StartNum];
for (int i = 1; i < NumBox.length+1; i++)
{NumBox[i - 1] = i;}
NumBox[0]=0;
Assuming there are other methods that can change cells in NumBox to 0, how would I use a for loop to check each cells in the array for any divisor? If there are no divisors for the cell in the array, it will then become a 0. For example, if the array is [0,2,0,4,0,6,7,8,9] 9,2 and 7 would become a 0.
The code below is what I tired but didn't get far.
boolean NoDiv=false;
for (int a=1; a < NumBox.length+1; a++)
{
a++
for (int check=1; a < NumBox.length+1; check++)
{
if (NumBox[a-1]% check == 0 && NumBox[a-1] !=0)
{
NumBox[a-1] = 0;
}
}
}
for (int i = 0; i < NumBox.length; i++) {
if (NumBox[i] == 0) continue;
boolean hasDivisor = false;
for (int j = 0; j < i; j++) {
if (NumBox[j] == 0) continue;
if (NumBox[i] % NumBox[j] == 0) {
hasDivisor = true;
break;
}
}
if (!hasDivisor) NumBox[i] = 0;
}

Grid and adjacency matrix in java

Need little help with my programming.
I'd like to create a grid with n columns and n rows. A also would like to show or print adjacency matrix.For start I did create some code, but the results are not correct, and I don't know hot to fix it. I need this grid to calculate shortest path, mutation of this grid, ...
The first for loop create a nice grid size n*n, but I don't know how to create links between naighbour nodes. The second code (which is in comment, create a adjacency matrix, but is not correnct -> node 3-4,7-8, 11-12 shouldn't be connected (if we have 4x4 grid), and in this code is missing last 4 nodes (if n=4).
Can someone tell me where did I fail in my coding :)?
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Network_1 {
public static void main(String[] args) throws Exception {
BufferedReader input1 = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter the number of columns/rows");
int cols = Integer.parseInt(input1.readLine());
input1.close();
int N = cols * cols;
int[][] A = new int[N][N];
for (int i = 0; i < N; i++) {
if (i > 1
&& ((cols == 0 && N % i == 0) || (cols > 0 && i % cols == 0))) {
if (cols == 0) {
cols = i;
}
System.out.print("\n");
}
System.out.format("%3d", i);
}
System.out.println("\nAdjacency matrix:");
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println();
}
/*
// If I try to create my "grid" with this code, I do not get true results
// The Matrix is incorrect
for(int i=0; i<N-cols; i++){
for(int j=0; j<N-cols; j++){
if((cols > 0) && (i % cols == 0)){
A[i][i+1] = 0;
A[i + 1][i] = 0;
}else{
A[i][i+1] = 1;
A[i + 1][i] = 1;
A[i][i+cols] = 1;
A[i + cols][i] = 1;
}
}
}
System.out.println("Adjacency matrix2:");
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println("");
}
*/
}
}
Helo. I did some other approach and this work quite well for me right now. I know tis isn't the best solution, but it wokrs for now. Now I will etst if realy works...
public static int[][] make_grid(int cols) {
int N = cols * cols;
int[][] A = new int[N][N];
for (int i = 0; i < N; i++) {
A[i][i] = 0;
int left= i - 1;
int right= i + 1;
int upper= i - cols;
int bottom= i + cols;
if (left> 0)
A[i][left] = 1;
if (rigft% cols != 0) {
if (right< N)
A[i][right] = 1;
}
if (upper> 0)
A[i][upper] = 1;
if (bottom< N)
A[i][bottom] = 1;
}
return A;
}

Categories