For loop in Java for filling up table - java

Let's say i have a table format in Java
0 1 2
|_E_|____|____| 0
|___|____|____| 1
Where the numbers at the top are the index of the column and the numbers on the side are the index of the row. A function:
add_at(x,y)
takes two arguments x and y which is the x coordinate and y coordinate. I'm trying to fill up the table using a for loop for which it begins from the position 0,1 which is
0 1 2
|_E_|__x_|____| 0
|___|____|____| 1
marked with x, followed by 0,2
0 1 2
|_E_|__x_|__x_| 0
|___|____|____| 1
proceeding with
0 1 2
|_E_|__x_|__x_| 0
|_x_|____|____| 1
0 1 2
|_E_|__x_|__x_| 0
|_x_|__x_|____| 1
0 1 2
|_E_|__x_|__x_| 0
|_x_|__x_|__x_| 1
until the table is filled except for the location 0,0 which is marked by E.
int max_row = 1; //maximum row length is 1
int max_col = 2; //maximum column length is 2
for (int x = 0; x<=max_row; x++) {
for (int y = 1; y<max_col; y++) {
this.add_at(x,y)
}
}
I'm a beginner at Java and I'm pretty sure the for loop i wrote is wrong in a way where i wanted the output to be. Would appreciate some help on this.

Change y to be initialised to zero (i.e. populate all rows) and add a special condition for (0,0).
Also, both conditions should use <=.
int max_row = 1; //maximum row length is 1
int max_col = 2; //maximum column length is 2
for (int x = 0; x <= max_row; x++) {
for (int y = 0; y <= max_col; y++) {
if (x == 0 && y == 0) continue;
this.add_at(x,y);
}
}

You can do as following, and u can change the code according to your needs:
public class Table {
public static void main(String[] args) {
int maxRow = 4; //maximum row length is 4
int maxCol = 5; //maximum column length is 5
for (int x = 0; x<maxRow; x++) {
for (int y = 0; y<maxCol; y++) {
if (x==0 && y==0){
System.out.print("| |");
continue;
}
add_at(x, y);
}
System.out.println();
}
}
public static void add_at(int x, int y) {
System.out.print("|x|");
}
}
The result will be like:
| ||x||x||x||x|
|x||x||x||x||x|
|x||x||x||x||x|
|x||x||x||x||x|
You can see the screenshot from the output:
I hope the code helps you

Related

Trying to implement Conway's Game of Life in Java but having trouble with counting the "living" cells around a cell

I'm a beginner in coding. I have this problem that I know already, but I can't seem to find the solution
Given a preset 5x5 2D array representing the board (. means dead cell and 0 means living cell.
)
. . . . .
. . . . .
. . 0 . .
. . . . .
. . . . .
I have a method countLivingNeighbors that counts the "living" cells around a cell.
When I visualize the number of living neighbors of each cell in a the same grid pattern, the expected output and the actual output are:
EXPECTED: ACTUAL:
0 0 0 0 0 0 0 0 0 0
0 1 1 1 0 0 1 1 1 0
0 1 0 1 0 0 1 0 0 0
0 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
I know the problem is that the method countLivingNeighbors doesn't count a "living" cell if its position is on the left, above-right, above, or above-left of the current cell. But I'm pretty sure the logic of my code is alright, I think.
For reference, here's the code for the method:
// 'true' means living, 'false' means dead
static int countLivingNeighbors(boolean[][] board, int posX, int posY) {
int counter = 0;
// Iterate around the cell
for (int j = -1; j <= 1; j++) {
if (posY + j < 0 || posY + j >= board.length) continue;
for (int i = -1; i <= 1; i++) {
if (posX + i < 0 || posX + i >= board[0].length) continue;
if (board[posY + j][posX + i]) ++counter;
}
}
// It counts the current cell as well, so let's remove that.
if (board[posY][posX]) --counter;
return counter;
I don't think I have problems with the code except for this which stomps me for quite a while now. Any help is much appreciated.
Here's the current version of the entire code.
package GameOfLife;
import java.util.Random;
public class Main {
public static void main(String[] args){
int boardWidth = 5, boardHeight = 5;
boolean[][] board = {{false, false, false, false, false},
{false, false, false, false, false},
{false, false, true , false, false},
{false, false, false, false, false},
{false, false, false, false, false}};
renderBoard(board);
System.out.println();
board = getNextBoardState(board);
renderBoard(board);
}
static boolean[][] createRandomBoard(int width, int height) {
boolean[][] board = new boolean[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
switch (new Random().nextInt(2)) {
case 0 -> board[i][j] = false;
case 1 -> board[i][j] = true;
}
}
}
return board;
}
static void renderBoard(boolean[][] board) {
for (boolean[] cellRows : board) {
for (boolean cells : cellRows) {
if (cells) System.out.print(" 0 ");
else System.out.print(" . ");
} System.out.println();
}
}
static boolean[][] getNextBoardState(boolean[][] board) {
boolean[][] nextBoard;
nextBoard = board;
for (int y = 0; y < board.length; y++) {
for (int x = 0; x < board[0].length; x++) {
int livingNeighbors = countLivingNeighbors(board, x, y);
System.out.print(" " + livingNeighbors + " ");
nextBoard[y][x] = setNextCellState(livingNeighbors, board[y][x]);
} System.out.println();
} System.out.println();
return nextBoard;
}
static int countLivingNeighbors(boolean[][] board, int posX, int posY) {
int counter = 0;
for (int j = -1; j < 2; j++) {
if (posY + j < 0 || posY + j >= board.length) continue;
for (int i = -1; i < 2; i++) {
if (posX + i < 0 || posX + i >= board[0].length) continue;
if (board[posY + j][posX + i]) ++counter;
}
}
if (board[posY][posX]) --counter;
return counter;
}
static boolean setNextCellState(int livingNeighbors, boolean cellState) {
if (cellState) {
if (livingNeighbors <= 1 || livingNeighbors > 3) return false;
} else {
if (livingNeighbors == 3) return true;
}
return cellState;
}
}
In the getNextBoardState method you are assigning nextBoard = board.
static boolean[][] getNextBoardState(boolean[][] board) {
boolean[][] nextBoard;
nextBoard = board;
It's natural to think that this should copy all of the values in the board array into a new array called nextBoard. But in fact, it creates a new pointer called nextBoard, which points to the same array as board. This means that when you change a value in nextBoard, you are in fact changing the same value pointed to by board.
To get around this, make a method that copies values from the board into a new board. Here's a very simple example (which has some pitfalls of its own):
private static boolean[][] copyBoard(boolean[][] board) {
boolean[][] newBoard = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
newBoard[i][j] = board[i][j];
}
}
return newBoard;
}
Then in getNextBoardState, replace
boolean[][] nextBoard;
nextBoard = board;
with
boolean[][] nextBoard = copyBoard(board);
You should get the result you expect:
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 1 1 0
0 0 0 0 0
Note: the copyBoard method assumes that board always has at least one inner array (board[0]) and that all of board's inner arrays have the same length as the array at board[0].

formatting a multiplication table with line spacing

I'm trying to make a multiplication table which is as big as the user specifies. The problem I'm having is with the format. The output right now prints all the numbers to one line, whereas I want it all on multiple lines on a nice neat table. With it formatted as it is, I can't tell where the \n would go to do so, or if there is another way.
here's my code:
import java.util.*;
public class question2 {
public static void main(String [] args) {
Scanner keyb = new Scanner(System.in);
int i = 0;
while (i<=0 || i>=11) {
System.out.print("please enter an integer between 1 and 10: ");
i = keyb.nextInt();
}
for (int x = 1; x <= i; x++) {
System.out.printf("%4d",x);
for (int y = 1; y <= i; y++){
System.out.printf("%4d",x*y);
}
}
}
}
EDIT:
The output for integer 5, prints like this:
1 1 2 3 4 5 2 2 4 6 8 10 3 3 6 9 12 15 4 4 8 12 16 20 5 5 10 15 20 25
After the second for loop, add a new line \n:
for (int x = 1; x <= i; x++) {
System.out.printf("%4d",x);
for (int y = 1; y <= i; y++){
System.out.printf("%4d",x*y);
}
System.out.println();
}
You should add a newline after the second for loop, and since you print x don't print x * 1. So,
for (int x = 1; x <= i; x++) {
System.out.printf("%4d", x);
for (int y = 2; y <= i; y++) {
System.out.printf("%4d", x * y);
}
System.out.println();
}
or you could eliminate the first print like,
for (int x = 1; x <= i; x++) {
for (int y = 1; y <= i; y++) {
System.out.printf("%-4d", x * y); // and simply for variety, left-aligned
}
System.out.println();
}
or if you are using Java 8+, you might use IntStream like
IntStream.rangeClosed(1, i).forEachOrdered(x -> {
IntStream.rangeClosed(1, i).forEachOrdered(y -> System.out.printf(
"%-4d", x * y));
System.out.println();
});
Try the following. My screen only fits 14 numbers neatly. I make a list (it can house empty space '') and then I start to display the list neatly using the end='\t' argument keyword to create tabs.
n = int(input('Enter a number(max 14): '))
# n = 12
list_x = list(range(1,n + 1))
list_y = list(range(1,n + 1))
list_z = ['',] + list_x
for y in list_y:
list_z.append(y)
for x in list_x:
x = x*y
list_z.append(x)
count = 0
for i in list_z:
print(i, end='\t')
count += 1
if count == (n + 1):
count = 0
print('', end='\n',)

Java: How to move a knight on a chessboard until no possible moves are left

I have an assignment to have a knight move around the chessboard until it either completes a full tour or has no where else to go.
im having a problem figuring out how to have it actually stop after there are no more moves. I have the algorithm for the movement down, as well as bounds checking on the chessboard.
setting the loop count to 64 just times out, because the program will try to continually find a spot that doesn't exist if a perfect tour isn't created.
two ideas I have had to fix this is to either increment a variable every time a certain position is checked around a certain spot, and if all possible moves are taken by a previous move, terminate the program. Problem is I have no idea how to actually do this.
A second idea I had is to have the program quit the for loop after 2 seconds(during which the for loop will check each position way more than once) but I feel like my professor would crucify me upside down if I did that
here is my code:
import apcslib.*; //this is only for Format()
public class ktour
{
int[][] kboard = new int[9][9];
int[] vert = new int[9];
int[] horiz = new int[9];
ktour()
{
vert[1] = -2;vert[2] = -1;vert[3] = 1;vert[4] = 2;vert[5] = 2;vert[6] = 1;vert[7] = -1;vert[8] = -2;
horiz[1] = 1;horiz[2] = 2;horiz[3] = 2;horiz[4] = 1;horiz[5] = -1;horiz[6] = -2;horiz[7] = -2;horiz[8] = -1;
path();
}
public void path()
{
int row = 1;
int col = 1;
int loops = 10; //i have this set to 10 for now
int col2 = 1;
int row2 = 1;
int r = (int)(Math.random() * (8) +1); //returns a random from 1 to 9
//System.out.println(r);
kboard[col][row] = 1;
for(int x = 2; x < loops; x++) //this runs the bounds check and places each number for the amount that loops is
{
r = (int)(Math.random() * (8) +1);
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
while(col <= 0 || col > 8 || row <= 0 || row > 8) //bounds check, will keep running until both row and columb is in the board
{
r = (int)(Math.random() * (8) + 1);
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
}
if(kboard[col][row] == 0)
{
kboard[col][row] = x;
row2 = row;
col2 = col;
}
else
{
x--; //if the above if is false and a number already occupies the generated spot, x is decremented and the program tries again
}
}
printboard();
}
public void printboard()
{
for(int y = 1; y < 9; y++)
{
System.out.println();
for(int x = 1; x < 9; x++)
{
System.out.print(Format.right(kboard[y][x],3));
}
}
}
}
I was able to fix my lab with the following code. I created a variable called count which I used to check if at any move there were no more moves left. As there are only 8 moves, when the variable reached 9 the code terminated, and printed up to the point it got to.
I had to put multiple if statements excluding r = math.random if count was not 0, meaning I was checking r 1-9, aka every possible move. Therefore, I couldn't use a randomizer, I had to traverse all 8 possible moves.
I also ran into problems when I reached the line where it checks if kboard[col][row] == 0. if you were running through a loop with count greater than 1, it was possible that col or row could be out of bounds, due to lack of a randomizer in the bounds checker. If left without a break, the bounds checker would run forever without a random number generated every time. I fixed this by adding an if statement that allowed the program to proceed if col and row were inside the board. if they were not, x was decremented and count was increased again, signifying a failed attempt.
This way I was able to check all possible moves, disregarding whether or not they were inside the board.
public void path()
{
int row = 1;
int col = 1;
int loops = 64; //i have this set to 10 for now
int col2 = 1;
int row2 = 1;
int count = 0;
boolean end = false;
int r = (int)(Math.random() * (8) +1); //returns a random from 1 to 9
//System.out.println(r);
kboard[col][row] = 1;
for(int x = 2; x < loops; x++) //this runs the bounds check and places each number for the amount that loops is
{
if(count == 0)
r = (int)(Math.random() * (8) +1);
if(count >= 1 && r != 8)
r++;
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
while(col <= 0 || col > 8 || row <= 0 || row > 8) //bounds check, will keep running until both row and columb is in the board
{
if(count == 0)
r = (int)(Math.random() * (8) + 1);
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
if(count >= 1)
break;
}
end = false;
if(r == 8 || r == 9)
r = 1;
if(count >= 9)
{
System.out.println("Halting... no where else to go");
loops = 0;
}
if(!(col <= 0 || row <= 0 || row > 8 || col > 8))
{
if(kboard[col][row] == 0)
{
kboard[col][row] = x;
row2 = row;
col2 = col;
count = 0;
}
else
{
count++;
x--; //if the above if is false and a number already occupies the generated spot, x is decremented and the program tries again
}
}
else
{
count++;
x--;
}
}
printboard();
}

Rotating sequential numbers to right

Its easy enough to rotate numbers to the left. I would do the following:
int numberCount = 4;
int rotationCount = 2 * numberCount;
for(int i = 0; i < rotationCount; i++)
{
for(int j = 0; j < numberCount; j++)
{
System.out.print((i+j) % numberCount + " ");
}
System.out.println();
}
In this example the following would be printed:
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
How would you do the same thing, but rotating the numbers to the right?
The answer was obvious once I thought about it-- to move a number left, you add to it, so to move right, you subtract from it. I thought the formula would be significantly changed, so I was thinking of formulas that were much more complicated than the solution turned out to be.
// ensures mod is positive
int mod(int a, int b)
{ return (a%b+b)%b; }
int numberCount = 4;
int rotationCount = 2 * numberCount;
for(int i = 0; i < rotationCount; i++)
{
for(int j = 0; j < numberCount; j++)
{
System.out.print(mod((j-i), numberCount) + " ");
}
System.out.println();
}

How to print out an X using nested loops

I have searched through to find a simple solution to this problem.
I have a method called
printCross(int size,char display)
It accepts a size and prints an X with the char variable it receives of height and width of size.
The calling method printShape(int maxSize, char display) accepts the maximum size of the shape and goes in a loop, sending multiples of 2 to the printCross method until it gets to the maximum.
Here is my code but it is not giving me the desired outcome.
public static void drawShape(char display, int maxSize)
{
int currentSize = 2; //start at 2 and increase in multiples of 2 till maxSize
while(currentSize<=maxSize)
{
printCross(currentSize,display);
currentSize = currentSize + 2;//increment by multiples of 2
}
}
public static void printCross(int size, char display)
{
for (int row = 0; row<size; row++)
{
for (int col=0; col<size; col++)
{
if (row == col)
System.out.print(display);
if (row == 1 && col == 5)
System.out.print(display);
if (row == 2 && col == 4)
System.out.print(display);
if ( row == 4 && col == 2)
System.out.print(display);
if (row == 5 && col == 1)
System.out.print(display);
else
System.out.print(" ");
}
System.out.println();
}
}
Is it because I hardcoded the figures into the loop? I did a lot of math but unfortunately it's only this way that I have been slightly close to achieving my desired output.
If the printCross() method received a size of 5 for instance, the output should be like this:
x x
x x
x
x x
x x
Please I have spent weeks on this and seem to be going nowhere. Thanks
The first thing you have to do is to find relationships between indices. Let's say you have the square matrix of length size (size = 5 in the example):
0 1 2 3 4
0 x x
1 x x
2 x
3 x x
4 x x
What you can notice is that in the diagonal from (0,0) to (4,4), indices are the same (in the code this means row == col).
Also, you can notice that in the diagonal from (0,4) to (4,0) indices always sum up to 4, which is size - 1 (in the code this is row + col == size - 1).
So in the code, you will loop through rows and then through columns (nested loop). On each iteration you have to check if the conditions mentioned above are met. The logical OR (||) operator is used to avoid using two if statements.
Code:
public static void printCross(int size, char display)
{
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (row == col || row + col == size - 1) {
System.out.print(display);
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
Output: (size = 5, display = 'x')
x x
x x
x
x x
x x
Instead of giving a direct answer, I will give you some hints.
First, you are right to use nested for loops.
However as you noticed, you determine when to print 'x' for the case of 5.
Check that 'x' is printed if and only if row = col or row + col = size - 1
for your printCross method, try this:
public static void printCross(int size, char display) {
if( size <= 0 ) {
return;
}
for( int row = 0; row < size; row++ ) {
for( int col = 0; col < size; col++ ) {
if( col == row || col == size - row - 1) {
System.out.print(display);
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
ah, I got beaten to it xD
Here's a short, ugly solution which doesn't use any whitespace strings or nested looping.
public static void printCross(int size, char display) {
for (int i = 1, j = size; i <= size && j > 0; i++, j--) {
System.out.printf(
i < j ? "%" + i + "s" + "%" + (j - i) + "s%n"
: i > j ? "%" + j + "s" + "%" + (i - j) + "s%n"
: "%" + i + "s%n", //intersection
display, display
);
}
}
Lte's try this simple code to print cross pattern.
class CrossPattern {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the number of rows=column");
int n = s.nextInt();
int i, j;
s.close();
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (j == i) {
System.out.print("*");
} else if (j == n - (i - 1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

Categories