Print and output an array in disorder.
This question provides three ideas and corresponding code:
Method 1: Create a new array, store a random number of the old array into the new array, and check whether the number is in the new array. If yes, continue. If no, insert it, but there is luck, because the random extraction may already exist in the new array;
Method 2: Create a new array, store a random number of the old array into the new array, and delete the number from the old array. The number will not be randomly drawn next time;
Method 3: Use the collection knowledge Collections. shuffle () to disrupt and then output.
Public class LuanxuPrint {
Public static void main (String [] args ){
Int [] arr = {2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
Int [] newArr = new int [arr. length];
Print1 (arr, newArr );
Print2 (arr, newArr );
Print3 (arr, newArr );
}
Public static void print3 (int [] arr, int [] newArr ){
ArrayList <Integer> list = new ArrayList <Integer> ();
ArrayList <Integer> newList = new ArrayList <Integer> ();
For (Integer I: arr ){
List. add (I );
}
Collections. shuffle (list );
System. out. print (list );
}
Public static void print2 (int [] arr, int [] newArr ){
ArrayList <Integer> list = new ArrayList <Integer> ();
ArrayList <Integer> newList = new ArrayList <Integer> ();
For (Integer I: arr ){
List. add (I );
}
While (list. size ()> 0 ){
Int ran = (int) (Math. random () * (list. size ()));
// System. out. print (ran + "");
If (! NewList. contains (list. get (ran ))){
NewList. add (list. get (ran ));
} Else {
List. remove (list. get (ran ));
}
}
System. out. print (newList );
}
Public static void print1 (int [] arr, int [] newArr ){
Int count = 0;
While (true ){
Int ran = (int) (Math. random () * (arr. length ));
// System. out. print (ran + "");
If (! Exist (arr [ran], newArr )){
NewArr [count ++] = arr [ran];
}
If (count = arr. length ){
Break;
}
}
System. out. println ();
For (Integer I: newArr ){
System. out. print (I + "");
}
}
Public static boolean exist (int ran, int [] newArr ){
For (int I = 0; I <newArr. length; ++ I ){
If (newArr [I] = ran ){
Return true;
}
}
Return false;
}
}