Java,如何按行和列拆分数组多维

时间:2015-03-25 07:47:12

标签: java arrays multidimensional-array

我有问题如何拆分数组以制作区域

我的数组是:

            1,   2,  3,  4,  5,  6
            7,   8,  9, 10, 11, 12
            13, 14, 15, 16, 17, 18
            19, 20, 21, 22, 23, 24
            25, 26, 27, 28, 29, 30
            31, 32, 33, 34, 35, 36

如果我设置row = 3和第3列,结果必须:

 1  2  3
 7  8  9
13 14 15
 4  5  6
10 11 12
16 17 18
19  20  21
25  26  27
31  32  33
22 23 24
28 29 30
34 35 36

我的问题是,只有

 1  2  3
 7  8  9
13 14 15

这是我的源代码

    int dataArray[][] = new int[][]{
        {1, 2, 3, 4, 5, 6},
        {7, 8, 9, 10, 11, 12},
        {13, 14, 15, 16, 17, 18},
        {19, 20, 21, 22, 23, 24},
        {25, 26, 27, 28, 29, 30},
        {31, 32, 33, 34, 35, 36}
    };


    int row = 3;
    int column = 3;

    int zone = 4;
    int copyArray[][] = new int[row][column];


    int countJ = 0, countK = 0;

    for (int j = 0; j < row; j++) {
        for (int k = 0; k < column; k++) {
            copyArray[countJ][countK] = dataArray[j][k];
            copyArray[countK][countJ] = dataArray[k][j];
            countK++;
        }
        countK = 0;
        countJ++;
    }

    for (int i = 0; i < zone; i++) {
        System.out.println(Arrays.deepToString(copyArray));
    }

}

谢谢你提前

1 个答案:

答案 0 :(得分:0)

案件已经解决..

  int dataArray[][] = new int[][]{
        {1, 2, 3, 4, 5, 6},
        {7, 8, 9, 10, 11, 12},
        {13, 14, 15, 16, 17, 18},
        {19, 20, 21, 22, 23, 24},
        {25, 26, 27, 28, 29, 30},
        {31, 32, 33, 34, 35, 36}};

    int baris = 3;
    int kolom = 3;
    int lebarZona = 2;
    int tinggiZona = 2;
    int counterTinggi = 0;
    ArrayList<int[][]> daftarZona = new ArrayList<int[][]>();
    counterTinggi = 0;
    int counterBaris = 0;
    int counterKolom = 0;

    for (int i = 0; i < tinggiZona; i++) {
        for (int j = 0; j < lebarZona; j++) {
            int copyArray[][] = new int[baris][kolom];

            for (int k = 0; k < baris; k++) {
                System.arraycopy(dataArray[counterBaris], counterKolom, copyArray[k], 0, kolom);
                counterBaris++;
            }

            daftarZona.add(copyArray);
        }
        counterBaris = 0;
        counterKolom += kolom;
    }

    for (int i = 0; i < daftarZona.size(); i++) {
        System.out.println(Arrays.deepToString(daftarZona.get(i)));
    }



    /*
     * Result : 
     * [[1, 2, 3], [7, 8, 9], [13, 14, 15]]
     *[[19, 20, 21], [25, 26, 27], [31, 32, 33]]
     *[[4, 5, 6], [10, 11, 12], [16, 17, 18]]
     *[[22, 23, 24], [28, 29, 30], [34, 35, 36]]
     */

谢谢大家