Friday, December 20, 2013 0 comments

Unique Random Algorithm

I want to make program that can generate random numbers. How should I do?
It can be done by using the function that already been provided by the library such as Random().

The thing comes out when we want unique random numbers. How should I do?
Step 1, generate random number and insert it into first element of an array.
Step 2, generate random number and check whether the random number is already exist in the array or not.
If the result is already exist, then repeat step 2.
If the result is not exist, then insert the random number to the next element of the array.

Here is the implementation in Java Programming Language:
import java.util.Random;

public class UniqueRandomAlgorithm {

    public static void main(String[] args) {
        printArray1D(generateUniqueRandom(50));
    }

    public static int[] generateUniqueRandom(int n) {
        int[] num = new int[n];
        Random a = new Random();
        int x = a.nextInt(n) + 1;
        num[0] = x;
        if (n > 1) {
            x = a.nextInt(n) + 1;
            int i = 1;
            while (i < n) {
                if (isSameNumber(num, x)) {
                    x = a.nextInt(n) + 1;
                } else {
                    num[i] = x;
                    i++;
                }
            }
        }
        return num;
    }

    public static boolean isSameNumber(int[] num, int x) {
        boolean result = false;
        for (int i = 0; i < num.length; i++) {
            if (num[i] == x) {
                result = true;
                break;
            }
        }
        return result;
    }

    public static void printArray1D(int[] num) {
        for (int i = 0; i < num.length; i++) {
            System.out.println("Number " + (i + 1) + " = " + num[i]);
        }
    }
}


Here is the implementation in C# Programming Language:
using System.IO;
using System;

class Program
{
    static void Main()
    {
        printArray1D(generateUniqRandom(50));
    }
    
    static int[] generateUniqRandom(int n) {
        int[] num = new int[n];
        Random a = new Random();
        int x = a.Next(n)+1;
        num[0] = x;
        if (n > 1) {
            x = a.Next(n)+1;
            int i = 1;
            while (i < n) {
                if (isSameNumber(num, x)==1) {
                    x = a.Next(n)+1;
                } else {
                    num[i] = x;
                    i++;
                }
            }
        }
        return num;
    }
    
    static int isSameNumber(int[] num, int x) {
        int result = 0;
        for (int i = 0; i < num.Length; i++) {
            if (num[i] == x) {
                result = 1;
                break;
            }
        }
        return result;
    }
    

    static void printArray1D(int[] num) {
        for (int i = 0; i < num.Length; i++) {
            Console.WriteLine("Number " + (i + 1) + " = " + num[i]);
        }
    }
}
 
;