I have a list of ints that I need to add to a two-dimensional array.
ArrayList<Integer> myList = new ArrayList<Integer>(size);
//Generation
if(size % 2 != 0) {
System.out.println("need nombre pair");
} else {
int x = 0;
while (x != 2) {
for (int i = 0; i >= size/2; i++) {
int n = (int)Math.random() * 10;
if(!myList.contains(n))
myList.add(n);
}
x++;
}
}
Collections.shuffle(myList);
Once my list is shuffled, I want to add all the ints to a two-dimensional array ( int[][]
). How do I do this?
You could split your list into multiple subLists and convert those into arrays, one for each column of the table:
Integer[][] table = new Integer[width][];
for (int x = 0; x < width; x++) {
table[x] = myList.subList(width * x, width * x + height).toArray(new Integer[height]);
}
Here's a method that will generate a 2D array that meets your requirements:
private static int[][] makeArray(int columns, int rows) {
int totalItems = rows * columns;
if (totalItems % 2 != 0) {
throw new IllegalArgumentException("Must be an even number of cells.");
}
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < totalItems / 2; i++) {
numbers.add(i);
numbers.add(i);
}
Collections.shuffle(numbers);
Iterator<Integer> iterator = numbers.iterator();
int[][] result = new int[columns][rows];
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
result[x][y] = iterator.next();
}
}
return result;
}
Here's a small main method to test it:
public static void main(String[] args) throws Exception {
int[][] array = makeArray(3, 4);
for (int i = 0; i < 3; i++) {
System.out.println(Arrays.toString(array[i]));
}
}
Example output:
[0, 5, 1, 0]
[3, 1, 5, 2]
[4, 3, 2, 4]
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.