简体   繁体   中英

Converting ArrayList to 2D array

After figuring out a way pof create of list of random numbers from 1 to 16, how can I display this list in matrix form.

 public static void main(String... args) throws Exception {

 List<Integer> list = new ArrayList<Integer>();
 for (int i = 1; i < 17; i++) {
    list.add(i);
}
System.out.println(list); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Collections.shuffle(list);
System.out.println(list); //[11, 5, 10, 9, 7, 0, 6, 1, 3, 14, 2, 4, 15, 13, 12, 8]

int[][] a2 = new int[4][4];
for (int i = 0; i < 4; i++) {
    for (int j = 0;  j< 4; j++) {


        a2[i][j] = list.get(i*4 + j);
      //  System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1],     [3, 14, 2, 4], [15, 13, 12, 8]]
    }
   System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1], [3,     14, 2, 4], [15, 13, 12, 8]]
}
//System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1], [3, 14                  2, 4], [15, 13, 12, 8]]
}

Like this :
3, 4, 5, 8,
2, 6, 7, 9,
11, 1, 15, 13,
10, 12, 14, 0

I put a zero at the end because I want it to present a void that can be moved by the user, using boolean operators.

Your two for-loops breaks the list into a 2D array just fine.

To print the a2 matrix you could for instance do the following:

for (int[] row : a2) {
    System.out.print("[");
    for (int i : row)
        System.out.printf("%4d", i);
    System.out.println("]");
}

Result:

[   6  11   3   7]
[   4  14   5   9]
[   2  13  16  10]
[   8   1  12  15]

Something like this:

int index = 1;
for(Integer i : list) {
  System.out.print(i);
  if (index % 4 == 0)
    System.out.println();
  index++;
}

If you need ArrayList and Random, then you can use the following:

Random random = new Random();
ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();
for(int i=0;i<4;i++) {
    ArrayList<Integer> array = new ArrayList<Integer>();
    for (int j=0;j<4;j++) {
        array.add(random.nextInt(16)+1);
    }
    matrix.add(array);
}

And then you can simply iterate over the matrix and print each array.

for(ArrayList<Integer> array: matrix) {
    System.out.println(array);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM