Whenever I want to convert an int[][] into an int[] array, I follow the procedure shown underneath.
final int[][] source = new int[3][3];
final int[] array = new int[9];
// I allocate an int that represents the current index of the int[] array.
int index = 0;
// Afterwards I iterate over the `int[][]` array.
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
array[++index] = source[x][y];
}
}
The code does the job, but I want to know if there is a better solution for my problem that effectively eliminates the index variable and even enhances the efficiency of my code.
You can do this with a single loop:
for (int x = 0; x < width; x++) {
System.arraycopy(twoDimensionalArray[x], 0, oneDimensionalArray, x*height, height);
}
We can just directly calculate it
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
oneDimensionalArray[x*height+y] = twoDimensionalArray[x][y];
}
}
I'm trying to count the adjacent mines in my Array of tiles objects. The code works fine for any section of the grid within the boundary. let's assume it's a 10 by 10 array if I pick point 9,8 it will give me an array out of bounds exception. How can I make sure the Array will count the Adjacent mines on the edge of the array without giving me an ArrayOutOfBounds exception?
void countAdjacentMines(int x,int y) {
//Iterate through the array check if there is a mine
for (int i = 0; i < tiles.length; i++) {
for (int j = 0; j < tiles.length; j++) {
if ((tiles[i][j].getMine() == false)) {
int count = 0;
//Search adjacent tiles. at x,y
for (int p = x - 1; p <= x + 1; p++) {
for (int q = y - 1; q <= y + 1; q++) {
if (0 <= p && p < tiles.length && 0 <= q && q < tiles.length) {
if (tiles[p][q].getMine()==true)
count++;
}
tiles[p][q].setCount(count);
}
}
}
} // end for loop rows
} // end for loop columns
} // end countAdjacentMines
Create a function
int hasMine (int x, int x)
that returns 1 when (x,y) holds a mine,
or 0 if either it doesn't or (x,y) is not a valid cell (it is also useful
to have a boolean valid (int x, int y) function).
Then, just do:
totalMines = hasMine(x+1,y+1) + hasMine(x+1, y) + hasMine(x+1, y-1) + .... + hasMine (x-1,y-1) // 8 hasMine() calls.
The problem is due to
if (0 <= p && p < tiles.length && 0 <= q && q < tiles.length) {
if (tiles[p][q].getMine()==true)
count++;
}
tiles[p][q].setCount(count);
where the last statement isn't guarded by the test that p and q are within bounds.
But I think that the entire method isn't right: either you need to iterate the entire board and count, or you access a single place (x,y) and do the count for this one.
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have an array of n elements and these methods:
last() return the last int of the array
first() return the first int of the array
size() return the length of the array
replaceFirst(num) that add the int at the beginning and returns its position
remove(pos) that delete the int at the pos
I have to create a new method that gives me the array at the reverse order.
I need to use those method. Now, I can't understand why my method doesn't work.
so
for (int i = 1; i
The remove will remove the element at the position i, and return the number that it is in that position, and then with replaceFirst will move the number (returned by remove) of the array.
I made a try with a simple array with {2,4,6,8,10,12}
My output is: 12 12 12 8 6 10
so if I have an array with 1,2,3,4,5
for i = 1; I'm gonna have : 2,1,3,4,5
for i=2 >3,2,1,4,5
etc
But it doesn't seem to work.
Well, I'll give you hints. There are multiple ways to reverse an array.
The simplest and the most obvious way would be to loop through the array in the reverse order and assign the values to another array in the right order.
The previous method would require you to use an extra array, and if you do not want to do that, you could have two indices in a for loop, one from the first and next from the last and start swapping the values at those indices.
Your method also works, but since you insert the values into the front of the array, its going to be a bit more complex.
There is also a Collections.reverse method in the Collections class to reverse arrays of objects. You can read about it in this post
Here is an code that was put up on Stackoverflow by #unholysampler. You might want to start there: Java array order reversing
public static void reverse(int[] a)
{
int l = a.length;
for (int j = 0; j < l / 2; j++)
{
int temp = a[j]
a[j] = a[l - j - 1];
a[l - j - 1] = temp;
}
}
int[] reverse(int[] a) {
int len = a.length;
int[] result = new int[len];
for (int i = len; i > 0 ; i--)
result[len-i] = a[i-1];
return result;
}
for(int i = array.length; i >= 0; i--){
System.out.printf("%d\n",array[i]);
}
Try this.
If it is a Java array and not a complex type, the easiest and safest way is to use a library, e.g. Apache commons: ArrayUtils.reverse(array);
In Java for a random Array:
public static void reverse(){
int[] a = new int[4];
a[0] = 3;
a[1] = 2;
a[2] = 5;
a[3] = 1;
LinkedList<Integer> b = new LinkedList<Integer>();
for(int i = a.length-1; i >= 0; i--){
b.add(a[i]);
}
for(int i=0; i<b.size(); i++){
a[i] = b.get(i);
System.out.print(a[i] + ",");
}
}
Hope this helps.
Reversing an array is a relatively simple process. Let's start with thinking how you print an array normally.
int[] numbers = {1,2,3,4,5,6};
for(int x = 0; x < numbers.length; x++)
{
System.out.println(numbers[x]);
}
What does this do? Well it increments x while it is less than numbers.length, so what is actually happening is..
First run : X = 0
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[0]);
// Which resolves to..
System.out.println(1);
Second Run : X = 1
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[1]);
// Which resolves to..
System.out.println(2);
What you need to do is start with numbers.length - 1, and go back down to 0. To do this, you need to restructure your for loop, to match the following pseudocode..
for(x := numbers.length to 0) {
print numbers[x]
}
Now you've worked out how to print, it's time to move onto reversing the array. Using your for loop, you can cycle through each value in the array from start to finish. You'll also be needing a new array.
int[] revNumbers = new int[numbers.length];
for(int x = numbers.length - 1 to 0) {
revNumbers[(numbers.length - 1) - x] = numbers[x];
}
int[] noArray = {1,2,3,4,5,6};
int lenght = noArray.length - 1;
for(int x = lenght ; x >= 0; x--)
{
System.out.println(noArray[x]);
}
}
int[] numbers = {1,2,3,4,5};
int[] ReverseNumbers = new int[numbers.Length];
for(int a=0; a<numbers.Length; a++)
{
ReverseNumbers[a] = numbers.Length - a;
}
for(int a=0; a<ReverseNumbers.Length; a++)
Console.Write(" " + ReverseNumbers[a]);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
reverse(numbers, 1); >2,1,3,4,5
reverse(numbers, 2); >3,2,1,4,5
public int[] reverse(int[] numbers, int value) {
int index = 0;
for (int i = 0; i < numbers.length; i++) {
int j = numbers[i];
if (j == value) {
index = i;
break;
}
}
int i = 0;
int[] result = new int[numbers.length];
int forIndex = index + 1;
for (int x = index + 2; x > 0; x--) {
result[i] = numbers[forIndex--];
++i;
}
for (int x = index + 2; x < numbers.length; x++) {
result[i] = numbers[x];
++i;
}
return result;
}
In my 2D Tiled game, I have a problem, when I update all the Object from a 2D array in a for loop inside another (looping in the 2D array from top left to bottom right, row by row(like the code below)), If the program is looping at index (5,6) and it need data from the Object under itself, It'll use the new data that he have executed when the loop is at (5,5) but I want to use the all data before the start of the double for loop...
A basical example:
int[][] map = new int[10][10];
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
update(x, y, map);
}
}
// I remember you that it is an example
void update(int x, int y, int[][] m)
{
m[x][y] = 0
if(y > 9) { return; }
m[x][y + 1] = 1
}
It will put instantly the data "1" at (x, 10), without considering that it generate errors...(ArrayOutOfBoundsException...)
How I can make it use the data of the array when he don't started the double loop yet?
I know that it generata ArrayOutOfBoundExecption, and with a single if I can correct it like I done up here
int Water = 1;
int Air = 0;
int[][] map = new int[20][20];
void update()
{
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
tick(x, y, map);
}
}
}
void tick(int x, int y, int[][] m)
{
if(y > m.lenght - 1) { return; }
m[x][y] = Air;
m[x][y + 1] = Water;
}
You are saying that you are iterating your map row by row when you are actually doing it by columns. Try looping first for y and then for x.
Your update method is also wrong. y+1 when y = 9 will try to access map[x][10] which will throw an ArrayOutOfBoundsException. Remember than an array declared as new int[10] has 10 items starting from 0 and ending at position 9.
int Water = 1;
int Air = 0;
int[][] map = new int[20][20];
void update()
{
for(int x = 0; x < 10; x++)
{
for(int y = 9; y >= 0; y--)
{
tick(x, y, map);
}
}
}
void tick(int x, int y, int[][] m)
{
if (y < m[0].length - 1)
m[x][y+1] = m[x][y];
}
Of course, you'll need to make some cells water to begin with, but that should go in the constructor.
Given an adjacency matrix, I need to compute the shortest path between the first vertex and the last vertex (generally, vertex i and j, but we can ignore that for the time being). I've written an algorithm that really only correctly computes the distance between the first and second node (a step in the right direction, I guess).
static int dijkstra(int[][] G, int i, int j) {
//Get the number of vertices in G
int n = G.length;
int[] bestpath = new int[n];
int max = Integer.MAX_VALUE;
boolean[] visited = new boolean[n];
for (int x = 0; x < n; x++) {
visited[x] = false;
bestpath[x] = max;
}
bestpath[i] = 0;
for (int x = 0; x < n; x++) {
int min = max;
int currentNode = i;
for (int y = 0; y < n; y++) {
if (!visited[y] && bestpath[y] < min) {
System.out.println(G[y][x]);
currentNode = y;
min = bestpath[y];
}
}
visited[currentNode] = true;
for (int y = 0; y < n; y++) {
if (G[currentNode][y] < max && bestpath[currentNode] + G[currentNode][y] < bestpath[y]) {
bestpath[y] = bestpath[currentNode] + G[currentNode][y];
}
}
}
return bestpath[j];
}
If I were to guess, I'd say my logic is flawed in this section:
for (int y = 0; y < n; y++) {
if (!visited[y] && bestpath[y] < min) {
System.out.println(G[y][x]);
currentNode = y;
min = bestpath[y];
}
}
An example would be the matrix
0 1 0
1 0 1
0 1 0
which would return 2 (one path between vertex one and two of weight 1 and another between 2 and 3 with weight 1).
If the matrix is not just storing 1s and 0s, but the distance from i to j, then you really need to keep track of the best distance from any node i to j. In other words, your working array should be a working matrix instead. Even if you are just doing a non - weighted graph, I think this approach is better.
There are different versions of the SPF algorithm. Post pseudocode for what you are trying to translate into java.