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;
}
Related
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();
}
}
}
}
I have coded for Sudoku puzzle in Java. The thing is my code has limitation for giving inputs for 9*9 grid. How do I make my code adaptable for all the grids. Please have patience. I am new to java.
What changes do I need to make so that the code can run on all grid sizes?The grid is square not a rectangle.
class Solution {
public void solveSudoku(char[][] board) {
if(solveSudoku2(board)) {
return;
}
}
public boolean solveSudoku2(char[][] board) {
boolean isEmpty = true;
int row = -1;
int col = -1;
int n = board.length;
//this code is used to check if there exists any empty cell in sudoku board
//if there is any empty cell, that means we are not done yet and we need to solve it further,
// so we cannot return true at any point until all the cells are full
//by empty cell, I mean cells having '.' as the value
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(board[i][j] == '.') {
row = i;
col = j;
isEmpty = false;
break;
}
}
if(!isEmpty) {
break;
}
}
if(isEmpty) {
return true;
}
//loop for all the numbers and start placing in the empty cells
//numbers start from 1 to n
for(int num = 1; num <= n; num++) {
//convert number to char
char char_num = (char)(num + '0');
//check if the number we are adding satisfies all the sudoku rules,
// if it does, then we place that number in the cell
if(checkSafe(board,char_num,row,col)) {
board[row][col] = (char)(num + '0');
//using this number in place row,col, we check for all the other empty places and see if the board is returning true or not
// if the board is not filled that means that we need to use other number in row,col place.
//hence backtrack.
if(solveSudoku2(board)) {
return true;
} else {
board[row][col] = '.';
}
}
}
return false;
}
public boolean checkSafe(char[][] board, char num, int row, int col) {
//checkk if num is present in the row
for(int i = 0; i< board.length; i++ ) {
if(board[row][i] == num) {
return false;
}
}
for(int j = 0; j < board[0].length; j++) {
if(board[j][col] == num) {
return false;
}
}
int checknum = (int)Math.sqrt(board.length);
//check for the current grid. grid will be basically checknum*checknum matrix. where every matrix will start from startrow to startrow + checknum having checknum length.
// so, we we have row = 0, then matrix will start from 0 to 2, i.e. the first 3x3 matrix.
// however, we have row = 2, then also the matrix will start from 0 to 2 - the first 3x3 matrix.
//however, if row = 3, then we will start our matrix from 3 and cotinute upto 5.
int startrow = row - row % checknum;
int startcol = col - col % checknum;
for(int k = startrow; k < startrow + checknum; k++) {
for(int l = startcol; l < startcol + checknum; l++) {
if(board[k][l] == num) {
return false;
}
}
}
return true;
}
}
I am trying to return the index of the column which contains the minimum value in a matrix, but so far i can only return the minimum value of the matrix, and can't figure out how to return that column's id. If I try to return "col" it doesn't change anything.
public static int minColIndex (int[][] m) {
int row = m.length, col = m[0].length;
int min = m[0][0];
for (col = 0; col < m.length; col++) {
for (row = 0; row < m[col].length; row++) {
if (min > m[col][row]) {
min = m[col][row];
}
}
}
return min;
}
In your code, the value of col will always be m.length - 1 after the outer loop completes. You need to store the minimum column somewhere, e.g.,
public static int minColIndex (int[][] m) {
int row = m.length, col = m[0].length;
int min = m[0][0];
int minCol = 0; // extra variable to store minimumm column
for (col = 0; col < m.length; col++) {
for (row = 0; row < m[col].length; row++) {
if (min > m[col][row]) {
min = m[col][row];
minCol = col; // remember the minimum column as well as minimum
}
}
}
return minCol; // return minimum column, not col
}
There's also no need for row and col to have initial values set before the loop, so you can change the first few lines of the method to be the following, for slightly greater clarity:
public static int minColIndex (int[][] m) {
int min = m[0][0];
int minCol = 0; // extra variable to store minimumm column
for (int col = 0; col < m.length; col++) {
for (int row = 0; row < m[col].length; row++) {
... etc.
public static int minColIndex (int[][] m) {
int row = m.length, col = m[0].length , int index = 0;
int min = m[0][0];
for (col = 0; col < m.length; col++) {
for (row = 0; row < m[col].length; row++) {
if (min > m[col][row]) {
min = m[col][row];
index= col;
}
}
}
return index;
}
If(min< m[c][r]){
min=[c][r];
save=c;
} '
Define these variables.
int rowOfMinValue = 0;
int colOfMinValue = 0;
And then,
Change:
if (min > m[col][row]) {
min = m[col][row];
}
To:
if (min > m[col][row]) {
min = m[col][row];
rowOfMinValue = row;
colOfMinValue = col;
}
now, you have min values row and column in hand.
Suggestion:
You have wrongly pointing row and col in a matrix. On an m x n matrix, m and n represent rows and columns respectively. And hence, in a m[][] matrix, each of [] represent row and col respectively in sequence.
If value 6 is in 2nd row, 4th col, then we write as
row=1;
col=3;
value = 6;
m[ row ][ col ] = value;
I need to write a short program on how to add two matrices.. The first matrix should look like this:
1 2 3 4 5 6 7 8 9 10
11 12 13.......19 20
21................30
31................40
41................50
etc..
91...............100
But I don't really come to a solution how to increment the first array.. :S
Here is what I got so far:
package uebung05;
public class MatrixAddition
{
public static void main(String[] argv)
{
int firstArray[][] = new int[10][10];
int secondArray[][] = new int[10][10];
int ergArray[][] = new int[10][10];
System.out.println("Matrix 1\n----------------------------");
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
// Increment Array here???
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nMatrix 2\n----------------------------");
// Dekrementieren der zweiten Matrix
for(int row = 0; row < secondArray.length; row++)
{
for(int column = 0; column < secondArray[row].length; column++)
{
// Array mit Werten befüllen
secondArray[row][column] = column + 1;
System.out.print(secondArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nAddition beider Matrizen\n----------------------------");
// Addition firstArray & secondArray
for(int row = 0; row < ergArray.length; row++)
{
for(int column = 0; column < ergArray[row].length; column++)
{
// Addition
ergArray[row][column] = firstArray[row][column] +
secondArray[row][column];
System.out.print(ergArray[row][column] + " ");
}
System.out.println();
}
}
}
Method to add the first and second matrices together:
public static int[][] matrixAdd(int[][] A, int[][] B)
{
// Check if matrices have contents
if ((A.length < 0) || (A[0].length < 0)) return B;
if ((B.length < 0) || (B[0].length < 0)) return A;
// create new matrix to store added values in
int[][] C = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++)
{
for (int j = 0; j < A[i].length; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
But I don't really come to a solution how to increment the first array.
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
firstArray[row][column] = 1+ row*10 + column;
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
Sum two matrices in the new one and return:
public int[][] addMatrixes(int[][] src1, int[][] src2){
int[][] dst = new int[src1.length][src1[0].length];
for(int i=0;i<src1.length;i++){
for(int j=0;j<src1[0].length;j++){
dst[i][j] = src1[i][j] + src2[i][j];
}
}
return dst;
}
Not very generic, but you can define your first matrix with only one easy loop :
int dim = 10;
int size = dim*dim;
int firstArray[][] = new int[dim][dim];
int row, column;
for (int index = 0; index < size; index++ ){
row = index/dim;
column = index%dim;
firstArray[row][column]=row*10+column+1;
System.out.print(String.valueOf(firstArray[row][column])+"\t");
if (column == 9){ System.out.println("");}
}
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.