简体   繁体   中英

fill 2d array with 1d array java

I have an matrix and an array and I want to fill matrix from the array values.

float [][] mat = new float [m][n];
float [] array= new float [3];

For example :

arr = {1, 2, 3}

mat with size 4*4

mat =

        {1, 2, 3, 1

         2, 3, 1, 2

         3, 1, 2, 3

         1, 2, 3, 1}

What is the way to fill the matrix?

Based on your example, you want to use the values in the array to insert in line in the matrix.

First, let's build our matrix and array values :

int m = 3;
int n = 5;
float[][] mat = new float[m][n];
float[] array = {1,2,3,4};
    

Then, iterate the matrix to prepare the update :

for(int i = 0; i < m; i++){
    for(int j = 0; j < n; j++){
        // update here
    }
}

So, what you want is to use the array to set the value, when you reach the end, you start over. There is two solution I see :

Using an index

We increment it but use the modulo to get back to "0" when we reach the length of the array.

int currentIndex = 0;
for(int i = 0; i < m; i++){
    for(int j = 0; j < n; j++){
        mat[i][j] = array[currentIndex];
        currentIndex = (currentIndex + 1 ) % array.length;
    }
}

Using the matrix coordinate

Or you can get the index by doing the sum of both index of the matrix then using the modulo again, this allow to update any value without a loop, (if needed)

for(int i = 0; i < m; i++){
    for(int j = 0; j < n; j++){
        mat[i][j] = array[(i+j)%array.length];
    }
}

One problem with this solution, you will not get the correct output for a matrix where m + n > Integer.MAX_VALUE simply because the sum will give a negative value, give an incorrect index.

Output

You can see the result using :

System.out.println(java.util.Arrays.deepToString(mat));

Both solution give :

[
    [1.0, 2.0, 3.0, 4.0, 1.0],
    [2.0, 3.0, 4.0, 1.0, 2.0],
    [3.0, 4.0, 1.0, 2.0, 3.0]
]

It is not necessary to specify second array size: float [][] mat = new float [m][];

Here is an example how to declare matrix of array:

int m = 5;
float[][] mat = new float[m][];
float[] array = new float[3];
for (int i = 0; i < m; i++) {
    mat[i] = array;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM