java - Randomly "shaking" an array to assign new random spots -
what im trying take array coins[]. , rearrange each coin different position. have far. when though, nothing happens. meaning values stay same. except last one. 1 changes.
public void shake() { (int = 0; < coins.length; i++) { int index = coin.random.nextint(coins.length); coin temp = coins[index]; coins[index] = coins[i]; coins[i] = temp; system.out.print(coins[i] + ", "); } }
i instantiate random this:
public static long seed = system.currenttimemillis(); public static random random = new random(seed);
as using swap index swapping current value can edit random number generator generate random numbers between range (say 0 - coins.length
) , can change implementation this
public void shake() { coin temp; (int = 0; < coins.length; i++) { //int swap = coin.random.nextint(coins.length); temp = coins[swap]; coins[swap] = coins[i]; coins[i] = temp; system.out.print(coins[i] + ", "); } }
for commented line in code check this update random number generator generate numbers between 2 values. each time generate swap(index) between i+1
- coins.length
, continue till exhaust array. ensures don't make swap @ index value have displayed. not confident indeed random shuffle in beginning of loop have more choices swap index have sometime later in loop , shake not random. solution in case want strictly implement own shake method without using collections.shuffle
@tomek mentioned.
Comments
Post a Comment