random()的唯一值

时间:2014-12-04 21:33:31

标签: java arrays random processing

我有一个数组,我在其中加载了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开始随机化。任何人都可以建议我实施这个的最好方法吗?

1 个答案:

答案 0 :(得分:2)

使用集合shuffle:

ArrayList<Integer> numbers = new ArrayList<Integer>();    
for(int i = 0; i < images.length; i++) {       
    numbers.add(i+1);     
}      
Collections.shuffle(numbers);
相关问题