generate k distinct number less then n

Posted by davit-datuashvili on Stack Overflow See other posts from Stack Overflow or by davit-datuashvili
Published on 2010-05-16T21:00:28Z Indexed on 2010/05/16 21:10 UTC
Read the original article Hit count: 148

Filed under:

hi i have following question task is this generate k distinct positive numbers less then n without duplication my method is following first create array size of k where we should write these numbers int a[]=new int[k]; //now i am going to cretae another array where i check if (at given number position is 1 then generate number again else put this number in a array and continue cycle i put here a piece of code and explanations

int a[]=new int[k];
int t[]=new int[n+1];
Random r=new Random();
  for (int i==0;i<t.length;i++){
   t[i]=0;//initialize it to zero
}
   int m=0;//initialize it also
  for (int i=0;i<a.length;i++){
    m=r.nextInt(n);//random element between  0 and  n   
  if (t[m]==1){
       //i have  problem with this i want in case of duplication element occurs repeats this steps afain until there will be different number

 else{
   t[m]=1;
x[i]=m;
}
}

so i fill concret my problem if t[m]==1 it means that this element occurs already so i want to generate new number but problem is that number of generated numbers will not be k beacuse if i==0 and occurs duplicate element and we write continue then it will switch at i==1 i need like goto for repeat step or

 for (int i=0;i<x.length;i++){
loop:
  m=r.nextInt(n);
if ( x[m]==1){
  continue loop;
}
  else{
    x[m]=1;
a[i]=m;
   continue;//continue next step at i=1 and so on

}
}

i need this code in java please help

© Stack Overflow or respective owner

Related posts about algorithm