[英]Unique values from random()
我有一个数组,我要在其中加载10张图像,如下所示:
int maxImages = 10; // Total # of images
int imageIndex = int(random(10)); // Initial image to be displayed is the first
// Declaring an array of images.
PImage[] images = new PImage[maxImages];
// Loading the images into the array
for (int i = 0; i < images.length; i ++ ) {
images[i] = loadImage( "assets/images/image" + i + ".jpg" );
}
当满足某些条件时,我将使用random()
生成一个新值,并将其保存在名为imageIndex
的新变量中。 如下所示:
imageIndex = int(random(images.length));
生成此图像后,我将以以下方式用新的随机数调用图像:
gameimages = loadImage( "assets/images/image" + imageIndex + ".jpg" );
上面的实现效果很好,但是有时会多次生成随机数,我希望它们从1-10唯一地随机化。 谁能建议我实现此目标的最佳方法?
使用集合洗牌:
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i = 0; i < images.length; i++) {
numbers.add(i+1);
}
Collections.shuffle(numbers);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.