Write a program that produces random permutations of the numbers 1 to 10. eg. (1
ID: 3642658 • Letter: W
Question
Write a program that produces random permutations of the numbers1 to 10. eg. (1,4,7,10,2,9,8,3,6,5) or (10,7,9,2,1,3,6,5,4,8)
Your class should have the following methods:
// Displays the array permutatedNumbers to the console public void displayPermutedArray(){}
// Repeat the selection of a number 10 times to populate the permutated array public void generatePermutation(){}
Make an array to hold the permuted numbers. Make a second array and fill it with the numbers 1 to 10 in order.
Pick one of the numbers from the second array randomly, remove it, and write it to the permutation array.
Repeat this 10 times. Test the functionality in your main method by calls to the generatePermutation() and displayPermutedArray() methods.
Explanation / Answer
public class NumberPermutation {
private int[] permutatedNumbers;
public NumberPermutation() {
permutatedNumbers = new int[10];
}
public void displayPermutedArray() {
System.out.print("(" + permutatedNumbers[0]);
for (int i = 1; i < permutatedNumbers.length; i++) {
System.out.print("," + permutatedNumbers[i]);
}
System.out.println(")");
}
public void generatePermutation() {
int[] numbersPool = new int[10];
for (int i = 0; i < 10; i++)
numbersPool[i] = i + 1;
for (int i = 0; i < 10; i++) {
int poolIndex = (int)(Math.random() * (10 - i));
int j;
for (j = 0; j < 10 && poolIndex >= 0; j++)
if (numbersPool[j] != 0)
poolIndex--;
permutatedNumbers[i] = numbersPool[j - 1];
numbersPool[j - 1] = 0;
}
}
public static void main(String[] args) {
NumberPermutation perm = new NumberPermutation();
perm.generatePermutation();
perm.displayPermutedArray();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.