Java: Random number in fixed range excluding specified number -
in (java android) game, spawn coins @ random positions.
coins can appear @ 1 of 6 positions horizontally across screen (2 max per horizontal level).
what create random number between 0 , 5 first coin, want generate random number excluding position of first coin.
so, example, coin 1 spawned @ random position between 0 , 5 - let's 4.
then next coin needs able choose between 0-3 or 5. (basically 0-5 excluding 4).
i have managed it, it's not elegant , i'm sure there must better/cleaner way achieve this, however, escapes me.
the random(int number) method in code below returns random int 0 number-1 (uses nextint) , randombool() returns random boolean
also, please bear in mind don't want use technique keeps re-generating random number if 1 produces equal 1 trying avoid.
code
//return random number between 0 , 5 excluding specified number private int getrandomexcluding(int excludednumber){ //if previous position 0 generate number between 1 , 5 if (excludednumber==0){ return random(5)+1; } //if position 5, generate , return number 0-4 else if (excludednumber==5){ return random(5); } //if number isn't 0 or 5 (then in range of 1-4 use random bool determine // if going number less or greater number excluding //true - number lower excluded number else if(randombool()){ //excluded number 1 if (excludednumber==1){ return 0; //only posibility } //excluded number > 1 else { //return random number between 0 (inclusive) , excluded number (exclusive) return random(excludednumber); } //false - number higher excluded number (between exludednumber+1 (inclusive) , 6(exlusive)) else { return random(6-(excludednumber+1))+(excludednumber+1); } }
you populate list , shuffle it:
list<integer> numbers = arrays.aslist(1, 2, 3, 4, 5); collections.shuffle(numbers); int coin1 = numbers.get(0); int coin2 = numbers.get(1);
Comments
Post a Comment