简体   繁体   English

从整数数组创建随机整数

[英]Creating a random integer from an array of integers

Is it possible to generate pseudo random integers from an integer array?是否可以从整数数组生成伪随机整数? I don't mean picking a random integer from an array, but instead doing something like我的意思不是从数组中选择一个随机整数,而是做类似的事情

[1,2,3] = 4542 [1,2,3] = 4542

[56,89,42] = 80421 [56,89,42] = 80421

Finally, is it possible to have the output be completely random, instead of gradually changing?最后,是否有可能让输出完全随机,而不是逐渐变化? Eg I would like this not this .例如,我想要这个而不是这个

Thanks for any input.感谢您提供任何意见。

Edit: I have tried using the hashcode in the following code.编辑:我尝试在以下代码中使用哈希码。 (The reason I don't just use random is I need to be able to access the random output without looping sometimes) (我不只是使用 random 的原因是我需要能够访问随机输出而不有时循环)

Random random = new Random();
int size = 10;
for (int x = 0; x < size; x++) {
  for (int y = 0; y < size; y++) {
    for (int z = 0; z < size; z++) {
      System.out.println(random.nextInt());
    }
  }
}
System.out.println();
for (int x = 0; x < size; x++) {
  for (int y = 0; y < size; y++) {
    for (int z = 0; z < size; z++) {
      System.out.println(Arrays.hashCode(new int[]{x, y, z}));
    }
  }
}

For the first section of code I get random numbers eg对于代码的第一部分,我得到随机数,例如

-733673840
2005335778 
-954776008
-695687646
-1339170035
...

For the second section I get numbers which increment by one对于第二部分,我得到的数字增加一

29791
29792
29793
29794
29795
...

You could hash your input array, and use the single hash value to seed an instance of Random .您可以散列您的输入数组,并使用单个散列值来播种Random的实例。 This is taken from Bloch:这取自布洛赫:

int myHash(int[] seedAry) {
  int result = 17;
  for (int s : seedAry) {
    result = 31 * result + s;
  }
  return result;
}

Use the returned hash value to seed an instance of Random .使用返回的哈希值来播种Random的实例。

Random ng = new Random();
for(int i: seedArray){
    outint = ng.setSeed(i).nextInt();
}

It will always give the same set of output ints, unless have changes the random number generator.除非更改随机数生成器,否则它将始终提供相同的输出整数集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM