Results 1 to 2 of 2
  1. #1
    jwl
    jwl is offline Member
    Join Date
    Jul 2012
    Posts
    93
    Rep Power
    0

    Default 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 01:55 AM.

  2. #2
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: random array permutation

    And what problems specifically are you having with #3?

Similar Threads

  1. Replies: 5
    Last Post: 10-24-2012, 09:17 PM
  2. Need a help in two dimentaional permutation
    By venk123 in forum New To Java
    Replies: 7
    Last Post: 08-06-2011, 01:28 AM
  3. Permutation
    By Claymz in forum New To Java
    Replies: 4
    Last Post: 06-01-2011, 02:27 PM
  4. Replies: 3
    Last Post: 08-24-2009, 07:39 PM
  5. How to get a random value in an array
    By Franneldort in forum New To Java
    Replies: 21
    Last Post: 11-01-2008, 02:42 PM

Posting Permissions

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