Last active
April 27, 2016 11:54
-
-
Save CSaratakij/1d48a24da8c61b387d4e62fbacb3a7a5 to your computer and use it in GitHub Desktop.
My Java random pick by index example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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