Today is an integer random replacement.
Remember: in Java, the basic data type is to pass the value, not to pass the reference.
1 package random replacement; 2 Import Java. util. *; 3 4 // generate random replacement of the First n integers 5 // first fill the entire array in order, then switch one by one to the previous random position. 6 7 public class randomexchange {8 9 public static void main (string [] ARGs) {10 // todo auto-generated method stub11 int [] A = suijizhihuan (6); 12 for (INT I = 0; I <. length; I ++) {13 system. out. print (A [I] + ","); 14} 15} 16 17 Private Static int [] suijizhihuan (INT N) {18 int [] suiji = new int [N]; 19 for (INT I = 0; I <n; I ++) {20 Suiji [I] = I + 1; 21} 22 random ran = new random (); 23 // I should start from 1 !!! 24 For (INT I = 1; I <n; I ++) {25 swap (suiji, I, ran. nextint (I); 26} 27 return suiji; 28 29} 30 // direct int temp = A; A = B; B = temp; the swap function of is not feasible. 31 // because the basic data type in Java is to pass the value rather than to pass the referenced 32 //, if an array exists, write the swap function 33 Private Static void swap (INT [] arr, int I, Int J) {34 int temp = arr [I]; 35 arr [I] = arr [J]; 36 arr [J] = temp; 37 38} 39 40}
Daily Record-