如何将1d数组转换为2d数组?

时间:2023-02-08 00:24:21

Say, I have a 1d array with 30 elements:

说,我有一个包含30个元素的1d数组:

array1d[0] = 1  
array1d[1] = 2  
array1d[2] = 3  
.  
.  
.  
array1[29] = 30

How to convert the 1d array to 2d array?
Say 10x3?

如何将1d数组转换为2d数组?说10x3?

array2d[0][0] = 1 array2d[0][1] =2 array2d[0][2] =3
.
.
.
array2d[9][0] = 28 array2d[9][1] =29 array2d[9][2] =30

Should I use a for loop?
But I cannot work it out.

我应该使用for循环吗?但我无法解决这个问题。

7 个解决方案

#1


14  

Without writing any code for you...

没有为你编写任何代码......

  • Think about how big your 2d array needs to be.
  • 想想你的2D阵列需要多大。
  • 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.
  • 使用for循环遍历1d数组。
  • 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.
  • 在for循环中,你需要弄清楚1d数组中每个值应该在2d数组中的位置。尝试对你的计数器变量使用mod函数来“环绕”2d数组的索引。

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

我故意模糊,因为这是作业。尝试发布一些代码,以便我们可以看到您遇到的问题。

#2


14  

int array2d[][] = new int[10][3];


for(int i=0; i<10;i++)
   for(int j=0;j<3;j++)
       array2d[i][j] = array1d[(j*10) + i]; 

#3


4  

public class Test{

    public static void main(String[] argv)
    {
        int x,y;
        for(int num =0; num<81;num++)
        {
            if((num % 9)>0)
            {
                x = num/9;
                y = num%9;

            }else
            {
                x = num/9;
                y = 0;
            }

            System.out.println("num ["+num+"]---["+x+","+y+"]");

        }
    }
}
/* Replace  9 by the size of single row of your 2D array */

#4


3  

Here a generic function to convert from 1D -> 2D array:

这里是从1D - > 2D数组转换的通用函数:

public int[][] monoToBidi( final int[] array, final int rows, final int cols ) {
    if (array.length != (rows*cols))
        throw new IllegalArgumentException("Invalid array length");

    int[][] bidi = new int[rows][cols];
    for ( int i = 0; i < rows; i++ )
        System.arraycopy(array, (i*cols), bidi[i], 0, cols);

    return bidi;
}

If you want to do the contrary (2D -> 1D), here the function:

如果你想做相反的事情(2D - > 1D),这里的功能如下:

public int[] bidiToMono( final int[][] array ) {
    int rows = array.length, cols = array[0].length;
    int[] mono = new int[(rows*cols)];
    for ( int i = 0; i < rows; i++ )
        System.arraycopy(array[i], 0, mono, (i*cols), cols);    
        return mono;
}

#5


1  

int[] oneDArray = new int[arr.length*arr.length];
    //Flatten 2D array to 1D array...
    int s = 0;
    for(int i = 0; i < arr.length; i ++) 
          for(int j = 0; j < arr.length; j ++){                           
              oneDArray[s] = arr[i][j];
              s++;
          } 

#6


1  

You often will find the same problem: how to manipulate 2D array as 1D array. I wrote a generic class Grid, that lets access objects by index or by (x,y).

您经常会发现同样的问题:如何将2D数组操作为1D数组。我写了一个泛型类Grid,它允许通过索引或(x,y)访问对象。

See the following class and understand the idea behind it. :)

请参阅以下课程并了解其背后的想法。 :)

You could use the following class for data manipulation as 2D array or 1D array. Here is the code for that I wrote and use.

您可以使用以下类作为2D数组或1D数组进行数据操作。这是我编写和使用的代码。

/**
 * Grid represents a 2 dimensional grid.
 *
 * @param <E> the type of elements in this grid
 */

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class Grid<E>
{
    private int     size    ;
    private int     width   ;
    private int     height  ;
    private List<E> elements;

    public int getCapacity()
    {
        return getWidth() * getHeight();
    }

    /**
     * @return number of elements in grid. Null is also an element.
     */
    public int getSize()
    {
        return getElements().size();
    }

    /**
     * @param sideSize size of the grid side
     */
    public Grid(int sideSize)
    {
        this(sideSize,sideSize);
    }

    /**
     * @param width of the grid
     * @param height of the grid
     */
    public Grid(int width, int height)
    {
        this.width  = width ;
        this.height = height; 
        this.elements = new ArrayList<E>(
                Collections.nCopies(width*height, (E)null));
    }

    public int getHeight()
    {
        return height;
    }

    public int getWidth()
    {
        return width;
    }

    /**
     * @return all elements of the grid
     */
    public List<E> getElements()
    {
        return elements;
    }

    /**
     * @return iterator for a grid
     */
    public Iterator<E> iterator()
    {
        return getElements().iterator();
    }

    /**
     * Returns the element at position (x,y).
     *
     * @return the element at position (x,y)
     */
    public E get(int x, int y)
    {
        return getElements().get(
                idx(x,y));
    }

    /**
     * Returns the element at index idx.
     *
     * @return the element at given index
     */
    public E get(int idx)
    {
        return getElements().get(idx);
    }

    /**
     * Puts an element to the position idx
     *
     * @param element to be added
     *
     * @param x position x to add element to
     *
     * @param y position y to add element to
     */
    public void put(int x, int y, E element)
    {
        put(idx(x,y), element);
    }

    /**
     * Puts an element to the position idx
     *
     * @param element to be added
     *
     * @param idx to add element at
     */
    public void put(int idx, E element)
    {
        getElements().add(idx, element);
    }

    /**
     * Returns the x coordinate from the index.
     *
     * @return x coordinate of the index
     */
    public int x(int idx)
    {
        return idx % getHeight();
    }

    /**
     * Returns the y coordinate from the index.
     *
     * @return y coordinate of the index
     */
    public int y(int idx)
    {
        return (idx - idx % getHeight()) / getHeight();
    }

    /**
     * Returns index of element at (x,y).
     *
     * @return index of the coordinates
     */
    public int idx(int x, int y)
    {
        return y*getHeight() + x;
    }
}

Here is how to use the class (see a test example):

以下是如何使用该类(参见测试示例):

public class TestGrid
{
    public static final int     SIZE = 10;
    public static final Integer el1  = new Integer(2);
    public static final Integer el2  = new Integer(3);
    public static final Integer el3  = new Integer(3);

    public static void main(String[] args)
    {
        Grid<Integer> grid = new Grid<>(SIZE);
        assert grid.getCapacity() == SIZE*SIZE ;

        assert grid.idx(0,0) == 0 ;
        assert grid.idx(1,0) == 1 ;
        assert grid.idx(0,1) == 10;
        assert grid.idx(6,1) == 16; 
        assert grid.idx(9,9) == 99;

        grid.put(1, el1);
        assert grid.get(1) == el1 : grid.get(1);

        grid.put(0, 1, el2);
        assert grid.get(0,1) != el1 && el1 != el2 && grid.get(0,1) == el2;

        grid.put(15, el3);
        assert grid.get(5,1) == el3;
    }
}

#7


-2  

You can't "convert" a 1D array to a 2D array, but an array can be multi-dimensionnal when you declare it.

您不能将1D数组“转换”为2D数组,但在声明时,数组可以是多维数组。

int myArray2d[][] = new int[10][3]

#1


14  

Without writing any code for you...

没有为你编写任何代码......

  • Think about how big your 2d array needs to be.
  • 想想你的2D阵列需要多大。
  • 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.
  • 使用for循环遍历1d数组。
  • 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.
  • 在for循环中,你需要弄清楚1d数组中每个值应该在2d数组中的位置。尝试对你的计数器变量使用mod函数来“环绕”2d数组的索引。

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

我故意模糊,因为这是作业。尝试发布一些代码,以便我们可以看到您遇到的问题。

#2


14  

int array2d[][] = new int[10][3];


for(int i=0; i<10;i++)
   for(int j=0;j<3;j++)
       array2d[i][j] = array1d[(j*10) + i]; 

#3


4  

public class Test{

    public static void main(String[] argv)
    {
        int x,y;
        for(int num =0; num<81;num++)
        {
            if((num % 9)>0)
            {
                x = num/9;
                y = num%9;

            }else
            {
                x = num/9;
                y = 0;
            }

            System.out.println("num ["+num+"]---["+x+","+y+"]");

        }
    }
}
/* Replace  9 by the size of single row of your 2D array */

#4


3  

Here a generic function to convert from 1D -> 2D array:

这里是从1D - > 2D数组转换的通用函数:

public int[][] monoToBidi( final int[] array, final int rows, final int cols ) {
    if (array.length != (rows*cols))
        throw new IllegalArgumentException("Invalid array length");

    int[][] bidi = new int[rows][cols];
    for ( int i = 0; i < rows; i++ )
        System.arraycopy(array, (i*cols), bidi[i], 0, cols);

    return bidi;
}

If you want to do the contrary (2D -> 1D), here the function:

如果你想做相反的事情(2D - > 1D),这里的功能如下:

public int[] bidiToMono( final int[][] array ) {
    int rows = array.length, cols = array[0].length;
    int[] mono = new int[(rows*cols)];
    for ( int i = 0; i < rows; i++ )
        System.arraycopy(array[i], 0, mono, (i*cols), cols);    
        return mono;
}

#5


1  

int[] oneDArray = new int[arr.length*arr.length];
    //Flatten 2D array to 1D array...
    int s = 0;
    for(int i = 0; i < arr.length; i ++) 
          for(int j = 0; j < arr.length; j ++){                           
              oneDArray[s] = arr[i][j];
              s++;
          } 

#6


1  

You often will find the same problem: how to manipulate 2D array as 1D array. I wrote a generic class Grid, that lets access objects by index or by (x,y).

您经常会发现同样的问题:如何将2D数组操作为1D数组。我写了一个泛型类Grid,它允许通过索引或(x,y)访问对象。

See the following class and understand the idea behind it. :)

请参阅以下课程并了解其背后的想法。 :)

You could use the following class for data manipulation as 2D array or 1D array. Here is the code for that I wrote and use.

您可以使用以下类作为2D数组或1D数组进行数据操作。这是我编写和使用的代码。

/**
 * Grid represents a 2 dimensional grid.
 *
 * @param <E> the type of elements in this grid
 */

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class Grid<E>
{
    private int     size    ;
    private int     width   ;
    private int     height  ;
    private List<E> elements;

    public int getCapacity()
    {
        return getWidth() * getHeight();
    }

    /**
     * @return number of elements in grid. Null is also an element.
     */
    public int getSize()
    {
        return getElements().size();
    }

    /**
     * @param sideSize size of the grid side
     */
    public Grid(int sideSize)
    {
        this(sideSize,sideSize);
    }

    /**
     * @param width of the grid
     * @param height of the grid
     */
    public Grid(int width, int height)
    {
        this.width  = width ;
        this.height = height; 
        this.elements = new ArrayList<E>(
                Collections.nCopies(width*height, (E)null));
    }

    public int getHeight()
    {
        return height;
    }

    public int getWidth()
    {
        return width;
    }

    /**
     * @return all elements of the grid
     */
    public List<E> getElements()
    {
        return elements;
    }

    /**
     * @return iterator for a grid
     */
    public Iterator<E> iterator()
    {
        return getElements().iterator();
    }

    /**
     * Returns the element at position (x,y).
     *
     * @return the element at position (x,y)
     */
    public E get(int x, int y)
    {
        return getElements().get(
                idx(x,y));
    }

    /**
     * Returns the element at index idx.
     *
     * @return the element at given index
     */
    public E get(int idx)
    {
        return getElements().get(idx);
    }

    /**
     * Puts an element to the position idx
     *
     * @param element to be added
     *
     * @param x position x to add element to
     *
     * @param y position y to add element to
     */
    public void put(int x, int y, E element)
    {
        put(idx(x,y), element);
    }

    /**
     * Puts an element to the position idx
     *
     * @param element to be added
     *
     * @param idx to add element at
     */
    public void put(int idx, E element)
    {
        getElements().add(idx, element);
    }

    /**
     * Returns the x coordinate from the index.
     *
     * @return x coordinate of the index
     */
    public int x(int idx)
    {
        return idx % getHeight();
    }

    /**
     * Returns the y coordinate from the index.
     *
     * @return y coordinate of the index
     */
    public int y(int idx)
    {
        return (idx - idx % getHeight()) / getHeight();
    }

    /**
     * Returns index of element at (x,y).
     *
     * @return index of the coordinates
     */
    public int idx(int x, int y)
    {
        return y*getHeight() + x;
    }
}

Here is how to use the class (see a test example):

以下是如何使用该类(参见测试示例):

public class TestGrid
{
    public static final int     SIZE = 10;
    public static final Integer el1  = new Integer(2);
    public static final Integer el2  = new Integer(3);
    public static final Integer el3  = new Integer(3);

    public static void main(String[] args)
    {
        Grid<Integer> grid = new Grid<>(SIZE);
        assert grid.getCapacity() == SIZE*SIZE ;

        assert grid.idx(0,0) == 0 ;
        assert grid.idx(1,0) == 1 ;
        assert grid.idx(0,1) == 10;
        assert grid.idx(6,1) == 16; 
        assert grid.idx(9,9) == 99;

        grid.put(1, el1);
        assert grid.get(1) == el1 : grid.get(1);

        grid.put(0, 1, el2);
        assert grid.get(0,1) != el1 && el1 != el2 && grid.get(0,1) == el2;

        grid.put(15, el3);
        assert grid.get(5,1) == el3;
    }
}

#7


-2  

You can't "convert" a 1D array to a 2D array, but an array can be multi-dimensionnal when you declare it.

您不能将1D数组“转换”为2D数组,但在声明时,数组可以是多维数组。

int myArray2d[][] = new int[10][3]