Choose Your Language

Thursday, 6 June 2013

Generate Random Number Without Duplicate Using java

import java.util.ArrayList;
/**
 *
 * @author Aravind Sankaran
 */


public class RandomWithoutDuplicate
{
    public static void main(String[] args)
    {
        int[] randomOrdering = createRandomOrdering(10);
        for(int x : randomOrdering)
        System.out.println(x);
    }
   
    public static int[] createRandomOrdering(int length)
    {
        int[]       randomOrdering = new int[length];
        boolean[]   takenPositions = new boolean[length];
       
        int
            distanceToRemainingPosition,
            currentSearchPosition;
       
        for(int remainingPositions=length; remainingPositions>0; --remainingPositions)
        {
            distanceToRemainingPosition = (int)(Math.floor(Math.random()*remainingPositions))+1;
            currentSearchPosition = -1;
           
            do
            {
                currentSearchPosition++;
                if(!takenPositions[currentSearchPosition]) --distanceToRemainingPosition;
            }
            while( distanceToRemainingPosition>0 );
           
            randomOrdering[currentSearchPosition] = remainingPositions;
            takenPositions[currentSearchPosition] = true;
        }
       
        return randomOrdering;
    }

No comments:

Post a Comment