java - How to create unique random numbers from a given Random generator -


write efficient algorithm print following 2 outputs 

you given pre-defined function named getrand100() returns integer 1 random number 1-100. can call function many times want beware function quite resource intensive. cannot use other random generator. cannot change 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. every number should printed once.
  • ii. there should no pattern in numbers listing. list should random
    i.e., numbers have equal probability appearing @ place.
  • iii. may call getrand100() number of time randomnumber 1 100.
  • iv. cannot use other random generator function except getrand100().

the idea use random generator given compute required random numbers.

1) random numbers 1-20, divide 100 numbers equally represent 1 20.

2) generate 1-200, find numbers 1 200 , add (-1 or 0) numbers 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 random numbers 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 random numbers generated     int numoff[]={-1,0}; //offset 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();    }   } 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -