extending two 2D Arrays into a larger one - java

I have two java 2D arrays(array1 and array2), both of type Double which I would like to join together.
array1 and array2 are n-by-d matrices. the n-rows for each array can vary from eachother but the d-columns are always the same.
The question is: i have to concatenate array2 after the first one.(at best into the new outputMatrix)
Example:
array1:
2 3
6 5
4 7
array2:
1 5
3 7
Output Array (n-array1 + n-array2)-by-d:
2 3
6 5
4 7
1 5
3 7
My idea was to copy array1 into the outputMatrix, and then fill the continuation of it with array2.
My Java code for merging the two arrays(that are already implemented) looks like:
private static double[][] outputMatrix ;
outputMatrix = new double[array1.length+array2.length][array1[0].length];
for (int column = 0; column < array1[0].length; column++) {
for (int row = 0; row < (array1.length); row++) {
outputMatrix[row][column] = array1[row][column];
}
}
for (int column = 0; column < array1[0].length; column++) {
for (int row = array1.length; row < (array1.length+ array2.length); row++) {
outputMatrix[row][column] = array2[row][column]; //error here as array2 starts iterating at field [4][0] which isnt defined in the example
}
}

Your indices are wrong.
Should be
for (int column = 0; column < array1[0].length; column++) {
for (int row = 0; row < array2.length; row++) {
outputMatrix[row+array1.length][column] = array2[row][column];
}
}
since array2 has indices from 0 to array2.length-1.

So what's happening is that when you are trying to transfer the data from the second array into the outputMatric variable, you go out of bounds in the second array (array2). This is due to the fact that you're outputMatrix is trying to put a value at [array1.length + row][array1.length + column] and the second array isn't as big as that one. On top of that, your row index is wrong, you need to add the array1 length to make up for it or start the for loop's row variable at that spot. I elected just to add the length into the storing of the variable. So, you should make your code:
outputMatrix[row + array1.length][column] = array2[row - array1.length][column - array1[0].length];

Related

2D Arrays with several for loops

I am fairly new at Java and have been having some issues understanding a code within my course and it is slowing me up. Can someone kindly give me a step by step of what the 1st for loop is doing? I get confused at what value is arr[row] getting?
When I look at the result it makes sense that it is 1 2 3 4 5 6 BUT is the 1st for loop generating and then going to the second one? if so, what is the second one doing since we are starting at row=0? and col=0? I really need help to move forward with this. Here is the code:
public static void main(String[] args) {
int[][] arr = new int[6][];
for(int row = 0; row < arr.length; row++)
arr[row]= new int[row + 1];
for(int row = 0; row < arr.length; row++){
for(int col = 0; col < arr[row].length; col++){
arr[row][col] = (row + 1) *(col +1);
//System.out.print(arr[row][col] + " ");
System.out.print("row[" + row + "]"+ "col["+col +"]= "+arr[row][col] + " ");
}
System.out.println(); //new line
}
}
It is just creating a multidimensional array, each row with one more slot then the previous.
Something like this:
[]
[][]
[][][]
[][][][]
[][][][][]
[][][][][][]
The second (couple of) for scans every element and assign a value proportionated to its dimensions. So it'll be:
[1]
[2][4]
[3][6][9]
[4][8][12][16]
[5][10][15][20][25]
[6][12][18][24][30][36]
It really reminds me of Fibonacci sequence
Hope I helped

2D array in Java with incremental column number that increase in each row

How Can I create a Java 2 Dimensional array whose output will be like:
0
0 0
0 0 0
0 0 0 0
I know how to declare a 2 dimensional array.But don't know how to implement that. Sp need some help here. Thanks
Java is considered "row major", meaning that it does rows first. So if you know the number of rows you can do something like:
int[][] myArr = new int [4][];
for(int i = 0; i < myArr.length; i++){
myArr[i]= new int[i+1];
}
System.out.println(Arrays.deepToString(myArr));
Here no of zeros you want to put in each row is equals to the sequence no of that row eg 1st row has 1 0,2nd has 2 and so on. It can be done as follows:
int[][] arr = new int[5][];
for (int i = 0; i < arr.length; i++)
{
arr[i]=new int[i+1];
for (int j = 0; j <= i; j++)
arr[i][j] = 0; //or whatever you want to store
}

Single array re-indexing for table formatting

I am looking for a more elegant solution to the following scenario (language doesn't matter, Java is fine, but I am currently in C#). Suppose a linear array is coming in and being displayed as a table with X items per row (For instance, 9 items coming in at 3 items per row, so 3 rows of 3). If the array is being indexed 0 through 8, it is currently displayed as such:
6 7 8
3 4 5
0 1 2
So, the elements are displayed left to right, bottom to top. I would like to rearrange this to be displayed top to bottom, like this:
0 1 2
3 4 5
6 7 8
This requires reordering the array so that the new array's indexes are [6,7,8,3,4,5,0,1,2], with respect to the original's indexes. My current (untested) solution is the following: assume the array to be returned is 'array' and a temporary copy is 'temp', and the 'cols' variable is already the number of items per row.
int rows = (array.Length + cols - 1) / cols; //ceiling function to determine rows needed
int pos = array.Length - cols; //starting position in index transfer
int offset = 0; //needed when negative index reached
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (pos + j >= 0)
array[cols * i + j - offset] = temp[pos + j]; //assign values of temp to array
else
++offset; //takes care of negative indeces
}
pos -= cols;
}
return array;
The problem is this code is quite unreadable and possibly inefficient because of the double loop, though I don't expect many more than 9 items to come through. Is there a more elegant solution to this using slicing up the array, reversing, or anything that isn't so difficult to read? It's just a fun little problem I've been thinking about for an issue at work. Anybody's input is appreciated, thanks!
It is worth noting that potentially uneven tables can be created (For instance, 9 elements with 4 items per row creates 2 rows of 4, one row of 1. The 'offset' variable is used to protect negative array indexing if this is the case).
This is what I came up with: it doesn't sort your original array at all, but every inner loop starts at a computed starting-index based on the row you're printing. Let me know if you have any questions. This isn't specific to you, more specific to your situation, but the concept and functionality is there.
int[] array = new int[9] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
int rows = 3;
int cols = 3;
int count = 0;
for (int x = 1; x <= rows; x++)
{
int startingPos = array.Length - (x * rows);
for (int y = cols; y > 0; y--)
{
Console.Write(array[startingPos] +", ");
count++;
startingPos++;
}
Console.WriteLine();
}

2D array not printing the last element during comparison

I am trying to replace rows from an original 2d array to a updated 2d array. Problem is it won't store the last element during the replacement.
Here's my code:
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < updatedArray[i].length; j++){
for(int x = 0; x < originalArray.length;x++){
for(int z = 0; z < originalArray[x].length;z++){
if(originalArray[x][0].equals(updatedArray[i][0])) {
updatedArray[i][j] = originalArray[x][j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
}
}
System.out.println("originalArray:");
System.out.println(Arrays.deepToString(originalArray));
System.out.println("updatedArray:");
System.out.println(Arrays.deepToString(updatedArray));
For example, initially updatedArray in last row "purple" has {"purple","a","b","c"}. When it does the replacement using values from originalArray, the code above only outputs:
... [purple, nn, mm, bb]
which is wrong because it doesn't add the last element "hello". It should output:
... [purple, nn, mm, bb, hello]
I am aware the problem is in this line:
updatedArray[i][j] = originalArray[x][j];
Problem is no matter what I try to change originalArray[x][j] to originalArray[x][z] ... its screws up everything.
Any ideas on this? Still trying to get the jist of 2D arrays.
If there is a match, instead of trying to set each element in the updatedArray to the corresponding element in the original array you can just set the entire array to the original array.
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < originalArray.length; j++){
if(originalArray[j][0].equals(updatedArray[i][0])) {
updatedArray[i] = originalArray[j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
The issue is how you chose to iterate over the dimensions of updatedArray which are different than the dimensions of originalArray.
Let just look at the case i=2 which is the 'row' for purple:
for (int j = 0; j < updatedArray[i].length; j++){
updatedArray[i=2].length = 4
in updated:
index = 0 , 1 , 2 , 3
{"purple","a","b","c"}
in original:
index = 0 , 1 , 2 , 3 , 4
{"purple","nn","mm","bb","hello"}
Therefore since j will always be < 4 it can never be used to index originalArray[x][4] = "hello"
DANGER: this code also doesn't handle the fact that you would need to extend the purple array for updatedArray. Java may do some magic to handle this for you but I wouldn't trust it to work that way.
Suggestion:
- compare the lengths of each row and allocate extra memory where necessary before copying data from originalArray to updatedArray
- if possible just copy the whole row between original and updated.

A method to solve a word search in Java using 2d arrays.?

I'm trying to create a method that will search through a 2d array of numbers. If the numbers add up to a certain sum, those numbers should remain and all of the other numbers should be changed to a 0. For example, if the desired sum is 7 and a row contains 2 5 1 2, the result should be 2 5 0 0 after the method is implemented. I have everything functioning but instead of keeping all of the numbers that add up to the sum, only the last number is retained. So, I am left with 0 5 0 0 . I think I need another array somewhere but not sure exactly how to go about implementing it. Any ideas?
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int[][] b = new int[a.length][a[0].length];
int columnStart = 0;
while (columnStart < a[0].length) {
for (int row = 0; row < a.length; row++) {
int sum = 0;
for (int column = columnStart; column < a[row].length; column++) {
sum += a[row][column];
if (sum == sumToFind) {
b[row][column] = a[row][column];
}
}
}
columnStart++;
}
return b;
}
In your example you use 2 5 1 1, would 0 5 1 1 also be a valid response? Or do you just need to find any combination? A recursive function may be the best solution.
If you just need to scan through the array and add up the numbers until the sum is reached then just add a for loop to copy the previous values from the array to the new array when the sum is found. Something like:
if (sum == sumToFind)
{
for (int i= 0; i<= columnStart; i++)
{
b[row][i] = a[row][i];
}
}
if (sum == sumToFind)
{
for (int i= columnStart; i<= column; i++)
{
b[row][i] = a[row][i];
}
}
A minor tweak was all it needed. If you have columnStart and column like in the other answer, it only finds the first number of the series.

Categories