Randomly generating sequence of ints in a specific range
I am unsure how to put this and my math skills aren't that strong. But here's what I need.
I want to generate a list of all the 16bit integers (0-65535). But everytime I do so I want to seed the algorithm randomly that each time the list starts wit开发者_Go百科h a different integer and all the subsequent integers will be generated once but also in random order.
small example (1-5): ...
1, 5, 3, 2, 4
4, 3, 1, 5, 2
2, 1, 4, 5, 3 ...
Any help?
The easiest way is probably to generate the list of required numbers and then shuffle it.
Assuming you have no security requirements, possibly the easiest method is to create a Linear Congruential Generator (LCG) and select a new multiplier and/or increment every time you need to change the sequence. Using the notation from the Wikipedia entry, if you want all k-bit integers, your modulus is m=2k and conditions 1, 2, and 3 simplify to:
1. c is odd
2. a = 1 + 4*x for any integer x
There are other generators that are similar to LCG that should be just as satisfactory.
- Create a list of integers. In your example from 1 to 5 inclusive;
- Perform a correct shuffle on it. For example, the Fisher-Yates shuffle. The "correct" part is important as an incorrect shuffle algorithm will yield biased results.
You don't say what language you use but here are two:
PHP
$arr = range(1, 5);
shuffle($arr);
Java
List<Integer> list = new ArrayList<Integer>();
for (int i=1; i<=5; i++) {
list.add(i);
}
Collections.shuffle(list);
精彩评论