Neighbors in a 2D 4x4 Array - java

Alright... So I've been stuck with an exercise for school for a little while now and I really can't figure out how to solve it. I think I've come really compared to where I started and I hope you guys could help me out.
The final meaning of the exercise would be that the code will output all the neighbors possible of every single digit in the array. I've done the middle four ones, they work perfectly. The outer digits are a pain for me, I can't find a way to make sure to make the code 'notice' that there are no more digits, for example, above the digit in the upper left corner.
I feel like I know how to do it: with an if statement that doesn't let something happen if the value of the index of the array is higher than 3 or lower than 0. Because it's a 4x4 2D Array that means there are 0, 1, 2, 3 indexes for the X Axis and Y Axis.
I hope someone here is willing to help me out. It will be greatly appreciated! Here's my code for so far!
Thanks in advance
public class P620 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int[][] counts =
{
{ 1, 0, 3, 4},
{ 3, 5, 6, 4 },
{ 9, 7, 1, 4},
{ 1, 1, 1, 1}
};
for(int i = 0; i <= 3; i++) {
for(int j = 0; j <= 3; j++) {
System.out.println("Neighbours van de array: " + i + j + " met waarde: " + counts[i][j]);
if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i - 1][j]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i - 1][j - 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i - 1][j + 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i][j - 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i + 1][j - 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i + 1][j]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i + 1][j + 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i][j + 1]);
}
else {
}
}
}
}
}

Here's a little hint:
for (int i=0; i < 4; ++i) {
for (int j=0; j<4; ++j) {
System.out.println("Neighbours van de array: " + i + j + " met waarde: " + counts[i][j]);
// print upper-left (northwest) neighbor, if there is one
if (i >= 1 && j >= 1)
System.out.println(counts[i-1][j-1]);
// print upper (north) neighbor, if there is one
if (i >= 1)
System.out.println(counts[i-1][j]);
.
.
.
// print lower (south) neighbor, if there is one
if (i < 3)
System.out.println(counts[i+1][j]);
// print lower-right (southeast) neighbor, if there is one
if (i < 3 && j < 3)
System.out.println(counts[i+1][j+1]);
}
}

Related

Finding adjacent matrix: Java.lang.ArrayIndexOutOfBoundsException

I am trying to find all adjacent elements in the matrix. Adjacent refers to elements being right beside each other either horizontal, vertical and diagonal elements. However it is giving me java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5. I am not sure why, any help would be much appreciated! Also the program needs to be recursive !
class matrixAdjacent
{
public static void main(String[] args)
{
char grid[][] = {{'0','0','0','1','1','0','1','1','0','0','0','1','1','1','0','1','1','1','0','1'},
{'1','0','0','0','0','1','0','0','0','1','0','0','0','0','0','1','1','1','1','1'},
{'0','1','0','0','1','0','0','0','1','0','1','0','0','0','0','0','0','1','1','1'},
{'1','1','1','0','0','1','0','1','0','0','0','0','1','0','1','1','0','1','1','0'},
{'0','1','1','1','0','1','1','1','0','1','0','0','1','0','1','0','1','1','0','1'}};
ExploreAndLabelColony(grid, 0, 0);
}
private static void ExploreAndLabelColony(char[][] grid, int i, int j)
{
// TODO Auto-generated method stub
if(grid==null)
{
return;
}
if(i==grid.length || j==grid[0].length)
{
return;
}
if (grid[i][j] == '1') //checks if theres a 1 which refers to a colony
{
if (i>0 && i + 1 < grid.length && j>0 && j + 1 < grid[0].length)
{
if (grid[i+1]==grid[j] || grid[i] == grid[j+1] || grid[i-1]==grid[j] || grid[i]==grid[j-1]) //checks if adjacent
{
grid[i][j] = 'A'; //creates a colony
}
}
}
else if(grid[i][j] == '0') //replaces 0 with '-'
{
grid[i][j] = '-';
}
System.out.print(grid[i][j]); //print grid
if(j==grid[0].length-1)
{
System.out.println(); //prints next row
ExploreAndLabelColony(grid,i+1,0); //recurse to increment row
}
ExploreAndLabelColony(grid,i,j+1); //recurse to increment column
}
}
Issues
if (i>0 && i + 1 < grid.length && j>0 && j + 1 < grid[0].length)
{
if (grid[i+1]==grid[j] || grid[i] == grid[j+1] || grid[i-1]==grid[j] || grid[i]==grid[j-1]) //checks if adjacent
{
grid[i][j] = 'A'; //creates a colony
}
}
In the above section of code, j>0 && j + 1 < grid[0].length can not guarantee the access to grid[j].
The check on inner array index can not correctly validate the access to outer array index.
Check adjacent elements
To check adjacent elements, all 4 valid adjacent indices have to be checked
grid[i][j - 1]
grid[i][j + 1]
grid[i - 1][j]
grid[i + 1][j]
In the above 4 checks, please validate the index before making any of the i - 1, i + 1, j - 1, j + 1 access.
For the given cell with coordinates i, j the adjacent elements are in the square:
[i - 1][j - 1], [i - 1][j], [i - 1][j + 1]
[i ][j - 1], CURR_CELL, [i ][j + 1]
[i + 1][j - 1], [i + 1][j], [i + 1][j + 1]
Additional limitations may be applied using Math.min, Math.max functions and adjacent cells can be detected as follows:
if (grid[i][j] == '1') { //checks if theres a 1 which refers to a colony
out: // label to break
for (int ii = Math.max(i - 1, 0), in = Math.min(grid.length, i + 2); ii < in; ii++) {
for (int jj = Math.max(j - 1, 0), jn = Math.min(grid[0].length, j + 2); jj < jn; jj++) {
if (ii == i && jj == j) {
continue; // skip reference cell
}
if (grid[ii][jj] == '1') {
grid[i][j] = 'A';
break out; // as soon as the first neighbor is found
}
}
}
}
With this change, the output for the given input:
public static void main(String[] args) {
char grid[][] = {
{'0','0','0','1','1','0','1','1','0','0','0','1','1','1','0','1','1','1','0','1'},
{'1','0','0','0','0','1','0','0','0','1','0','0','0','0','0','1','1','1','1','1'},
{'0','1','0','0','1','0','0','0','1','0','1','0','0','0','0','0','0','1','1','1'},
{'1','1','1','0','0','1','0','1','0','0','0','0','1','0','1','1','0','1','1','0'},
{'0','1','1','1','0','1','1','1','0','1','0','0','1','0','1','0','1','1','0','1'}
};
ExploreAndLabelColony(grid, 0, 0);
}
is as follows:
---AA-A1---AA1-AAA-A
A----A---A-----AAAAA
-A--A---A-1------AAA
AAA--A-A----A-AA-AA-
-AA1-AA1-1--1-1-A1-1
Possibly, condition should be fixed to check if adjacent cell is already containing A, or if there are too many neighbors but setting/applying these or any other rules is up to the author.

Can I convert for loop number pattern to while loop and do while loop?

I'm learning java looping, and managed to print a number one pattern using the for loop.
I tried printing the number one pattern using the while and do while loop, but had difficulty. This is my code:
for (int i = 0; i <= 7; i++) {
for (int j = 0; j <= 4; j++) {
if ((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
System.out.print("1");
else
System.out.print(" ");
}
System.out.println();
}
This is my while loop code:
int i = 0, j = 0;
while (i <= 7) {
while (j <= 4) {
if((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
System.out.print("1");
else
System.out.print(" ");
j++;
}
System.out.println();
i++;
}
Need to reset j counter after first j_while end
int i = 0, j = 0;
while (i <= 7)
{
//could also reset here
j=0;
while (j <= 4)
{
if((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
System.out.print("1");
else
System.out.print(" ");
j++;
}
System.out.println();
i++;
}
Yes, any for loop can be converted into a while or do-while.
For example:
for(initialize; condition_check, statement1) {
......
}
Here statement1 => generally this is an increment or decrement of a variable used in the condition_check
Similarly the equivalent while loop would be:
initialize;
while (condition_check) {
.......;
statement1;
}
So it seems that you have forgotten to initialize one of the variables. The other answer has already given you that.
This answer would help in mapping the for loop to the while loop and vice-versa.
Hope it helps.

I am Attempting to Interweave Two One Dimensional Arrays Into a New Array

I am trying to take two one dimensional arrays and interweave them in a new array. For example
a = (1,2,3) & b = (44,55,66,77,88)
taking these two arrays and interweaving them to make
c = (1,44,2,55,3,66,77,88)
I sincerely believed I have solved it but I cannot figure out why this code outputs
c/interleave as 1,44,2,55,66,77,88,0
Code:
public static int[] interleave(int[] a, int[] b)
{
int [] interleave = new int [a.length + b.length];
int j = 0, k = 0;
for (int i = 0; i < (a.length + b.length);i++)
{
if (((i % 2 == 0) || (k >= b.length)) && (j < a.length))
{
interleave[i] = a[j];
j++;
}
if (((i % 2 == 1) || (j >= a.length)) && (k < b.length))
{
interleave[i] = b[k];
k++;
}
You are checking b.length against k and a.length against j. Thus when k becomes 3 your second if will overwrite interleave[i] with b[k]. k and j should be switched:
if (((i % 2 == 0) || (j >= b.length)) && (j < a.length))
{ //^^^
interleave[i] = a[j];
j++;
}
if (((i % 2 == 1) || (k >= a.length)) && (k < b.length))
{ //^^^
interleave[i] = b[k];
k++;
}
Output:
[1, 44, 2, 55, 3, 66, 77, 88]

How to convert integers 0-80 to point coordinates (0,0) -> (8,8)?

I'm coding up a Sudoku solving program and have a double for loop for iterating through all the coordinate points from (0,0) to (8,8), 9x9=81 cells in total. I'm trying to write my values into the cells with a string of digits, but can't find any useful methods apart from .charAt(i), which doesn't work.
I'm using a double for loop (for i = 0; i < 9; i++) and (for j = 0; j < 9; j++) to iterate through my coordinates new Point(i,j).
Does anyone know how to convert integers from 0-80 to point coordinate form (preferably without double for loops).
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (i == 0 && j == 0) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(76, 77));
} else if (i == 0 && j == 1 || i == 1 && j == 0) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(77, 78));
} else if (i == 0 && j < 9 || i == 1 && j == 1 || i >= 2 && j == 0) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(78, 79));
} else if (i == 1 && j < 9 || i >= 2 && j == 1) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(79, 80));
} else if (i >= 2 && j < 9 || i >= 2 && j == 1) {
sb.append(
sudokuPuzzle.getSudokuCell(new Point(j, i)).toString().substring(80, 81));
}
}
}
System.out.println(sb);
// for all sudoku cells
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.println(sb.charAt(i));
int nextValue = sb.charAt(i);
if (nextValue != 0) {
// get next sudoku cell
SudokuCell sudokuCell = sudokuPuzzle.getSudokuCell(new Point(j, i));
// set values
sudokuCell.setValue(nextValue);
sudokuCell.setIsInitial(true);
sudokuPuzzle.removePossibleValue(sudokuCell);
sudokuCell.clearPossibleValues();
sudokuFrame.repaintSudokuPanel();
}
}
}
Just use the mapping i -> (i / 9, i % 9), which corresponds to the normal mapping you'd expect.

how to write a conditional telling java that the array index is invalid

(this is a 2d array filled with objects) So the places marked "//Out of Grid" is where I don't know how to tell java that the index its looking for is not in the grid and to move on.
A basic over view of what im trying to accomplish is go thru each cell starting[0][0] and check all of its adjacent neighbors, as for the first check its neighbors would be [0][1],[1][0], and [1][1]. and then if the age of the object in the index is 0, do something..
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int neighbor_x = x + i;
int neighbor_y = y + j;
if (neighbor_x < 0 || neighbor_x >= board.length) {
// Out of Grid
}
if (neighbor_y < 0 || neighbor_y >= board[neighbor_x].length) {
// Out of Grid
}
if (board[neighbor_x][neighbor_y].age == 0) {
nCount++;
if (board[x + i][y + j].getPreviousValue() == 0)
hCount++;
}
}
}
Unless you want to perform some operations, you can simply leave them out.
Out of bound exception can occur in the case where neighbor_x < 0 and neighbor_y >=0, when the second statement is being ran, the first condition is verified and the second throws an exception. You can simply use the only condition that matters
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int neighbor_x = x + i;
int neighbor_y = y + j;
if ((neighbor_x >=0 && neighbor_x < board.length) &&
(neighbor_y >= 0 && neighbor_y < board[neighbor_x].length) &&
board[neighbor_x][neighbor_y].age == 0 ) {
nCount++;
if (board[x + i][y + j].getPreviousValue() == 0)
hCount++;
}
}
}
If this ever throws an exception, then just separate the conditions comme suite
if ( neighbor_x >=0 && neighbor_x < board.length )
if(neighbor_y >= 0 && neighbor_y < board[neighbor_x].length)
if(board[neighbor_x][neighbor_y].age == 0 )

Categories

Resources