Skip to content

Instantly share code, notes, and snippets.

@odinsbane
Created October 2, 2018 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odinsbane/50020aab213b96158624910b6165ee5e to your computer and use it in GitHub Desktop.
Save odinsbane/50020aab213b96158624910b6165ee5e to your computer and use it in GitHub Desktop.
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
public class NonRepeatingChoices{
static Random ng;
static int min = 1;
static int max = 49;
static int choices = 40;
static public int[] chooseAndCheck(){
int[] out = new int[choices];
for(int i = 0; i<choices; i++){
boolean selected = false;
while(!selected){
selected = true;
int next = ng.nextInt(max - min + 1) + min;
for(int k = 0; k<=i; k++){
if(out[k]==next){
selected=false;
break;
}
}
if(selected){
out[i] = next;
}
}
}
return out;
}
static public int[] shuffleAndSelect(){
List<Integer> ints = IntStream.rangeClosed(min, max).boxed().collect(Collectors.toList());
Collections.shuffle(ints, ng);
int[] out = new int[choices];
for(int i = 0; i<choices; i++){
out[i] = ints.get(i);
}
return out;
}
static public int[] chooseAndRemove(){
int[] out = new int[choices];
List<Integer> ints = IntStream.rangeClosed(min, max).boxed().collect(Collectors.toList());
for(int i = 0; i<choices; i++){
int dex = ng.nextInt(ints.size());
int choice = ints.get(dex);
ints.remove(dex);
out[i] = choice;
}
return out;
}
public static void main(String[] args){
long start;
int steps = 1000000;
int sum;
for(int j = 1; j<100; j++){
start = System.currentTimeMillis();
ng = new Random(j);
sum = 0;
for(int i = 0; i<steps; i++){
sum += chooseAndCheck()[0];
}
System.out.println(System.currentTimeMillis() - start + "ms repeat " + sum);
start = System.currentTimeMillis();
ng = new Random(j);
sum = 0;
for(int i = 0; i<steps; i++){
sum += shuffleAndSelect()[0];
}
System.out.println(System.currentTimeMillis() - start + "ms shuffle" + sum);
start = System.currentTimeMillis();
ng = new Random(j);
sum = 0;
for(int i = 0; i<steps; i++){
sum += chooseAndRemove()[0];
}
System.out.println(System.currentTimeMillis() - start + "ms remove" + sum);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment