Convert a 2D array index into a 1D index

后端 未结 5 1358
说谎
说谎 2020-12-15 20:49

I have two arrays for a chess variant I am coding in java...I have a console version so far which represents the board as a 1D array (size is 32) but I am working on making

5条回答
  •  长情又很酷
    2020-12-15 21:14

    You could use this ArrayConvertor class to convert 2D arrays in 1D arrays and back.

    Beware: Converting a 2D array to a normal one does only work with a matrix.

    public class ArrayConvertor {
        static public int[] d2Tod1(int[][] array){
    
            int[] newArray = new int[array.length*array[0].length];
    
            for (int i = 0; i < array.length; ++i) 
            for (int j = 0; j < array[i].length; ++j) {
                newArray[i*array[0].length+j] = array[i][j];
            }
    
            return newArray;
        }
    
        static public int[][] d1Tod2(int[] array, int width){
    
            int[][] newArray = new int[array.length/width][width];
    
            for (int i = 0; i < array.length; ++i) {
               newArray[i/width][i%width] = array[i];
            }
    
            return newArray;
        }
    }
    

    And Some testing code:

    public class JavaMain{
        public static void main(String[] args) {
            int[][] arr2D_1 = new int[4][8];
    
            byte counter=0;
            for (int i = 0; i < 4; i++) 
            for (int j = 0; j < 8; j++) {
                arr2D_1[i][j] = counter++;
            }
    
            int[]arr1D = ArrayConvertor.d2Tod1(arr2D_1);
            int[][] arr2D_2 = ArrayConvertor.d1Tod2(arr1D, 8);
    
            boolean equal = true;
            for (int i = 0; i < arr2D_1.length; i++) 
            for (int j = 0; j < arr2D_1[0].length; j++){ 
                if(arr2D_1[i][j]!=arr2D_2[i][j]) equal=false;
            }
    
            System.out.println("Equal: "+equal);
        }
    }
    

    Output: Equal: true

提交回复
热议问题