我如何填写随机Java中的数组? [英] How do I randomly fill an array in Java?
本文介绍了我如何填写随机Java中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在写创建了一个从整数n的二维数组的程序。然后,我不得不从1填充值的数组到n * n的数组大小和检查,看看它是否是一个幻方。我现在正在做的方式填补,以n * n的数组大小数组1。我怎么能作出这样的乱?
我的code:
结果
System.out.print(输入一个整数:);
INT N = scan.nextInt(); INT [] [] =魔法INT新[N] [N]; 对于(INT行= 0;&行LT; magic.length;排++)
{
对于(INT COL = 0;&山坳LT;魔术[行]。长度;山坳++)
魔术[行] [COL] =((行* N)+ 1)+ COL;
}
解决方案
创建号码洗牌列表添加到您的阵列,像这样:
列表<整数GT;数=新的ArrayList<整数GT;();
的for(int i = 1; I< = n * n的;我++)numbers.add(I)
Collections.shuffle(数字); INT [] [] =魔法INT新[N] [N]; INT索引= 0;
对于(INT行= 0;&行LT; magic.length;排++)
{
对于(INT COL = 0;&山坳LT;魔术[行]。长度;山坳++)
魔术[行] [山口] = numbers.get(指数++);
}
I'm writing a program that creates a 2D array from a integer n. I then have to fill the array with values from 1 to the n*n array size and check to see if it is a magic square. The way I am doing it now fills the array in order from 1 to n*n array size. How can I make that random?
My code:
System.out.print("Enter an whole number: ");
int n = scan.nextInt();
int [][] magic = new int [n][n];
for (int row = 0; row < magic.length; row++)
{
for(int col = 0; col < magic[row].length; col++)
magic[row][col] = ((row * n) + 1) + col;
}
解决方案
create a shuffled list of numbers to add to your array, something like this:
List<Integer> numbers = new ArrayList<Integer>();
for (int i=1; i<=n*n; i++) numbers.add(i);
Collections.shuffle(numbers);
int [][] magic = new int [n][n];
int index = 0;
for (int row = 0; row < magic.length; row++)
{
for(int col = 0; col < magic[row].length; col++)
magic[row][col] = numbers.get(index++);
}
这篇关于我如何填写随机Java中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文