我需要采用集合{0,.5,1,2,5}并用值随机填充一个nxm矩阵,我认为我可以使用此代码
public static void main(String[] args) {
//create the grid
final int rowWidth = 10;
final int colHeight = 10;
Random rand = new Random();
int [][] board = new int [rowWidth][colHeight];
//fill the grid
for (int[] board1 : board) {
for (int col = 0; col < board1.length; col++) {
board1[col] = rand.nextInt(5);
}
}
//display output
for (int[] board1 : board) {
for (int j = 0; j < board1.length; j++) {
System.out.print(board1[j] + " ");
}
System.out.println();
然后只需将每个数字{0,1,2,3,4}映射到{0,.5,1,2,5},然后重绘矩阵....有没有更好的方法...我如何从一开始就用指定的数字随机填充矩阵?
您可以保持一个数组容纳可能的值,然后从该数组中随机选择一个:
final int rowWidth = 10;
final int colHeight = 10;
final double[] possibleValues = {0.0, 0.5, 1.0, 2.0 ,5.0};
Random rand = new Random();
double[][] board = new double[rowWidth][colHeight];
for (double[] board1 : board) {
for (int col = 0; col < board1.length; col++) {
board1[col] = possibleValues[rand.nextInt(possibleValues.length)];
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句