Array sync error (Java) - java

So. I have a problem I simply cant get my head around.
I'm currently making a cellular automaton. (Java)
For this, I have 2 Arrays, one called cells[][] for current states,
and one called cellsX[][] for the temporary state inbetween steps.
at each update i do this:
public void updateCells() {
cellsX = cells;
for(int i = 0; i< Xsize; i++) {
for(int j = 0; j < Ysize; j++) {
cellsX[i][j].Update();
}
}
}
And later I render:
for(int i = 0; i< Xsize; i++) {
for(int j = 0; j < Ysize; j++) {
if(cells[i][j].isAlive()) {
int Colori[] = cells[i][j].GetColor();
g2d.setTransform(identity);
g2d.translate(0, 0);
g2d.setColor(new Color(Colori[0],Colori[1],Colori[2]));
g2d.drawRect((i*5)+20, (j*5)+20, 5, 5);
}
}
}
Right now, I would say nothing should happen, as I newer update cells[][]
but for some reason it do?
How can the cells[i][j] update, when the only cell I've given a command is cellsX[i][j]?
to show you the Update function in the Cell
public void Update() {
if(Info[0][0] > 0) {
Info[0][0] += 1;
Info[0][2] += rand.nextInt(2);
}
Info[1][0] ++;
if(Info[1][0] >255) Info[1][0] =0;
if(Info[0][0] > Info[0][1]) Info[0][0] = 0;
if(Info[0][2] <= 0) Info[0][0] = 0;
}
Its a void an no nothing to affect the outside world (Info[][] is an int array used to store data such as life and color (Info[1][0] is the red color)
I have no idea how the H. i can mess up. the creation of the cells and cellsX is
int Xsize = 100;
int Ysize = 100;
Cell[][] cells = new Cell[Xsize][Ysize];
Cell[][] cellsX = new Cell[Xsize][Ysize];
and initialized:
for(int i = 0; i< Xsize; i++) {
for(int j = 0; j < Ysize; j++) {
cellsX[i][j] = new Cell();
}
}
for(int i = 0; i< Xsize; i++) {
for(int j = 0; j < Ysize; j++) {
cells[i][j] = new Cell();
}
}
Sorry for the wall of text...
I just can't figure out how cells get's updated :S

From your comment -
"How should this not give me 2 2d arrays, one called cells and another
called cells X"
You do it's just that they equal each other here - cellsX = cells; Consider, and run/watch, this simple example...
public static void main(String[] args){
int size = 5;
int foo[][] = new int[size][size];
int bar[][] = new int[size][size];
for(int i = 0; i < size; ++i) {
for(int j =0; j < size; ++j) {
System.out.print(foo[i][j] + " ");
}
}
System.out.println();
foo = bar;
for(int i = 0; i < size; ++i) {
for(int j = 0; j < size; ++j) {
bar[i][j] = j;
}
}
for(int i = 0; i < size; ++i) {
for(int j =0; j < size; ++j) {
System.out.print(foo[i][j] + " ");
}
}
}//SSCCE1
Output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 0 1 2 3 4
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
This shows that while I do have two 2D arrays they equal each other, they are not unique copies of each other. foo was a 2D array that was initialized by default to 0, but then we have foo reference bar. So the changes made to bar are reflected by foo. You want, I'm supposing, an independent copy initialized with the values of the other.
See that Arrays are Objects.

What you don't seem to understand is what the following line in your code does:
cellsX = cells;
Arrays in Java are objects. Variables hold references to objects. You just assigned the reference held in cells to cellsX. You now have two variables pointing to one array object. The array (and the arrays it contained) you originally instantiated and assigned to cellsX is gone; nothing references it and it will be garbage collected.
Consider the following:
public class Demo {
public static class MyPojo {
public int value;
public MyPojo(int value) {
this.value = value;
}
}
public static void main(String[] args) {
MyPojo pojoOne = new MyPojo(1);
MyPojo pojoTwo = new MyPojo(2);
System.out.println(pojoOne.value);
System.out.println(pojoTwo.value);
pojoTwo = pojoOne;
// You now have two variables holding a reference to
// a single instance of MyPojo. Changes made through
// either affect the same object. The object you
// originally instantiated and assigned to pojoTwo
// is no longer referenced by anything and will be
// garbage collected.
pojoOne.value = 3;
System.out.println(pojoTwo.value);
}
}
If in your code you're trying to copy the contents of the array referenced by cells to the array referenced by cellsX you would need to do so.
Since this is a multi-dimensional array you need to do a deep-copy; What you really have is an array of array references (since, again, arrays are objects in Java). This StackOverflow question covers that.

Related

Transpose java error

I was trying to do a 2D array program to demonstrate a TRANSPOSE but I am getting error .. here is my code.
import java.util.Scanner;
/* To demonstrate TRANSPOSE USING 2-D array */
public class Array_2ddd {
public static void main(String args[]) {
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[9][9];
int myArray2[][] = new int[9][9];
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.println("Enter array from 1 to 9");
myArray1[i][j] = s1.nextInt();
System.out.print("your array is" + myArray2[i][j]);
}
}
// Transposing now...
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.print("Your array is as follow" + myArray2[i][j]);
}
}
}
}
EDIT: My error during runtime (Solved)
EDIT 2: Solved
EDIT 3: The loop is in infinity ..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity..
There are several errors in your code, also it is recommend that the dimensions of the array is to be declared as a final int, so your code works for all matrix sizes and that debugging is easier. In your original code, the errors are:
At the input step, you are printing one element of myArray[2] before you perform the transpose. That means, you are getting your array is0.
In the section commented "After transposing", you are outputting your array wrong. Namely, for each entry, you call System.out.print("Your array is as follow" + myArray2[i][j]);, and that you forgot to add a new line after each row (when inner loop is finished).
"..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity.." There are 81 entries for the 9-by-9 case and you did not output which i,j index to be applied. You probably mistaken an infinite loop with a long but terminating loop.
Your transpose step is good.
Here is a refined version of your code which allows you to input array (in reading order, or more technically, row-major order), create a transposed array. You can copy and compare your current code with this code directly to test it.
public static void main(String args[]) {
final int m = 9; // Rows
final int n = 9; // Columns
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[m][n]; // Original array, m rows n cols
int myArray2[][] = new int[n][m]; // Transposed array, n rows m cols
// Input
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
// Should be only prompt.
// Improved to show which entry will be affected.
System.out.printf("[%d][%d]" + "Enter array from 1 to 9\n", i, j);
myArray1[i][j] = s1.nextInt();
}
}
// Transposing now (watch for the ordering of m, n in loops)...
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing, output
System.out.print("Your array is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(myArray1[i][j] + " ");
}
System.out.println(); // New line after row is finished
}
System.out.print("Your transposed array is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(myArray2[i][j] + " ");
}
System.out.println();
}
s1.close();
}
For an array with three rows (m = 3) and four columns (n = 4), I inputted the numbers from 0 to 9, and then 0, 1, 2. As expected, the output should be:
Your array is:
0 1 2 3
4 5 6 7
8 9 0 1
Your transposed array is:
0 4 8
1 5 9
2 6 0
3 7 1
You define your matrix as 9x9
int myArray1[][] = new int[9][9];
But actually you want to insert 10x10 items:
for (i = 0; i <= 9; i++)
{
for (j = 0; j <= 9; j++)
So either:
Redefine your arrays to store 10x10 items
int myArray1[][] = new int[10][10];
Only read and store 9x9 items in your defined array
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++)
You haven't close your first outer for loop i.e in line 17 and change your array size to 10,as you wanted take 10 input (for 0 to 9 = 10 values).

JAVA Writing the diagonal of an 2-dimensional array into an 1-dimensional array

Want to write the diagonal of an 2-dimensional array (n*n Matrix) into an one-dimensional array.
1 2 3
4 5 6 => 1 5 9
7 8 9
public int[] getDiagonalFromArray(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array[0].length];
int k=0;
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
for (int l = 0; l < two_d_array[0].length; l++) {
diagonal_array[k]=two_d_array[i][j];} //HERE SHOULD BE THE ERROR... HOW DO I CYCLE THROUGH THE 1dim "diagonal_array"?
}
}
return diagonal_array;
}
This method delivers wrong values.
This method of mine works, but just Prints the diagonale, instead of putting it into an 1dim array.
public void getDiagonal(int[][] two_d_array){
//int[] diagonal_array = new int[two_d_array[0].length];
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
if (i==j) System.out.print(two_d_array[i][j]+" ");
}
}
}
Where is the logical difference? I tried the if-clause on the first method, but it raises the "outofbound"-Exception.
Thanks in advance.
Why do you need more than one loop?
for (int i = 0; i < two_d_array[0].length; i++) {
diagonal_array[i]=two_d_array[i][i];
}
Seems to be enough to me.
If your matrix has the same width and height, this is a solution:
public int[] getDiagonal(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array.length];
for (int i = 0; i < two_d_array.length; i++) {
diagonal_array[i] = two_d_array[i][i];
}
return diagonal_array;
Here, I consider principal diagonal elements to be the set of elements , where n & m are the number of rows and the number of columns (per row?) respectively.
Thus, the number of diagonal elements is never greater than min(numOfRows, numOfColumns).
And so, you can always try:
public int[] getDiagonalFromArray(int[][] 2DArray){
int[] diagonalArray = new int[Math.min(2DArray.length, 2DArray[0].length]);
int k=0;
for (int i = 0; i < 2DArray.length && k < diagonalArray.l length; ++i) {
for (int j = 0; j < 2DArray[i].length && k < diagonalArray.l length; ++j) {
if (i == j) {
diagonalArray[k++]=2DArray[i][j];
}
}
}
return diagonalArray;
}
Threw in some bounds checks for good measure.
Your input matrix must at be at least rectangular (square makes most sense), otherwise, the code will behave unreliably.
This is the same as #Andreas' answer, but I sacrifice performance and brevity here for the sake of understanding.

Conway's Game of Life Rules Java

I am making the Conway's Game of Life like almost every other beginner. The main problem I have is I have no clue how to implement the rules for the game, which are :a dead cell with exactly three live neighbors becomes alive, a live cell with exactly one live neighbor becomes dead, and a live cell with more than three live neighbors becomes dead. I've never manipulated a matrix before so I do not have any idea where to start. The class I'm in does not allow us to use non-static methods yet, and also we cannot use the java libraries. This is currently what I have:
public class Life {
public static boolean[][] origin(int a) {
boolean[][] randomMatrix = new boolean [a][a];
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
randomMatrix[i][j] = StdRandom.bernoulli();
}
}
return randomMatrix;
}
public static void print(boolean[][] a) {
int N = a.length;
StdOut.println(N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (a[i][j]) StdOut.print("1 ");
else StdOut.print("0 ");
}
StdOut.println();
}
}
public static void show(boolean[][] a, boolean which) {
int N = a.length;
StdDraw.setXscale(0, N-1);
StdDraw.setYscale(0, N-1);
double r = .5;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (a[i][j] == which) {
StdDraw.filledSquare(j, N-i-1, r);
}
}
}
}
public static void main(String[] args) {
int a = 5;
boolean[][] b = origin(a);
int gens = 3;
for (int i = 0; i < gens; i++) {
System.out.println("Generation " + i + ":");
print(b);
show(b, true);
}
}
}
The output I'm receiving right now is what I need for the initial generation of the game. I think I need a new array to store the new generations, and maybe some if and else statements to check if the cells are alive or dead. Any help is appreciated.
HINTS
Recently I completed this example. So the right structure is:
Required 2 dimension arrays ("current" & "next")
Initialize "current" with random values
print "current"
Copy & Calculate each cell of the next generation in array "next"
After calculation, update the "current" array. Use function to update each cell
Set "current" with "next" generation values
Print "current" and go to step 4
Warning!!
Use different formula to check the cells that are on the edges.

Create a 2D array and initialize every element to be the value of i * j where i and j are the 2 indices (for instance, element [5][3] is 5 * 3 = 15)

I am truly stuck here on how to do this. I got as far as creating the 10x10 array and making variables i and j - not far at all. I thought about the use of loops to initialize every element, but I just don't know how to go about doing it. Any help is appreciated, thanks.
public class arrays {
public static void main(String[] args) {
int[][] array = new int[10][10];
int i = 0, j = 0;
}
}
I was thinking of using a do while loop or for loop.
Psuedo-code:
for i = 0 to 9
for j = 0 to 9
array[i][j] = i*j
Converting this to Java should be a snap.
Create two nested for loops, one for i, and one for j, looping over all valid indices. In the body of the inner for loop, assign the computed product to the 2D array element.
You will need two for loops inside each other:
int[][] array = new int[10][10];
for (int x = 0; x < array.length; ++x)
{
for (int y = 0; y < array[y].length; ++y)
{
int product = x * y;
// put the value at the right place
}
}
You can read this as:
For each x value, iterate over the ten y values and do...
int [][] array = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
//initialize every element
array[i][j] = i + j;
}
}

Eclipse - Java Array ID Values are Equal. Cannot change values independently

I have two arrays that I create like this:
public int GameBoard[][] = new int[30][14];
public int DirectionMap[][] = new int[30][14];
I then initialize the arrays like this:
for (int i = 0; i < GameBoard.length; i++)
{
for (int j = 0; j < GameBoard[i].length; j++)
{
GameBoard[i][j] = 0;
}
}
... //Same for DirectionMap
When I run the function:
DirectionMap = AStar(GameBoard);
To render the pathfinding map that my units will follow, DirectionMap is correctly set to the values generated based on my GameBoard. However GameBoard is set to the result as well. When I run the application in Debug Mode within Eclipse, I can see that the ID's of the two arrays are the same. For some reason they seem to be pointing to the memory space. My AStar function does not modify the GameBoard array at all. The only reference to it is int retVal[][] = GameBoard;
My function prototype is public int[][] AStar(int[][] Board); and it returns the int[][] retVal.
I have no idea why I cannot change the values of DirectionMap without GameBoard following. I have never had any issues like this before.
Any ideas are really appreciated. Thanks for your help.
public int[][] AStar(int[][] Board)
{
int retVal[][] = Board;
//Initialize All Needed Lists
int width = retVal.length;
int height = retVal[0].length;
int goalX = 0;
int goalY = 0;
//List<Node> fieldInfo = new ArrayList<Node>();
Node fieldArray[][] = new Node[width][height];
for (int i = 0; i < fieldArray.length; i++)
{
for (int j = 0; j < fieldArray[i].length; j++)
{
fieldArray[i][j] = new Node(i, j);
if (retVal[i][j] == 2)
{
fieldArray[i][j].setOpen(1);
fieldArray[i][j].setDirection(10); //Set as target
goalX = i;
goalY = j;
}
if (retVal[i][j] == 1)
{
fieldArray[i][j].setOpen(0);
fieldArray[i][j].setDirection(9); //Set as wall
}
}
}
//Add AStar Algorithm Here
for (int i = 0; i < fieldArray.length; i++)
{
for (int j = 0; j < fieldArray[i].length; j++)
{
if (fieldArray[i][j].getDirection() == 0)
{
//Occurs when node was never reached
int dX = i - goalX;
int dY = j - goalY;
if (dX < 0)
dX = -dX;
if (dY < 0)
dY = -dY;
if (dY > dX)
fieldArray[i][j].setDirection(1);
else
{
if (i > goalX)
fieldArray[i][j].setDirection(7);
if (i < goalX)
fieldArray[i][j].setDirection(3);
}
}
}
}
for (int i = 0; i < fieldArray.length; i++)
{
for (int j = 0; j < fieldArray[i].length; j++)
{
retVal[i][j] = fieldArray[i][j].getDirection();
}
}
return retVal;
}
Remember when you are passing an object to methods you are actually passing a copy of reference. So when you initialise retVal[][] = Board; you actually point Board using another reference retVal. And you are returning the same reference to DirectionMap. Hence same id's for Board and DirectionMap. Consider array copy instead.
I can see that the ID's of the two arrays are the same. For some
reason they seem to be pointing to the memory space
The int[] array in Java has 0's as default values.
int[] x = new int[2];
System.out.println(x[0]); // prints 0
System.out.println(x[1]); // prints 0
The only reference to it is int retVal[][] = GameBoard;
Java arrays are objects. If at any point you are setting array = array, you are setting one reference to point to the same object as the other.

Categories