How to merge two elements in an array together? - java

For example you have the 2d array Board as shown below:
{0, 2, 4, 2}
{0, 0, 2, 2}
{2, 2, 0, 0}
{0, 5, 0, 2}
You want it to become:
{0, 2, 4, 2}
{0, 0, 4, 0}
{4, 0, 0, 0}
{0, 5, 0, 2}
When there are 2 elements next to each other you need to merge them to make 4 into the left-most place out of those two elements and then make the 2nd element to be 0.
You want to do this with java.
forgot to show my existing loop, this is it below:
for (int row = 0; row < Board.length; row++){
for (int col = 0; col <= Board.length; col++){
if ((Board[row][col] == Board[row][col +1])){
Board[row][col] = 2 * Board[row][col];
Board[row][col + 1] = 0;
}
}
}

Well, I guess that should work. In the loop, you must be careful not to refer to the wrong ( or non-existing) array element.
public static void main(String[] args) {
int[][] arr = new int[][]{{0, 2, 4, 2}, {0, 0, 2, 2}, {2, 2, 0, 0}, {0, 5, 0, 2}, {2, 2, 2, 2}, {2, 2, 2, 0}};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length - 1; j++) {
if (arr[i][j] == arr[i][j + 1]) {
arr[i][j] = arr[i][j] + arr[i][j + 1];
arr[i][j + 1] = 0;
}
}
}
System.out.println(Arrays.deepToString(arr));
}

Here is one way, focusing only array values that equal 2.
iterate the 2D array.
then iterate over each linear array, checking adjacent values and making the changes.
for(int[] arr : v) {
for(int i = 0; i < arr.length-1; i++) {
if (arr[i] == 2 && arr[i+1] == 2) {
arr[i]+= arr[i+1];
arr[i+1] = 0;
}
}
}
for(int arr[]: v) {
System.out.println(Arrays.toString(arr));
}
prints
[0, 2, 4, 2]
[0, 0, 4, 0]
[4, 0, 0, 0]
[0, 5, 0, 2]

Well I assume that Board variable holds array (quick tip, common convention is to name variable in camelCase (first letter lowercase, then each letter of next work upper, if that variable is constant, then convention is SNAKE_UPPER_CASE)
Your first for is pretty okay, the second one too but it assumes that matrix will be always NxN and will fail if thats not the case or it will not work properly (depending if amount of cols is lower or greater than length of array)
Inside it you dont want to check if the values are equal, you want to check if these values are both equal to 2. And you should check if thats not processing of last column of the row, in that case youll get IndexOutOfBoundException because you want to get value of matrix that is not present.
So with small changes, you will achieve what you want. This code will hopefuly shows my thoughts better
public class MergingTwos {
public static void main(String args[]) {
// Init a matrix
int[][] array = new int[][] { { 0, 2, 4, 2 }, { 0, 0, 2, 2 }, { 2, 2, 0, 0 }, { 2, 2, 0, 0 }, { 0, 5, 0, 2 }};
// Iterating over each row of matrix, in veriable i, the current X index is stored
for(int i = 0; i < array.length; i++) {
// Iterating over each column of row, in variable n, the current Y index is stored
for(int n = 0; n < array[i].length; n++) {
// To prevent index out of bound exception, last element of row wont be processed so as we dont want to proceed if given and next value on row are not 2
if(n == array[i].length -1 || array[i][n] != 2 || array[i][n+1] != 2) {
continue;
}
// To value at given coordinates [i,n] you add values of value on coordinates [i, n+1]
array[i][n] = array[i][n] + array[i][n+1];
// And setting next element to 0
array[i][n+1] = 0;
}
}
// Printing the result
for (int[] x : array) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}

Related

How to shift everything in a 2D array to the left

I need to take a 2D array and move everything as far left as possible. It is a 4x4 array and I have tried to do it but either only move certain items or the index goes out of bounds.
The gameBoard array looks like this:
{0 2 4 2}
{0 0 2 0}
{2 2 0 0}
{0 4 0 2}
and after you call the swipeLeft() method it should look like this:
{2 4 2 0}
{2 0 0 0}
{2 2 0 0}
{4 2 0 0}
There is also the issue of placing a zero into the previous index that you moved it from.
I created a double for loop to just loop through the array and tried to code something that would move it over but it hasn't worked.
Here was the code I had so far
public void swipeLeft() {
for ( int r = 0; r < gameBoard.length; r++ ) {
for ( int c = 0; c < gameBoard[r].length; c++ ) {
gameBoard[r][c] = gameBoard[r][ (c+1) %
gameBoard.length];
}
}
}
Based on your desired OUTPUT, it looks like swipeLeft() is supposed to push all non-zero values to the very left of their row, displacing the zeroes to the right of all non-zero values.
If that's correct, this is similar to Old Dog Programmer's approach, except all shifting is done "in place" without creating any new arrays:
import java.util.*;
class Main {
private static int[][] gameBoard;
public static void main(String[] args) {
gameBoard = new int[][] {
{0, 2, 4, 2},
{0, 0, 2, 0},
{2, 2, 0, 0},
{0, 4, 0, 2}
};
System.out.println("Before:");
displayBoard();
swipeLeft();
System.out.println("\nAfter:");
displayBoard();
}
public static void displayBoard() {
for(int[] row : gameBoard) {
System.out.println(Arrays.toString(row));
}
}
public static void swipeLeft() {
for(int[] row : gameBoard) {
// find the first blank (zero) spot
int nextIndex = 0;
while(nextIndex < row.length && row[nextIndex] != 0) {
nextIndex++;
}
// start with the first blank, and shift any non-zero
// values afterwards to the left
for(int col=nextIndex; col < row.length; col++) {
if (row[col] != 0) {
row[nextIndex] = row[col];
row[col] = 0;
nextIndex++;
}
}
}
}
}
Output:
Before:
[0, 2, 4, 2]
[0, 0, 2, 0]
[2, 2, 0, 0]
[0, 4, 0, 2]
After:
[2, 4, 2, 0]
[2, 0, 0, 0]
[2, 2, 0, 0]
[4, 2, 0, 0]
From the example in the question, it appears to me that what is wanted is to shift all non-zero elements to the left, and zero elements are shifted to the right. The order of the non-zero elements is to be retained.
Note that each row is independent of other rows.
One way to approach this is to create a method that works on a 1D array. This method takes a 1D array as a parameter, and returns another 1D array with the elements shifted:
public static int [] zeroShift (int [] arr) {
int [] left = new int [arr.length];
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
left [count++] = arr [i];
}
}
return left;
}
This copies each non-zero element to a new array of the same size, keeping track (count) of how many have been copied so far. Note this relies on left being initialized to all-zeros.
Once that method is working, it can be used for gameBoard on a row-by-row basis:
public void swipeLeft() {
for (int r = 0; r < gameBoard.length; r++) {
gameBoard [r] = zeroShift (gameBoard [r]);
}
// output for testing
for (int i = 0; i < gameBoard.length; ++i) {
System.out.println(Arrays.toString(gameBoard[i]));
}
}
To rotate the array in place, you should roteate the array 3 times:
123456 -> 654312
654321
3456..
....12
public static void shiftLeft(int[] arr, int offs) {
if (offs <= 0)
return;
offs = arr.length - offs % arr.length - 1;
for (int i = 0, j = arr.length - 1; i < j; i++, j--)
swap(arr, i, j);
for (int i = 0, j = offs; i < j; i++, j--)
swap(arr, i, j);
for (int i = offs + 1, j = arr.length - 1; i < j; i++, j--)
swap(arr, i, j);
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
So your code intends to rotate the board one column to the left. Rotate? Well, the numbers you push out on the left might come back on the end, right?
Probably the line
gameBoard[r][c] = gameBoard[r][ (c+1) % gameBoard.length];
should be
gameBoard[r][c] = gameBoard[r][ (c+1) % gameBoard[r].length];
But try to do this stuff with pen & paper, and you should notice that you are going to loose one column/copy the values from the second column into the first, then copy that into the last column again.
You will need to change two items:
store the value from the first column somewhere if you still need it so you can push it into the last one.
only rotate the column data if it needs to be rotated. Or in other words, rotate the remainder of the row if you find a zero. In this case you do not need to remember the first column, as you will overwrite a zero and push a zero into the last column. And then it would not be called rotate but shift.
Exercise this with pen & paper until you can write down instructions for someone else to perform the same operation. Then you are ready to also write it in Java.

Finding indexes of 2d array elements in a sorted 2d array by columns

I have two 2D arrays of integers of the same dimension that I need to compare. I am going to explain what I need with an example where Sjm1 is the "original" array and the Sjm2 array has the same values as Sjm1 but the values of each column are ordered in increasing order (i.e. "0" is the min value of Sjm1 in column 0 so Sjm2[0][0]=0; then "70" is the next min value of Sjm1 in column 0 ⇒ Sjm2[1][0]=70; and so on). I have a method to sort a "Sjm1" array to "Sjm2".
Now I need to build an "output" array (2D array of integers) where the values in each column represent the number of the row in Sjm1 array that coincides with the elements of the column in Sjm2. For example, Output[0][0]=5 because Sjm1[0][0]=366 is Sjm2[5][0]=366; Output[1][0]=2 because Sjm1[1][0]=104 is Sjm2[2][0]=104; and so on).
Thus, for the previously presented example, the needed output must be the following:
I tried to build a method in Java where I pass the two 2D arrays of integers but is not working as needed:
public static int[][] sec(int[][] Sjm1, int[][] Sorted_Sjm2) {
int k;
int[][] output = new int[Sjm1.length][Sjm1[0].length];
for (int j = 0; j < Sjm1.length; j++) {
k = 0;
for (int m = 0; m < Sjm1[0].length; m++) {
if (Sorted_Sjm2[j][m] == Sjm1[j][m]) {
output[j][m] = k;
k++;
}
}
}
return output;
}
The output is clearly not what I need:
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
I'll be glad if someone can help me.
I think you are not updating the value of k correctly, if I understood what you need, once you find the value you are looking for just update the value of k to the index you found the value in. Note that if you have repeated values it will only take the first it found.
public static int[][] sec(int[][] Sjm1, int[][] Sorted_Sjm2) {
int k;
int[][] output = new int[Sjm1.length][Sjm1[0].length];
for (int j = 0; j < Sjm1.length; j++) {
k = 0;
for (int m = 0; m < Sjm1[0].length; m++) {
if (Sorted_Sjm2[j][m] == Sjm1[j][m]) {
k = j;
output[j][m] = k;
break;
}
}
}
return output;
}
I'm kinda new to contributing, so please let me know if I got this wrong! ><"
The problem is with your code, you're comparing both of the matrices at the same intervals (as m and j changes). What you could do, is iterate through matrix sjm2 and compare for each iteration for matrix sjm1.
i.e.
Have value of SJM1
Iterate through that column in SJM2 to find the row with the same val
Add the row number in the output.
Plus, the only way you got your output is if your Sorted_Sjm2 is the same as your Sjm1, as k was incremented to 6 every iteration.
Inside your inner loop (which sets output[j][m]) an easy way to find the matching index would be to use List.indexOf rather than searching for it yourself:
output[j][m] = Arrays.asList(Sjm2[j]).indexOf(Sjm1[j][m]);
If I get your question right, the problem is with the k variable.
It represents the row index on the second array, so when you compare the value on the two array, you should index the row of the second array with k.
Also, you should iterate the k over all rows in the current column, so the code would look like this (I modified the variables to make them more describing):
public static int[][] sec(int[][] Sjm1, int[][] Sorted_Sjm2) {
int[][] output = new int[Sjm1.length][Sjm1[0].length];
for (int row = 0; row < Sjm1.length; row++) {
for (int column = 0; column < Sjm1[0].length; column++) {
int valueToSearchFor = Sjm1[row][column];
for (int rowInSorted = 0; rowInSorted < Sorted_Sjm2.length; rowInSorted++) {
if (Sorted_Sjm2[rowInSorted][column] == valueToSearchFor) {
// Found
output[row][column] = rowInSorted;
break;
}
// Not found
output[row][column] = -1;
}
}
}
return output;
}
Note that although this code works, I doubt that it's optimal, so I would not use it for very large data sets.
At first you need to iterate on Sorted_Sjm2[j][] to find out where is the Sjm1[j][m] value so you need another for in for (int m = 0; m < Sjm1[0].length; m++). And the other thing is why you are using k?k doesn't show any thing in your array. If you want gain the sorted position you should use another variable that you declare in new for statement in
Sorted_Sjm2[j][]. Because we know you are in column j so we just need to now row number of the sorted array.
public static int[][] sec(int[][] Sjm1, int[][] Sorted_Sjm2) {
int k;
int[][] output = new int[Sjm1.length][Sjm1[0].length];
for (int j = 0; j < Sjm1.length; j++) {
for (int m = 0; m < Sjm1[0].length; m++) {
for (int d = 0; m < Sjm1[0].length; d++) {
if (Sorted_Sjm2[j][d] == Sjm1[j][m]) {
output[j][m] = d;
}
}
}
}
return output;
}
To get a matrix of row indices by columns of elements of this matrix in a sorted matrix - you can first sort the row indices of the elements of this matrix by columns and get the sorted transposed matrix of indices. Then transpose the sorted matrix back and, for each element, swap its value and column index:
int m = 7;
int n = 8;
int[][] arr1 = new int[][]{
{366, 139, 223, 312, 563, 471, 437, 2},
{104, 195, 85, 0, 377, 289, 227, 5},
{451, 221, 329, 425, 523, 591, 537, 1},
{208, 78, 0, 140, 437, 380, 286, 6},
{0, 52, 114, 84, 296, 212, 205, 3},
{70, 0, 40, 121, 194, 156, 123, 3},
{299, 351, 446, 216, 648, 685, 571, 2}};
int[][] arr2 = IntStream
// iterate over the indices
// of the rows of the array
.range(0, n)
.mapToObj(i -> IntStream
// iterate over the
// indices of the columns
.range(0, m)
.boxed()
// sort indices of the elements of the
// columns by its values in the array
.sorted(Comparator.comparingInt(j -> arr1[j][i]))
.mapToInt(Integer::intValue)
// sorted column of indices
// is a row in the new array
.toArray())
// return sorted array of indices
.toArray(int[][]::new);
// transpose the array of indices
int[][] arr3 = new int[m][n];
IntStream.range(0, m).forEach(i ->
IntStream.range(0, n).forEach(j -> {
// swap the column index and
// the value of the element
int val = arr2[j][i];
arr3[val][j] = i;
}));
// output
Arrays.stream(arr3).map(Arrays::toString).forEach(System.out::println);
Output:
[5, 3, 4, 5, 5, 4, 4, 1]
[2, 4, 2, 0, 2, 2, 2, 5]
[6, 5, 5, 6, 4, 5, 5, 0]
[3, 2, 0, 3, 3, 3, 3, 6]
[0, 1, 3, 1, 1, 1, 1, 3]
[1, 0, 1, 2, 0, 0, 0, 4]
[4, 6, 6, 4, 6, 6, 6, 2]
See also:
• Sorting 2d array of integers by column
• Finding the position of a row element in a 2d ordered array

Square Value at Index without using a temp array

At 0th index value is 4, so I have to check the value at index 4 and square it and place the value at 0th index without using a temp array:
Index 0 1 2 3 4
Values 4 3 1 2 0
================
Result 0 4 9 1 16
Now I am getting the first two values right, but the last three are not right. My code is as below:
static void Index(int arr[], int n) {
for(int i=0;i<n;i++) {
int index = arr[i];
int value = arr[index];
arr[i]=value*value;
}
}
Below is the output that I am getting:
Original Array
4 3 1 2 0
Array after Squaring
0 4 16 256 0
Can anyone help me out here as to what am I doing wrong?
Assuming the numbers are within range [0, 46341), we can store both the old and the new values in the array during the process (as 32 bits are enough). Then after the first loop we do another one to discard the old values and square the new ones.
// assume array[i] is within range [0, 46341) for any i
static void f(int[] array) {
for (int i = 0; i < array.length; i++) {
int j = array[i] & 0xffff; // get old value
array[i] = array[j] << 16 | j; // put new and old values
}
for (int i = 0; i < array.length; i++) {
int j = array[i] >>> 16; // get new value
array[i] = j * j; // put new value squared
}
}
NOTE: This approach is valid only if length of array is less than 10.
I have completed this code using only one loop without using any extra space.
Although, I have set a flag to run the complete loop twice.
If you do not have any constraint of using one loop, you can avoid using the flag and simply use two loops.
Approach:
Index 0 1 2 3 4
Values 4 3 1 2 0
Updated value 04 23 31 12 40
You must have got the idea what I did here.
I put the values at tens place whose square is to be displayed.
Now you have to just have to iterate once more and put the square of tens place at that index
Here's the code:
void sq(int arr[], int n){
bool flag = false;
for(int i=0; i<n; i++){
if(!flag){
if(arr[arr[i]] < 10){
arr[i] += (arr[arr[i]] * 10);
}
else{
arr[i] += ((arr[arr[i]]%10) * 10);
}
}
if(i==n-1 && !flag){
i=0;
flag = true;
}
if(flag)
arr[i] = (arr[i]/10) * (arr[i]/10);
}
}
It is in C++.
The problem is you are changing the values in your original array. In you current implementation this is how your array changes on each iteration:
{4, 3, 1, 2, 0}
{0, 3, 1, 2, 0}
{0, 4, 1, 2, 0}
{0, 4, 16, 2, 0}
{0, 4, 16, 256, 0}
The problem is you still need the values stored in the original array for each iteration. So the solution is to leave the original array untouched and put your values into a new array.
public static void index(int arr[]) {
int[] arr2 = new int[arr.length];
for(int i=0;i<arr.length;i++) {
int index = arr[i];
int value = arr[index];
arr2[i]=value*value;
}
}
Values of arr2 in revised process:
{0, 0, 0, 0, 0}
{0, 0, 0, 0, 0}
{0, 4, 0, 0, 0}
{0, 4, 9, 0, 0}
{0, 4, 9, 1, 0}
{0, 4, 9, 1, 16}

How to implement deleteValues (int values) method for a custom ArrayList?

I am implementing my custom ArrayList class for integers with the help of an array, and I would like to be able to delete a certain value from my array. My problem is when there are many same delete-able value next to each other, I am getting two 0s next to each other which leads to a bug. i tried to solve it for a couple of hours without luck. Here is my code:
int max=10;
public int[] a = new int[max];
#Override
public void deleteValues(int value) {
int tempIndex=0;
for (int i = 0; i <50 ; i++) {
if (a[tempIndex] == value) {
a[tempIndex] = a[tempIndex + 1];
a[tempIndex + 1] = 0;
} else if (a[tempIndex] == 0) {
a[tempIndex] = a[tempIndex + 1];
a[tempIndex + 1] = 0;
} else {
tempIndex++;
}
}
}
My array looks like that before deleting the value (4):
[4, 2, 3, 4, 4, 4, 4, 1, 2, 3]
This is the wrong result after running the code:
[2, 3, 0, 0, 4, 4, 4, 1, 2, 3]
What I would like to achieve:[2, 3, 1, 2, 3, 0, 0, 0, 0, 0]
My question is: What would be the best approach to make the code work, using as few loop as possible?
One of the problems in your code is that you're always copying the element at index tempIndex+1 into tempIndex: it's always the next element.
In fact, after deleting let's say 5 elements from the array, you'll have to copy tempIndex+5 into tempIndex.
I think this is a good way of doing it:
public void deleteValues(int[] a, int value) {
int j=0;
for(int i=0; i<a.length; i++) {
if(a[i]!=value) {
a[j] = a[i];
j++;
}
}
// fill the rest of the array with zeros
while(j<a.length) {
a[j] = 0;
j++;
}
}
Basically, you keep two indices: i and j.
The index i follows the "original" array, while index j follows the "new" array (after deletion).
Index i loops over all the elements: if a[i] is not equal to value, copy it into its new position j and increment both j and i. If a[i] is equal to value, skip it and increment i without incrementing j.
After all the elements have been copied or skipped, fill the end of the array with zeros.
Sample input:
a = {4, 2, 3, 4, 4, 4, 4, 1, 2, 3}
value = 4
Output:
a = {2, 3, 1, 2, 3, 0, 0, 0, 0, 0}
public static void deleteValues(int[] a, int value) {
int newSize = a.length;
int current = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != value) {
if (i != current) {
a[current] = a[i];
newSize--;
}
current++;
}
}
//use first newSize values, for example you can copy to new array
System.out.println("New size = " + newSize);
}
you can use iterator:
List<Integer> numbers = ....
Iterator<Integer> i = numbers.iterator();
while (i.hasNext()) {
Integer num = i.next();
// add here your custom code
i.remove();
}
int tempIndex,index;
for (index = 0, tempIndex = 0; index < valuesArray.length; index++) {
if (valuesArray[index] != valToDelete) {
valuesArray[tempIndex++]=valuesArray[index];
}
}
while(tempIndex<valuesArray.length){
valuesArray[tempIndex++]=0;
}

Moving recursively in arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Does anybody know how to move "on the ones" and change them to 2? I think we need recursion, but I'm not very good at it, so I'm asking you for help.
You can only move up, down, left or right.
Here is an example:
int[][] a = {{ 0, 0, 0},
{1, 1, 0},
{1, 1, 1},
{1, 0, 1} };
recursiveFunction(a, 1, 1); // (<array you're checking>, <x of the group>, <y of the group>
/* int a now contains:
* { 0, 0, 0,
* 2, 2, 0,
* 2, 2, 2,
* 2, 0, 2 } */
int[][] b = {{0, 0, 0, 0, 1},
{1, 1, 0, 0, 1},
{1, 1, 1, 0, 1},
{1, 0, 1, 0, 1} };
recursiveFunction(b, 0, 5);
/* int b now contains:
* { 0, 0, 0, 0, 2
* 1, 1, 0, 0, 2
* 1, 1, 1, 0, 2
* 1, 0, 1, 0, 2 } */
You have defined just 1D array and its number so you should use int.
Instead of doing it recursively, try solving it easily with two for loops (1 for row and 1 for column) for 2D array as below:
int array[][] = {{0, 0, 0},
{1, 1, 0},
{1, 1, 1},
{1, 0, 1}};
for (int i = 0; i< array.length; i++) {
for (int j = 0; j< array[0].length; j++) {
if (array[i][j] == 1) {
array[i][j] = 2;
}
}
}
You dont need recursion for this .It is pretty straightforward.Also notice the way I have created a 2d array
char[][] a = { {0, 0, 0},
{1, 1, 0},
{1, 1, 1},
{1, 0, 1 }};
for(int i = 0; i < a.length; i++)
for(int j = 0; j < a[i].length; j++) {
if(a[i][j] == 1)
a[i][j] = 2;
}
}
Would this work ?
You can create a function and pass it the value that you want to replace. It will be better then recursion because you can avoid extra cost of stack that will be required during each recursive call
public static void replace(char[][] arr, char target, char replacment) {
for (int i = 0; i< arr.length; i++) {
for (int j = 0; j< arr[i].length; j++) {
if (arr[i][j] == target) {
arr[i][j] = replacment;
}
}
}
}
Then you can call it like this
replace(arr, (char)1, (char)2);
Ok, so if you want to change value of the connected component you start out in this should work.
public class Example {
public static void main(String[] args) {
int[][] b =
{
{0, 0, 0, 0, 1},
{1, 1, 0, 0, 1},
{1, 1, 1, 0, 1},
{1, 0, 1, 0, 1}
};
rec(b, 0, 4);
for (int[] row : b) {
System.out.println(Arrays.toString(row));
}
}
public static void rec(final int[][] grid, final int row, final int col) {
if (grid[row][col] != 1) return;
grid[row][col]++;
if (row-1 >= 0) rec(grid, row-1, col);
if (row+1 < grid.length) rec(grid, row+1, col);
if (col-1 >= 0) rec(grid, row, col-1);
if (col+1 < grid[0].length) rec(grid, row, col+1);
}
}
Note that depending of how big your components are you might run out of stack. Either you'd then have to manage your own stack explicitly in the code or you would need to increase the stack space available to the JVM.
Why do you think you need recursion? You could just iterate over the array and multiply every element by two (since 0 * 2 is 0 anyway, and it's faster than having to check the element):
for (int i = 0; i < a.length; ++i) {
for (int j = 0; j < a[i].length; ++j) {
a[i][j] *= 2;
}
}
If you are using Java 8 the Arrays.parallelSetAll method could be used.
public static void replace(int[][] arr, int target, int replacement) {
Arrays.parallelSetAll(arr, row -> {
Arrays.parallelSetAll(arr[row], col -> arr[row][col] == target ? replacement : arr[row][col]);
return arr[row];
});
}
It uses the Java 8 Stream API:s and offers a quite nice compact programming model. Furthermore, it uses the ForkJoinPool so performance could be better since it may be multi-threaded (depending on the CPU etc).

Categories