Generate Random numbers without using any external functions

后端 未结 9 978
梦如初夏
梦如初夏 2020-12-08 16:26

This was questions asked in one of the interviews that I recently attended.

As far as I know a random number between two numbers can be generated as follows

9条回答
  •  春和景丽
    2020-12-08 16:39

    public class randomNumberGenerator {
    
        int generateRandomNumber(int min, int max) {
            return (int) ((System.currentTimeMillis() % max) + min);
        }
    
        public static void main(String[] args) {
            randomNumberGenerator rn = new randomNumberGenerator();
            int cv = 0;
            int min = 1, max = 4;
            Map hmap = new HashMap();
    
            int count = min;
            while (count <= max) {
                cv = rn.generateRandomNumber(min, max);
                if ((hmap.get(cv) == null) && cv >= min && cv <= max) {
                    System.out.print(cv + ",");
                    hmap.put(cv, 1);
                    count++;
                }
            }
    
        }
    }
    

提交回复
热议问题