如何将一个一维数组转换为二维数组?

13

假设我有一个包含30个元素的一维数组:

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

如何将一维数组转换为二维数组?
例如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

我应该使用for循环吗?
但我无法解决它。

9个回答

17
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]; 

谢谢!如果我的数组元素不是连续数字,而是随机数字怎么办?我该如何修改循环来实现? - kafter2
1
他的代码与数组中包含的内容无关,因此它适用于任何数组元素。 - TimCodes.NET
10
array2d[i][j] = array1d[(j10) + i]; 是错误的。应该是array2d[i][j] = array1d[j%3+i3]; - compski
这对我来说不起作用。我尝试使用它将图像颜色代码的1D int数组转换为2D数组,但生成的图像旋转了90度。 - You'reAGitForNotUsingGit
arr2d[i][j] = (int) arr1d[(i*3)+j]; 也可以工作。 - Cuong Trinh

17

不需要为您编写任何代码...

  • 考虑需要多大的2D数组。
  • 认识到您需要循环遍历源数组的内容,以获取每个值并放入目标数组中。

所以它看起来像这样...

  • 创建适当大小的二维数组。
  • 使用for循环遍历您的一维数组。
  • 在该for循环内,您需要确定1D数组中的每个值在2D数组中应该放置在哪里。尝试使用模函数针对计数器变量来“环绕”2D数组的索引。

我有意地保持含糊,因为这是家庭作业。尝试发布一些代码,以便我们可以看到您在哪里被卡住。


5

这是一个通用的将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;
}

如果你想做相反的操作(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;
}

这对我来说不起作用。我尝试使用它将图像颜色代码的1D int数组转换为2D数组,但生成的图像旋转了90度,并且还有垂直线穿过它。 - You'reAGitForNotUsingGit

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 */

5
请勿提供只有代码而没有解释的答案。 - dmportella

2

你经常会遇到同样的问题:如何将二维数组视为一维数组进行操作。我写了一个通用类Grid,可以通过索引或(x,y)来访问对象。

看下面的类并理解其中的思想。:)

你可以使用以下类来作为二维数组或一维数组进行数据操作。这是我编写和使用的代码。

/**
 * 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;
    }
}

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

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;
    }
}

1
这只是一个伪代码。ROWS代表二维数组的长度,而COLUMNS代表数组中第一个元素的长度。
for(i=0; i<ROWS; i++)
   for(j=0; j<COLUMNS; j++)
       array2d[i][j] = array1d[ (i*COLUMNS) + j];

1
package com.vikrant;

import java.util.Arrays;

public class TwoD {
    public static void main(String args[])
    {
        int a[][]=new int[4][3];
        int d[]={10,20,30,40,50,60,70,80,90,100,110,120};
        int count=0;
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<3;j++)
            {
                if(count==d.length) break;
                a[i][j]=d[count];
                count++;
            }}
        int j=0;
        for (int i = 0; i<4;i++)
        {
            for(j=0;j<3;j++)
        System.out.println(a[i][j]);

        }
    }}

这个可以完成工作


1
欢迎来到SO。感谢您的回答。虽然仅提供代码的答案可能会提供可工作的代码,但有些人可能会难以理解代码的作用。请尝试详细说明您的代码片段。 - Korashen

0
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++;
          } 

8
顺便提一下,原帖是针对相反的方向的。 - Paul Rigor

-2

你不能将一维数组“转换”为二维数组,但是在声明时可以将数组定义为多维数组。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接