How to Convert a One-Dimensional Array to Two-Dimensional Array in Java

How to convert a one-dimensional array to two-dimensional array in Java

After the line

int[] sum= Convert(stockArr); 

you have your entire file in a 1D array of integers. At this point, you have to determine the width and height of the 2D array.

Let's say you want the 2D array to have 3 rows and 4 columns as an example. Do this:

int[][] int_table = new int[3][4];
for(int j = 0; j < 3; j++)
{
for(int i = 0; i < 4; i++)
{
int_table[j][i] = sum[j * 4 + i];
}
}

The equation I'm using within sum's index is a conversion function that goes from 1D to 2D coordinates. Starting at both j and i being equal to 0, sum[j * 4 + i] = sum[0 * 4 + 0] = sum[0]. The variable i would increment by one at the next step, and we would have sum[0 * 4 + 1] = sum[1]. At the end of the row, i would reset to 0 and j would increment by 1. At that point, we would have sum[1 * 4 + 0] = sum[4], or sum's fifth element. This makes sense if you consider the first four elements as those of the first row. now that we're on a new row, we can fill it with the next four. The "four" that I've been mentioning is the width of the row that we defined earlier while declaring the 2D array.

Keep in mind that the 2D array's width and height can't multiply together to be larger than the total number of integers in the 1D array. You'll get an IndexOutOfBoundsException if you try to read beyond that size.

Converting a 1D array to a 2D array

You're assigning the wrong value to arr[i][j]:

for (int i = 0; i <arr.length ; i++) {
for (int j = 0; j <arr[j].length ; j++) {
arr[i][j] = array[i * arr[j].length + j];
}
}

Convert two dimensional array to one dimensional array in Java

We create a single Integer array with a length determines by the size method. Size takes the 2-dimensional array and finds the sum of all columns in each row and returns that sum. We check if the length is 0, and if so, we return. We then loop through all rows, followed by a loop through all columns in that row. We then assign the value at that row and column to that next index in the array. Unfortunately we can't do any math (to my knowledge) to determine the index based of row/column since they could be variable sizes.

    public static int[] twoDConvert(int[][] nums) {
int[] combined = new int[size(nums)];

if (combined.length <= 0) {
return combined;
}
int index = 0;

for (int row = 0; row < nums.length; row++) {
for (int column = 0; column < nums[row].length; column++) {
combined[index++] = nums[row][column];
}
}
return combined;
}

private static int size(int[][] values) {
int size = 0;

for (int index = 0; index < values.length; index++) {
size += values[index].length;
}
return size;
}

Dividing a 1D array into a 2D array

Change the 2D array's initialization to not contain the second dimension: new int[rows][]. Your array now has null arrays inside it. You have to initialize those in your loop: b[i]=new int[Math.min(columns,remainingCount)]; where remainingCount is the amount of numbers outside the 2d array.

In java how do I put two one-dimensional arrays into one two-dimensional array?

int[] x1 = { 1, 2, 3, 4, 5 };
int[] x2 = { 6, 7, 8, 9, 10 };
int[][] y = { x1, x2 };

for(int i=0;i<y.length;i++){
for(int k=0;k<y[i].length;k++){
System.out.println(y[i][k]);
}
}

here you have a working example. this should help you with your problem

full one-dimensional array in a two-dimensional array java

I don't know if this makes sense in your application/context, but for performance reasons you should normally have coherent data as close in the memory as possible.

For Arrays (double[row][column]) that means that data which is has the same row value is normally stored very close in the memory. For example when you have an Array like double[][] d = double[10][10] and save two values like d[0][0] = 1.0; d[1][0] = 2.0;, then they are (I think) 40 bytes away from each other.

But when you save them like d[0][0] = 1.0; d[0][1] = 2.0;, they're directly next to each other in the memory and are normally loaded into the super-fast cache at the same time. When you want to use them iteratively, then that is a huge performance gain.

So for your application, a first improvement would be this:

public double[][] getResult(double[] data, int rowSize) {
int columnSize = data.length;
double[][] result = new double[rowSize][columnSize];
for (int i = 0; i < columnSize; i++) {
result[0][i] = data[i];
}
return result;
}

Secondly, you have to consider whether you are going to re-use the data-Array or not. Because if you don't re-use it, you can just set the reference of the first row in your result Array to the data-Array like this:

result[0] = data;

Again, this gives you another huge performance gain.

Why? Well simply because you don't need to use unnecessary much memory by copying all values - and as you might know, memory allocation can be rather slow.

So always re-use memory instead of copying it wildly.

So my full suggestion is to go with this code:

public double[][] getResult(double[] data, int rowSize) {
double[][] result = new double[rowSize][];
result[0] = data;
return result;
}

It is optional whether you set the columnSize or not.

How can you convert a 2 dimensional array into a 1 dimensional array in Java

public static String[] flatten(String[][] data) {
ArrayList<String> list = new ArrayList<String>();

for(int i = 0; i < data.length; i++) {
for(int j = 0; j < data[i].length; j++){
list.add(data[i][j]);
}
}

return list.toArray(new String[0]);
}

Or add whole rows at one time:

    for(int i = 0; i < data.length; i++) {
list.addAll( Arrays.asList(data[i]) );
}

Edit:
From comments on my answer it seems like this is what the OP wanted (i.e. converting each row of 2d array to some string representation of it):

public static String[] rowsToString(String[][] data) {
ArrayList<String> list = new ArrayList<String>();

for(int i = 0; i < data.length; i++) {
String row = Arrays.toString(data[i]);
list.add( row.substring(1, row.length()-1) );
}

return list.toArray(new String[0]);
}

How to convert a 1d array to 2d array?

Without writing any code for you...

  • Think about how big your 2d array needs to be.
  • Recognize that you'll need to loop over the contents of your source array to get each value into your destination array.

So it will look something like...

  • Create a 2d array of appropriate size.
  • Use a for loop to loop over your 1d array.
  • Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.

I'm being intentionally vague, seeing as this is homework. Try posting some code so we can see where you get stuck.

How efficiently to convert one dimensional array to two dimensional array in swift3

You can write something like this:

var pixels: [UInt8] = [0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15]
let bytesPerRow = 4
assert(pixels.count % bytesPerRow == 0)
let pixels2d: [[UInt8]] = stride(from: 0, to: pixels.count, by: bytesPerRow).map {
Array(pixels[$0..<$0+bytesPerRow])
}

But with the value semantics of Swift Arrays, all attempt to create new nested Array requires copying the content, so may not be "efficient" enough for your purpose.

Re-consider if you really need such nested Array.



Related Topics



Leave a reply



Submit