hey,
I have been working on this bonus question due tomorrow for more than 4 hours total. This a just a part but I am not making good time with this and I am getting frustrated.
here is part of the question:
Write a function int[] RandomPermutation(int n) to create a random permutation of {0, 1, 2, ×××, (n − 1)}.
1. Create the initialize array nums[] = [0, 1, 2, ..., (n-1)].
2. Create a random number m in the range 0 to i.
3. Exchange nums[m] and nums[i].
4. Repeat steps (2)-(3) for i = n-1, n-2, ..., 1.
here is my code:
Code:package bonus;
import java.util.Random;
public class Bonus {
public int[] RandomPermutation(int n){
int[] nums = new int[n];
Random rand = new Random(0);
for (int i = 0; i < n; i++) {
nums[i] = i;
}
for (int i = n - 1; i > 0; --i) {
int m = rand.nextInt(i);
System.out.println(m);
System.out.println(nums[m] + " " + i);
}
return nums;
}
public static void main(String[] args) {
Bonus permutation = new Bonus();
permutation.RandomPermutation(10);
}
}
I am about to take a break but i will probably be working on this for the rest of the evening.
OK, I think I got steps one two and four taken care of here. Now I need to implement step 3.
