This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to generate random numbers without the numbers recurring  RSS feed

 
smyle khanna
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i want 2 know wht condition can i apply within the if loop 2 stop the recurring of numbers 4 atleast 4 iterations,
thanks........
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you could keep the last generated numbers in a List and use the contains() method to see if the newest is contained.
if not then remove the oldest and add the new.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or with a short list of possible values - 16 in your example - you can generate a complete list and "shuffle" it like a deck of cards. Then deal out the first "n" cards to get a random selection. Shuffling is kinda like:

This is common in card games and lottery number pickers. If your max might go into thousands, it would probably be slow.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shuffling is kinda like:
[ code omitted ]

Alternately, it's kinda like

Of course that does require you to use Integer wrappers, but that's not unusual.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!