簡體   English   中英

如何將一維數組轉換為二維數組?

[英]How to convert a 1d array to 2d array?

說,我有一個包含 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循環嗎?
但我無法解決。

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

無需為您編寫任何代碼...

  • 想想你的二維數組需要多大。
  • 認識到您需要遍歷源數組的內容才能將每個值放入目標數組。

所以它看起來像......

  • 創建一個適當大小的二維數組。
  • 使用 for 循環遍歷一維數組。
  • 在 for 循環中,您需要弄清楚一維數組中的每個值應該放在二維數組中的哪個位置。 嘗試對您的計數器變量使用 mod 函數來“環繞”二維數組的索引。

我故意含糊其辭,因為這是家庭作業。 嘗試發布一些代碼,以便我們了解您遇到的問題。

這里有一個從 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;
}
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 */

你經常會發現同樣的問題:如何將二維數組作為一維數組進行操作。 我編寫了一個通用類 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;
    }
}
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++;
          } 
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]);

        }
    }}

這行得通

這只是一個偽代碼。 ROWS 表示二維數組的長度,COLUMNS 表示數組中第一個元素的長度

for(i=0; i<ROWS; i++)
   for(j=0; j<COLUMNS; j++)
       array2d[i][j] = array1d[ (i*COLUMNS) + j];

您不能將一維數組“轉換”為二維數組,但聲明數組時可以是多維數組。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM