Reputation: 309
I need to get dataset from values (prepared set) when every value should appear at least once on random positions.
After running the following code this condition satisfied only sometimes. How is possible to improve the generation?
private static Random rand = new Random();
private static int N = 5;
public static void main(String[] args){
List<String> indexList = new ArrayList<>();
indexList.add("aaa");
indexList.add("bbb");
indexList.add("ccc");
indexList.add("ddd");
List<String> generatedDataList = new ArrayList<String>();
for (int i=0; i<=5; i++) {
String generatedIndex = getRandomValue(indexList);
System.out.println("Step " + i+ ": " + generatedIndex);
generatedDataList.add(generatedIndex);
}
}
static String getRandomValue(List<String> list){
return list.get(rand.nextInt(list.size()));
}
Upvotes: 0
Views: 37
Reputation: 37645
If you want every string to appear at least once, the best way is to add all the strings right at the beginning, then add just two random String
s, and finally shuffle the list.
List<String> generatedDataList = new ArrayList<String>(indexList);
for (int i = 0; i < 2; i++)
generatedDataList.add(getRandomValue(indexList));
Collections.shuffle(generatedDataList);
Upvotes: 1
Reputation: 4690
You can shuffle the indexList
by using the Collections.shuffle method, easy:
Collections.shuffle(indexList)
Upvotes: 1