java 数组一维转二维

public static void main(String[] args) {

    int[] datas = init();
    int[][] a1 = convert(datas, 2, 5);
    int[][] a2 = convert(datas, 5, 2);
    show(a2,a1);

}

/**
 * 初始化
 * @return
 */
public static int[] init() {
    int[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    return data;
}

/**
 * 一维转二维
 * @param datas
 * @param w
 * @param h
 * @return
 */
public static int[][] convert(int[] datas, int w, int h) {
    int[][] data = new int[h][w];
    int index = 0;
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            index = i * w + j;
            data[i][j] = datas[index];
            System.out.print("[" + (index) + "] " + data[i][j] + " ");
        }
        System.out.println();
    }
    System.out.println();
    return data;
}

public static void show(int[][] a1, int[][] a2) {
    for (int i = 0; i < a1.length; i++) {
        for (int j = 0; j < a1[0].length; j++) {
            System.out.print(a1[i][j] + " " + a2[j][i] + " ");
        }
        System.out.println();
    }
}

你可能感兴趣的:(java,算法,开发语言)