Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The two permutation generation methods we will investigate proceed in a simlar m

ID: 3547646 • Letter: T

Question

The two permutation generation methods we will investigate proceed in a simlar manner. An array of items is set up. Then, for each index in the array, say i running from 0 to the length of the array minus 1, choose another index j at random. Then, swap the element at index i with the element at index j. Please note, as there has been some misunderstanding here: only j is chosen randomly, i simply steps through the array indexes.

The two methods differ only in the way that j is chosen:

Here is the method header:

It is very important that the method not modify the array base! Make a copy of the array before doing any modifications. If you don't follow this requirement, you will not see any difference between the two methods.

Explanation / Answer

import java.util.Random;


public class PermutationTest {

    public static void main(String[] args) {
        String[] strings = {"one", "apple", "two", "car", "lorry", "test"};
        String[] copyStr = new String[strings.length];
        for(int i=0; i < strings.length; i++) {
            copyStr[i] = strings[i];
        }
        System.out.println("Initial Array:");
        display(copyStr);
       
        generatePermutation(strings);
        System.out.println("Permutation -I Array:");
        display(strings);
       
        generatePermutation(strings);
        System.out.println("Permutation -II Array:");
        display(strings);

    }
    public static String[] generatePermutation(String[] base) {
        for(int i=0; i< base.length; i++) {
            int j = new Random().nextInt(i+1);
            String temp = base[i];
            base[i] = base[j];
            base[j] = temp;
        }
        return base;
    }
    public static String[] generatePermutation2(String[] base) {
        for(int i=0; i< base.length; i++) {
            int j = new Random().nextInt(base.length);
            String temp = base[i];
            base[i] = base[j];
            base[j] = temp;
        }
        return base;
    }
    public static void display(String[] str) {
        for(int i=0; i < str.length; i++) {
            System.out.print(str[i] + " ");
        }
        System.out.println();
    }

}
Output:

Initial Array:
one apple two car lorry test
Permutation -I Array:
lorry car two one apple test
Permutation -II Array:
one test two apple lorry car