简体   繁体   中英

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

[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 = 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 . 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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