There is an array of char. You must perform a random permutation. however, the elements should not be repeated. Suppose there is an array {1,2,3,4} after the permutation should be {2,3,4,1}

  • Random indices of array elements to help you. - Cooler
  • however, the elements should not be repeated. Suppose there is an array {1,2,3,4} after the permutation should be {2,3,4,1} - Ilya Chizhanov

2 answers 2

Elementary Watson. Randomly select 2 array indices, then swap them:

Random r=new Random(System.currentTimeMillis()); int index1, index2, array[]={1,2,3,4}; for(int i=0; i < 10; i++) { //iterating over elements index1=r.nextInt(array.length); index2=r.nextInt(array.length); int value=array[index1]; array[index1]=array[index2]; array[index2]=value; } for(int i=0; i < array.length; i++) System.out.print(array[i]+" "); System.out.println(); 

    for each element of the array, generate a random number in correspondence, for example, from 0 to 1,000,000. after that, sort the obtained numbers in ascending order, and with them the indices of the elements of the array.
    For example:
    [a, b, c, d] -> generate a random number for each element -> [123,23423,3452,12] -> sort the array with numbers in ascending order -> [12,123,3452,23423] -> and with it and indices of array elements whose elements need to be scattered -> [d, a, c, b]