Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate unique random number on each call

In a interview I was asked to wrtie a method which will generate unique 5 digit random number everytime when it is called.For ex: if I call the method and get 22222 then in next call i should not get 22222.

I wrote a code as below:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class RandomNumberGen {


    private static ArrayList arr=new ArrayList();
    private static int k=-1;
    public RandomNumberGen(){
        for (int i=10000;i<99999;i++){
            arr.add(i);
        }
        Collections.shuffle(arr);
    }
    public static void main(String[] args) {
        for(int m=0;m<10;m++){
            try {
                System.out.println(new RandomNumberGen().randomNumbermethod());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    }
    public Integer randomNumbermethod() throws Exception{
        k++;
        if(k>=arr.size()){
            throw new Exception("No more number available");
        }else return (Integer) arr.get(k);
    }

}

Answer got accepted but I was asked to avoid memory wastage now. My question is here as you can see I am using only 10 numbers.So rest of the space occupied by arraylist is a memory-wastage.Is there a way I can achieve same thing without using extra memory. What I mean is there someway using which unique number can be generated on each call so that this much memory do not get wasted.

like image 589
TheGraduateGuy Avatar asked Nov 28 '22 02:11

TheGraduateGuy


1 Answers

private static int number = 10000;
public int getNextUniqueRandomNumber() {
   return number++;
}

Random number generator

like image 95
Piotr Müller Avatar answered Dec 06 '22 09:12

Piotr Müller