Program should print out the given values in array1 and print the second array as true or false.
Array1 represents a boardgame where characters can stand at the different positions. The integers indicate how dangerous it is to stand at every position.
If the character finds itself at int 3, it is to be declared dead.
If you add the values of each neighbor(not including the current position) and the total value equals 15 or more, it is also to be declared dead.
dead = false (F)
alive = true (T)
So if the current position is 2 or 1 and the total value of every neighbor is less then 15, the character lives. The neighbors missing in the edge of the array is to be counted as 0.
How do i print this the same way as array1 but with boolean values of T or F?
totalavGrannar is the variable that should add all the neighbors total value.
My code so far:
import java.util.Arrays;
public class uppg10{
public static void main(String[] args){
int [][] array1 = {{1,1,2,3,3},
{2,1,1,2,3},
{3,2,2,1,2},
{3,3,3,3,3}};
boolean [][] array2 = new boolean [4][5];
int rows = array1.length;
int cols = array1[0].length;
int totalavGrannar = 0;
array2 = new boolean[rows][cols];
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
System.out.print(String.format("%4d", array1[row][col]));
if ( ( (col+1) % cols ==0) && (col > 0))
System.out.println();
}
}
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
boolean trueorFalse;
if (array1[row][col]<3) {
trueorFalse = true;
array2[row][col] = trueorFalse;
}
else{
trueorFalse = false;
}
row = 1;
col = 1;
for(int offsetRow=row-1; offsetRow<=row+1; offsetRow++){
for(int offsetCol=col-1; offsetCol<=col+1; offsetCol++){
totalavGrannar += array1[offsetRow][offsetCol];
boolean trueorFalse2;
if (totalavGrannar<15) {
trueorFalse2 = true;
array2[row][col] = trueorFalse2;
}
else{
trueorFalse2 = false;
}
}
}
}
}
for (int row=0; row<array2.length; row++) {
for (int col=0; col<array2[row].length; col++) {
System.out.print(String.format("%8s" , array2[row][col] ? "T" : "F"));
if ( ( (col+1) % cols ==0) && (col > 0))
System.out.println();
}
}
}
}
How do i print this the same way as array1 but with boolean values of T or F?
For your question you did it correct in your code.
Your code not work because you have few others problems:
In the second loop you override array2 values even if false(dead).
you make him alive (set to true)
if (totalavGrannar<15) {
trueorFalse2 = true;
array2[row][col] = trueorFalse2;
}
Also, you sum the position with all neighbors (total 9 cells instead of only 8 neighbors)
--> In solution I set condition to exclude the position itself.
Another problem is that when you sum neighbors you check equality to 15 per addition for updat (T/F). This is wasteful.
--> You need to sum all and only then update value (T/F).
In the second loop you reset you loop condition to '1' so you have endless loop.
--> I removed those lines.
You forgot to reset totalavGrannar
A short fix I suggest:
(I also removed some redundant lines)
import java.util.Arrays;
public class uppg10 {
public static void main(String[] args) {
int[][] array1 = {{1, 1, 2, 3, 3},
{2, 1, 1, 2, 3},
{3, 2, 2, 1, 2},
{3, 3, 3, 3, 3}};
int rows = array1.length;
int cols = array1[0].length;
boolean[][] array2 = new boolean[rows][cols];
int totalavGrannar = 0;
//Print array1
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
System.out.print(String.format("%4d", array1[row][col]));
if (((col + 1) % cols == 0) && (col > 0))
System.out.println();
}
}
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (array1[row][col] < 3)
array2[row][col] = true;
//Iterate neighbors to sum values
for (int offsetRow = row - 1; offsetRow <= row + 1; offsetRow++) {
for (int offsetCol = col - 1; offsetCol <= col + 1; offsetCol++) {
if (offsetRow >= 0 && offsetCol >= 0) //0-bounds check
/*if (offsetRow < array1.length && offsetCol < array1.length) //edges-bounds check
if (offsetRow != row && offsetCol != col) { //exclude position from sum
totalavGrannar += array1[offsetRow][offsetCol];
}*/
if (offsetRow < array1.length && offsetCol < array1[0].length) //edges-bounds check
if (offsetRow != row || offsetCol != col) { //exclude position from sum
totalavGrannar += array1[offsetRow][offsetCol];
}
}
}
if (totalavGrannar >= 15)
array2[row][col] = false;
totalavGrannar = 0;
}
}
for (int row = 0; row < array2.length; row++) {
for (int col = 0; col < array2[row].length; col++) {
System.out.print(String.format("%8s", array2[row][col] ? "T" : "F"));
if (((col + 1) % cols == 0) && (col > 0))
System.out.println();
}
}
}
}
Related
I have to write a program that reads a file containing set of 16 numbers and creates a magic square. A magic square is one where the sum of each row, column, and diagonal is the same. I have to use the sentinel method to control your loop. The sentinel value is -999. When I run the code it shows that all are not magic square. When I run it it looks like the following.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
NOT a magic square
1 15 14 4
12 6 7 9
8 10 11 5
13 3 2 16
NOT a magic square
30 8 20 11
3 10 21 35
24 25 13 7
12 26 15 16
NOT a magic square
14 8 19 92
37 53 16 27
67 10 54 2
15 62 44 12
NOT a magic square
2 5 6 1
8 5 2 9
4 5 6 7
3 2 7 5
NOT a magic square
The following is the code.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
class square {
public static void main(String[] args) throws IOException {
File data = new File("Lab8Data.txt");
Scanner input = new Scanner(data);
int[][] array = new int[4][4];
int[] rowTotal = new int[4];
int[] columnTotal = new int[4];
for (int row = 0; row < array.length; row++)
array[0][row] = input.nextInt();
while (array[0][0] != -999) {
for (int column = 1; column < array.length; column++)
for (int row = 0; row < 4; row++)
array[column][row] = input.nextInt();
for (int column = 0; column < array.length; column++) {
for (int row = 0; row < array.length; row++)
System.out.print(array[column][row] + " ");
System.out.println();
}
for (int column = 0; column < array.length; column++)
for (int row = 0; row < array.length; row++)
rowTotal[column] += array[column][row];
for (int row = 0; row < array.length; row++)
for (int column = 0; column < array.length; column++)
columnTotal[row] += array[column][row];
int diagonalOne = 0;
for(int row = 0; row < array.length; row++)
diagonalOne = diagonalOne + array[row][row];
int otherDiagonal = 0;
for (int row = 0; row < array.length; row++) {
otherDiagonal = otherDiagonal + array[row][Math.abs(3 - row)];
int rows = rowTotal[0];
boolean rowEqual = true;
for (int r = 0; r < array.length; r++)
if (rowTotal[r] != r)
rowEqual = false;
int col = columnTotal[0];
boolean columnEqual = true;
for (int column = 0; column < array.length; column++)
if (rowTotal[column] != col)
columnEqual = false;
int diagonal = diagonalOne;
boolean diagonalEqual = true;
if (otherDiagonal != diagonal)
diagonalEqual = false;
boolean isMagic = false;
if (rowEqual && columnEqual && diagonalEqual)
if (rows == col && col == diagonal)
isMagic = true;
if (isMagic)
System.out.println("Is a magic square");
else
System.out.println("NOT a magic square");
for (int r = 0; r < 4; r++)
array[0][r] = input.nextInt();
}
}
}
}
This should be a magic square.
1 15 14 4
12 6 7 9
8 10 11 5
13 3 2 16
What should I do to make it print if the square is magic correctly.
I initialize the variables inside the loop, otherwise the totals will not be correct:
while (true) {
int[][] array = new int[4][4];
int[] rowTotal = new int[4];
int[] columnTotal = new int[4];
the first number you read is either the sentinel, or array[0][0]:
int number = input.nextInt();
if (number == -999) {
break;
}
array[0][0] = number;
Now you need to read the remainder of row 0:
for (int column = 1; column < array[0].length; column++) {
array[0][column] = input.nextInt();
}
and then the other rows:
for (int row = 1; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
array[row][column] = input.nextInt();
}
}
Now, the calculations; column totals:
for (int column = 0; column < array.length; column++) {
for (int row = 0; row < array.length; row++) {
columnTotal[column] += array[row][column];
}
}
row totals:
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array.length; column++) {
rowTotal[row] += array[row][column];
}
}
diagonals:
int diagonalOne = 0;
for (int row = 0; row < array.length; row++) {
diagonalOne += array[row][row];
}
int otherDiagonal = 0;
for (int row = 0; row < array.length; row++) {
otherDiagonal += array[row][array.length - row - 1];
}
then the comparisons:
int row = rowTotal[0];
boolean rowEqual = true;
for (int r = 0; r < array.length; r++) {
if (rowTotal[r] != row) {
rowEqual = false;
}
}
int col = columnTotal[0];
boolean columnEqual = true;
for (int column = 0; column < array.length; column++) {
if (columnTotal[column] != col) {
columnEqual = false;
}
}
int diagonal = diagonalOne;
boolean diagonalEqual = true;
if (otherDiagonal != diagonal) {
diagonalEqual = false;
}
boolean isMagic = false;
if (rowEqual && columnEqual && diagonalEqual) {
if (row == col && col == diagonal) {
isMagic = true;
}
}
if (isMagic) {
System.out.println("Is a magic square");
} else {
System.out.println("NOT a magic square");
}
Of course you wouldn't need to store the totals in arrays: you could just compare them as you compute them.
int sum = 0;
for (int row = 0; row < array.length; row++) {
sum += array[row][row];
}
boolean isMagic = true;
int magicNumber = sum;
sum = 0;
for (int row = 0; row < array.length; row++) {
sum += array[row][array.length - row - 1];
}
if (sum != magicNumber) {
isMagic = false;
}
for (int column = 0; column < array.length; column++) {
sum = 0;
for (int row = 0; row < array.length; row++) {
sum += array[row][column];
}
if (sum != magicNumber) {
isMagic = false;
}
}
for (int row = 0; row < array.length; row++) {
sum = 0;
for (int column = 0; column < array.length; column++) {
sum += array[row][column];
}
if (sum != magicNumber) {
isMagic = false;
}
}
public class Foo {
public static void main(String... args) throws IOException {
File file = new File("Lab8Data.txt");
int[][] square = readSquareFromFile(file);
boolean magicSquare = isMagicSquare(square);
System.out.println(magicSquare);
}
private static int[][] readSquareFromFile(File file) {
// TODO read from file
return new int[][] {
{ 1, 15, 14, 4 },
{ 12, 6, 7, 9 },
{ 8, 10, 11, 5 },
{ 13, 3, 2, 16 } };
}
private static boolean isMagicSquare(int[][] square) {
int magicNumber = Arrays.stream(square[0]).sum();
return isRowsMagic(square, magicNumber)
&& isColumnsMagic(square, magicNumber)
&& isDiagonalsMagic(square, magicNumber);
}
private static boolean isRowsMagic(int[][] square, int magicNumber) {
for (int row = 0; row < square.length; row++) {
int sum = 0;
for (int col = 0; col < square[row].length; col++)
sum += square[row][col];
if (sum != magicNumber)
return false;
}
return true;
}
private static boolean isColumnsMagic(int[][] square, int magicNumber) {
for (int col = 0; col < square[0].length; col++) {
int sum = 0;
for (int row = 0; row < square.length; row++)
sum += square[row][col];
if (sum != magicNumber)
return false;
}
return true;
}
private static boolean isDiagonalsMagic(int[][] square, int magicNumber) {
return getLeftDiagonalSum(square) == magicNumber && getRightDiagonalSum(square) == magicNumber;
}
private static int getLeftDiagonalSum(int[][] square) {
int sum = 0;
for (int i = 0; i < square.length; i++)
sum += square[i][i];
return sum;
}
private static int getRightDiagonalSum(int[][] square) {
int sum = 0;
for (int row = 0, col = square.length - 1; row < square.length; row++, col--)
sum += square[row][col];
return sum;
}
}
I have a 9x9 sudoku grid and I need to get a random number from every 3x3 square in the grid.
The most awful code would be something like this:
if(square == 0) {
row = random.nextInt(3);
col = random.nextInt(3);
}
if(square == 1) {
row = random.nextInt(3);
col = random.nextInt(3) + 3;
}
if(square == 2) {
row = random.nextInt(3);
col = random.nextInt(3) + 6;
}
if(square == 3) {
row = random.nextInt(3) + 3;
col = random.nextInt(3);
}
if(square == 4) {
row = random.nextInt(3) + 3;
col = random.nextInt(3) + 3;
}
if(square == 5) {
row = random.nextInt(3) + 3;
col = random.nextInt(3) + 6;
}
if(square == 6) {
row = random.nextInt(3) + 6;
col = random.nextInt(3);
}
if(square == 7) {
row = random.nextInt(3) + 6;
col = random.nextInt(3) + 3;
}
if(square == 8) {
row = random.nextInt(3) + 6;
col = random.nextInt(3) + 6;
}
where square is the index of the square in the grid (square = 0,1,...,8)
I cannot figure out how to write it in a better way.
Some ideas? Thanks
This should work for any square size. In your case is 3x3, so size is 3.
int size = 3;
row = random.nextInt(size) + (square / size) * size;
col = random.nextInt(size) + (square % size) * size;
Something like this
int[] rowAdd = new int[] { 0, 0, 0, 3, 3, 3, 6, 6, 6 };
int[] colAdd = new int[] { 0, 3, 6, 0, 3, 6, 0, 3, 6 };
row = random.nextInt(3) + rowAdd[square];
col = random.nextInt(3) + colAdd[square];
Put in one array values which should be added to variable row, name it rowAdd. In second array colAdd put variable which should be added to col.
Finally, use square like the index to fetch correct value for addition.
Of course, arrays rowAdd and colAdd should be part of the method. (It is vast of time and memory to create new arrays every time when you call the method). These arrays should be class related, so they should be static.
This is the code for all things in once
public class Test {
public static void main(String[] args) {
//initializing arrays
int[][] grid = new int[9][9];
int[] numbers = new int[9];
//populating grid
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
grid[i][j] = (int)(Math.random()*10);
}
}
//printing grid
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
System.out.print(grid[i][j]);
}
System.out.println();
}
System.out.println();
int counter = 0;
//first and second loops counts for 0,3,6
for(int i = 0; i < 9; i += 3) {
for(int j = 0; j < 9; j += 3) {
//after taking i or j values(which must be either 0,3 or 6) goes for 3x3 parts and saving those numbers in number array
for(int t = i; t < i+3; t++) {
for(int k = j; k < j+3; k++) {
numbers[counter] = grid[t][k];
counter++;
}
}
//you can pick randomly from numbers array here
//showing which numbers picked
for(int t = 0; t < 9; t++) {
System.out.print(numbers[t]);
}
System.out.println();
System.out.println();
counter = 0;
}
}
}
}
I'm kind of stuck in this algorithm. I have this function below that gets a String and a matrix[n][m].
The String has up to n*m digits, and I need to insert them by reverse from the last digit to the last cell of the matrix, respectively, until I reach the first cell;
For example: the String='3' will be like that {[0][0],[0][3]}; the String='123' will be like that {[0][1],[2][3]}; and the String='2222' will be like that {[2][2],[2][2]};
The issue is: For the String '123' I get a matrix {[1][1],[1][1]}. It seems like only the first digit insert into the matrix.
stringToInteger(String correctBase, int [][] board)
{
int integerNum;
for(int i=correctBase.length()-1; i>=0; i--)
{
integerNum=correctBase.charAt(i)-'0';
for(int row=board.length-1; row>=0; row--)
for(int col=board[row].length-1; col>=0; col--)
board[row][col]=integerNum;
}
Try this:
stringToInteger(String correctBase, int [][] board)
{
int integerNum;
int row = board.length - 1;
int col = board[0].length - 1;
for(int i=correctBase.length()-1; i>=0; i--)
{
integerNum=correctBase.charAt(i)-'0';
board[row][col]=integerNum;
col--;
if(col < 0) {
col = board[0].length - 1;
row--;
}
}
...
}
Yes, or:
int i = correctBase.length();
for(int row=board.length-1; row>=0; row--)
for(int col=board[row].length-1; col>=0; col--)
board[row][col] = i > 0 ? correctBase.get(--i)-'0' : 0;
I would first check if the size of the string matches the size of the matrix. If it does not, then pad said string with zeroes. Then just parse the positions of the string and insert them into the matrix.
Try it like this.
public static void main(String[] args) {
//define size of matrix
int n = 2;
int m = 2;
String input = "3";
//if size of string is less than matrix size we append 0 to it
if (input.length() < n * m) {
int diff = n * m - input.length();
for (int i = 0; i < diff; i++)
input = "0" + input; //pad zeroes to the string
}
int board[][] = new int[n][m]; //declare matrix
//populate matrix
int stringPosition = 0; //position in the string starting from the left
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
board[i][j] =
Character.getNumericValue(input.charAt(stringPosition)); //transfrom char to int, then assign it to matrix
stringPosition++; //increment position
}
}
//display matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.println("board[" + i + "][" + j + "] = " + board[i][j]);
}
}
}
It produces the desired results
input="3"
board[0][0] = 0
board[0][1] = 0
board[1][0] = 0
board[1][1] = 3
input="123"
board[0][0] = 0
board[0][1] = 1
board[1][0] = 2
board[1][1] = 3
input="2222"
board[0][0] = 2
board[0][1] = 2
board[1][0] = 2
board[1][1] = 2
So i want to create a program that will print true or false depending on the values of the array. If the values in the 2d array (row and column) each equal 15. so the values in the row equal 15 and the values in the column equal 15. My code so far:
public static boolean isAmazingArray(int[][] array) {
int rowTemp = 0;
int colTemp = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
rowTemp += array[row][0];
colTemp += array[0][col];
}
if (rowTemp == 15 && colTemp == 15) {
return true;
}
}
return false;
}
Simple for iteration can do this. Notably, however, this requires that the array is non-jagged (array[i].length == array[0].length for all i in range). If this isn't the case it could still be valid, but the problem becomes a bit more interesting.... fixing...
public static boolean isAmazingArray(int[][] array) {
final int VALID_VAL = 15;
//Check Rows - handle jagged rows without issue
for (int[] row : array) {
int a = 0;
for(int i : row) {a += i;}
if(a != VALID_VAL) return false; //Found a bad row
}
//Check Cols - handle jagged-ness by finding max length row first.
int maxRowLength = 0;
for(int[] i : array){
maxRowLength = Math.max(maxRowLength, i.length);
}
//Init array to hold running sum for each column
int[] colSums = new int[maxRowLength];
for(int r = 0; r < array.length; r++){
for(int c = 0; c < array[r].length; c++){
//Add value to its corresponding column sum
colSums[c] += array[r][c];
}
}
for(int i : colSums){
//Found bad column
if(i != VALID_VAL) return false;
}
//No invalid rows/cols found
return true;
}
I have spent quite a while trying to write a program to implement Conway's game of life - Link with more info. . I am following some online guides and was given the majority of the functions. I wrote the "next" and "neighbours" methods shown below. Could anyone tell me if these are good implementations, and how they could be made better please ?
The point of the exercise was to not modify or change any of the other methods and just write the next method ! :)
import java.io.*;
import java.util.Random;
public class Life {
private boolean[][] cells;
public static void main( String[] args ) {
Life generation = new Life( );
for (int i = 0; i != 10; i++) {
System.out.println( generation );
generation.next( );
}
}
// Constructors
public void next (){
int SIZE;
SIZE=cells.length;
boolean[][] tempCells = new boolean [SIZE] [SIZE];
for( int i=0; i<SIZE; i++ ) {
for( int j=0; j<SIZE; j++ ) {
tempCells[i][j] = cells[i][j];
}
}
for (int row = 0; row < cells.length ; row++)
{
for (int col = 0 ; col < cells[row].length ; col++)
{
if ( neighbours(row, col) > 3 || neighbours(row, col) < 2 )
{
tempCells[row][col] = false;
}
else if (neighbours(row, col) == 3 )
{
tempCells[row][col] = true;
}
}
}
cells = tempCells;
}
public int neighbours (int row, int col) {
int acc=0;
for ( int i = row -1; i <= row + 1 ; i++)
{
for (int j = col -1 ; j <= col + 1 ; j++)
{
try {
if (cells[i][j]==true && (i != row || j!=col))
{
acc++;
}
} catch ( ArrayIndexOutOfBoundsException f)
{continue;}
}
}
return acc;
}
// Initialises 6 * 6 grid with Glider pattern.
public Life( ) {
final int SIZE = 8;
// Arguably, this should have been a class (static) array.
final int[][] pairs = {{2,4},{3,3},{1,2},{2,2},{3,2}};
cells = new boolean[ SIZE ][ ];
for (int row = 0; row < SIZE; row ++) {
cells[ row ] = new boolean[ SIZE ];
}
for (int pair = 0; pair < pairs.length; pair ++) {
final int row = pairs[ pair ][ 0 ];
final int col = pairs[ pair ][ 1 ];
cells[ row ][ col ] = true;
}
}
// Initialise size * size grid with random cells.
//public Life( int size ) {
//final Random rand = new Random( );
//cells = new boolean[ size ][ ];
//for (int row = 0; row < size; row ++) {
//cells[ row ] = new boolean[ size ];
//for (int col = 0; col < size; col ++) {
//cells[ row ][ col ] = (rand.nextInt( 2 ) == 0);
//}
//}
//}
// Public methods and helper methods.
#Override
public String toString( ) {
String result = "";
for (int row = 0; row < cells.length; row ++) {
final boolean[] column = cells[ row ];
for (int col = 0; col < column.length; col ++) {
result = result + (column[ col ] ? "x" : ".");
}
result = result + "\n";
}
return result;
}
}
You don't need to copy the contents of cells to tempCells (the first nested loop in next). Instead, you can add one extra clause to the if-else in the next loop. Also, storing the result from neighbours may be a good idea for both speed and clarity.
for (int row = 0; row < cells.length ; row++)
for (int col = 0 ; col < cells[row].length ; col++) {
int n = neighbours(row,col);
if (n > 3 || n < 2)
tempCells[row][col] = false;
else if (n == 3)
tempCells[row][col] = true;
else
tempCells[row][col] = cells[row][col];
}
(Apart from that, looks fine, but I haven't run and tested your code.)
Don't use ArrayIndexOutOfBoundException to compute out-of-boundary (OOB) conditions. It kills performance. Better use the wrap-around mechanism to treat your array like a sphere so that you don't encounter OOBs at all. You could try something like this:
public Cell[] getNeighbours(int i, int j) {
int i2 = i - 1, i3 = i + 1, j2 = j - 1, j3 = j + 1;
if (i2 == -1) i2 = board.length - 1;
if (i3 == (board.length)) i3 = 0;
if (j2 == -1) j2 = board[i].length - 1;
if (j3 == (board[i].length)) j3 = 0;
return new Cell[]{board[i2][j2], board[i2][j], board[i2][j3], board[i][j2], board[i][j3], board[i3][j2], board[i3][j], board[i3][j3]};
}
Then you can loop through the returned array and check how many of those are alive and return that count.