If the number range is 0 - 10. I would like to generate the following numbers
开发者_高级运维e.g.
unique 5 numbers [3, 8, 5, 1, 9]
unique 3 numbers [2, 6, 5]
5 numbers of which 2 numbers occur twice [2, 3, 2, 6, 3]
7 numbers of which 2 numbers occur twice [2, 5, 9, 2, 7, 5, 3] (Here 2, 5 occur twice)
5 numbers of which 1 number occur thrice [2, 3, 8, 3, 3] (Here 3 occurs twice)
7 numbers of which 1 number occur thrice and 1 number occurs twice [1, 5, 9, 1, 1, 5, 3] (Here 1 occurs thrice, 5 occurs twice)
How would you implement a generic function which caters to the above requirements.
EDIT1:
This is what I have right now..
protected List<Integer> fetchOverlapIntegers(int min, int max,
int howMany, int overlap) {
// The following code fetches unique numbers within the range
List<Integer> numbers = this.fetchRandomIntegers(min, max, howMany);
if (overlap > 0) {
int size = numbers.size();
for (int i = 0; i < overlap; i++) {
numbers.set(size - 1 - i, numbers.get(i));
}
}
Collections.shuffle(numbers);
return numbers;
}
Just for grins I wrote this up for this very underspecified problem:
public static List<Integer> weirdFunction(List<Integer> criteria, List<Integer> candidateNumbers) {
List<Integer> results = new ArrayList<Integer>();
for (int occurrenceCount = 0; occurrenceCount < criteria.size(); occurrenceCount++) {
int thisMany = criteria.get(occurrenceCount);
for (int i=0; i < thisMany; i++) {
Integer theChoice = candidateNumbers.get(new Random().nextInt(candidateNumbers.size()));
for (int ct=0; ct < occurrenceCount; ct++) {
results.add(theChoice);
}
}
}
Collections.shuffle(results);
return results;
}
It takes two lists, one which is the criteria
which is basically a list of how many times it'll place a randomly chosen number in the results (the 1st one gets chosen once, the 2nd twice, etc.), and a list of candidateNumbers
from which they'll be chosen.
But, this way only allows you to specify one particular "count" for each criteria. e.g. you can't have a list where "two numbers appear twice" because "appear twice" only has one slot. You could make this a list of lists or some other data structure of course.
Also, it doesn't eliminate duplicates when it pulls them in. So if we had a criteria
of {1, 1, 1}
it'd try and pull one number once, one number twice, and one number thrice. But it doesn't check if any of those are the same number - so it could end up pulling the same number each time and effectively pulling just one number six times instead of 3 separate numbers once, twice, and thrice.
You can randomly pull out items from the list of contender values, for example:
List<int> numbers = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Random r = new Random();
for (int i = 0; i < 4; i++)
{
int index = r.Next() % numbers.Count;
Console.WriteLine(numbers[index]);
numbers.RemoveAt(index);
}
If you want a value tripled, just triple the first removed. Then shuffle your results at the end.
精彩评论