# Thread: random array permutation

1. Member
Join Date
Jul 2012
Posts
93
Rep Power
0

## random array permutation

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:

Java 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.
Last edited by jwl; 11-15-2012 at 02:55 AM.

2. ## Re: random array permutation

And what problems specifically are you having with #3?

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•