I have some java code as :
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
// do someything
}
However, I want the code to randomly skip X percentage of tokens.
Example : If tokens are [a , b , c , d] and skip percentage is 50% Valid execution could be printing any two tokens, say [ b , c ] or [a , d] etc
How can I implement it in the simplest manner?
First Solution:
double percentage = 50.0;
int max = (int)percentage * token.length;
int[] skip = new int[token.length];
int count = 0;
while(count < max)
{
int rand = rnd.nextInt(token.length);
if(skip[rand] == 0){
skip[rand] = 1;
count++;
}
}
//Use a for loop to print token where the index of skip is 0, and skip index of those with 1.
You may consider this. Create a 1D array of switches (Can be boolean too). Generate 1D array of random switches with size similar to token length. Print token element if switch of the corresponding index is true, else don't print.
Second solution:
Convert your token of array to an arrayList.
int count = 0, x = 0;
while(printed < max){ //where max is num of elements to be printed
int rand = rnd.nextInt(2); //generate 2 numbers: 50% chance
if (rand == 0){
System.out.println(list.get(x);
list.remove(x);
printed ++;
}
x++;
}
Roll a probability (e.g. 50% chance) whether to print current element for every iteration. Once element is printed, remove it from list, so you won't print duplicates.
Third solution:
Randomly remove a percentage (e.g. 50%) of elements from your token. Just print the rest. This is probably one of the most straight forward way I can think of.