java - preventing redundant random numbers -
i'm trying random numbers 0 - 499 in sets of 2 based on user inputs. example 234 , 58, , thats 1 set, user may prompt wan 8 sets. im trying make sure redundant number doesnt show up, 234 & 58, 12 & 444, 198 & 58. (58 showed twice.)
the way im trying prevent putting found numbers array , when go around next match im checking in array make sure havent been used yet. wondering best way of be. on first go around no numbers have been chosen yet dont need check. next go around if redundant? numbers , check array, , if in array how go , new numbers? while loop maybe?
here im doing:
//now add specified number of random connections system.out.println(); system.out.println("new connection(s): "); //array keeping track of new connections prevent redundant add's int redundant [] = new int[con*2]; for( int = 1; <= con; i++ ){ random ran = new random(); if( == 1){ int ran1 = ran.nextint(sworld.length-1) + 1; int ran2 = ran.nextint(sworld.length-1) + 1; redundant[i - 1] = ran1; redundant[i] = ran2; system.out.println(" " + ran1 + " - " + ran2); } else{ int ran1 = ran.nextint(sworld.length-1) + 1; int ran2 = ran.nextint(sworld.length-1) + 1; //need }
thanks in advance!
edit. going maethod below (using collections)
list<integer> nums = new linkedlist<integer>(); for( int = 0; <= 499; i++ ){ nums.add(i); } //shuffle collection more randomness system.out.println(); system.out.println("new connection(s): "); (int x = 1; x <= con; x++){ collections.shuffle(nums); random ran = new random(); int r1 = nums.remove(ran.nextint(nums)); int r2 = nums.remove(ran.nextint(nums));
but having trouble getting random numbers, help?
one way create list of number 0-499
list<integer> nums = new linkedlist<integer>(); for(int i=0; i<=499; i++) nums.add(i);
then shuffle the list
collections.shuffle(nums);
then each time need non-recurring random number between 0-499, remove element list
int x = nums.remove()
Comments
Post a Comment