How to create unique random numbers from a given random number generator

Write an efficient algorithm to print the following two outputs

You are given a predefined function called getrand100 () that returns an integer that is one random number from 1 to 100. You can call as many times as you want, but be careful that this function is quite resource intensive. You cannot use any other random generator. You cannot change the definition of getrand100 ().

int getrand100(){
    Random rand = new Random();
return (1+rand.nextInt(100));      
}
  • Output1: print numbers 1-20 in random order. (Not 20 random numbers)
  • Output2: print numbers 1-200 in random order. (Not 200 random numbers)

Note:

  • I am. Each number should be printed exactly once.
  • II. .
    .. .
  • III. getrand100() , randomnumber 1 100.
  • IV. - , getrand100().
+5
3

, .

1) 1-20 100 1-20.

2) 1-200, 1 200, (-1 0) , 1 200.

import java.util.*;
public class Rand20_200{
   int number20[]=new int[20]; //numbers in random order
   int number200[]=new int[200];

   public Rand20_200(){
    int n=0;
    int ngen[]=new int[20]; //to store which random numbers are generated
    while(n<20){
      int rnd=1 + (getrand100()-1) / 5;
      if (ngen[rnd-1]==0){
        ngen[rnd-1]=1;
        number20[n++]=rnd;
      }
    }
    System.out.println("Random 20 numbers");
    print(number20);

    ngen=new int[200]; //to store which random numbers are generated
    int numoff[]={-1,0}; //offset to add
    n=0;
    while(n<200){
      int rnd=numoff[(getrand100()-1)/50]+ (getrand100()*2);
      if (ngen[rnd-1]==0){
     ngen[rnd-1]=1;
     number200[n++]=rnd;
      }
    }   
    System.out.println("\nRandom 200 numbers");
    print(number200);
   }

   int getrand100(){
    Random rand = new Random();
    return (1+rand.nextInt(100));      
   }

   void print(int arr[]){
     for(int i=0;i<arr.length;i++){
       System.out.print(arr[i]+" ");
     }
   }

   public static void main(String args[]){
     new Rand20_200();
   }

 }
+3

, , .:)

%

+2

You can create a list with your value (1 - 20, 1 - 200) and a random number, and then sort the list by random number.

public class RandomListItem
{
    int value;
    int sortindex;

    public RandomListItem(x,y)
    {
        value = x;
        sortindex = y;
    }
}

for(int i = 1; i <= maxvalue; i++)
{
    list.add(new RandomListItem(i, getrand100());
}

This may not be so good for a list of 200, as you can generate random numbers up to 100. You might want to use getrand100 () * getrand100 () or something to create a wider range of random numbers.

0
source

All Articles