Skip to content

Instantly share code, notes, and snippets.

@CSaratakij
Last active April 27, 2016 11:54
Show Gist options
  • Select an option

  • Save CSaratakij/1d48a24da8c61b387d4e62fbacb3a7a5 to your computer and use it in GitHub Desktop.

Select an option

Save CSaratakij/1d48a24da8c61b387d4e62fbacb3a7a5 to your computer and use it in GitHub Desktop.
My Java random pick by index example.
package javaapplication1;
import java.util.*;
public class JavaApplication1 {
public static void main(String[] args) {
Random rand = new Random();
List<Integer> lstNum = new ArrayList();
List<Integer> lstSelectedNum = new ArrayList();
//init list
for (int i = 1; i < 9; i++) {
lstNum.add(i);
}
//random select by index
while (lstNum.size() > 0) {
int index = rand.nextInt(lstNum.size());
int selectedNum = (int)lstNum.toArray()[index];
lstSelectedNum.add(selectedNum);
lstNum.remove(index);
}
//print all selected element
for (int i = 0; i < lstSelectedNum.size(); i++) {
System.out.println(lstSelectedNum.toArray()[i]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment