We are about to switch to a new forum software. Until then we have removed the registration on this forum.
hello all,
obviously an old problem. It occurs in different forms.
E.g. in a scrabble game we have to hand out letters to the players. But they are not distributed evenly over the Alphabet, so there are not as many Qs than Es in the game (reflecting the distribution of letters in normal English texts).
Let's therefore assume, I make a char array, where this distribution is reflected, so it's
EEEEEEEEEQAAAAAAMMOO
or so.
Now retrieving elements from this list randomly:
When I retrieved a letter I can't retrieve it again. I can replace it with a character that is a stop sign like #.
EEEEE#EEEQAAAAAAMMOO
But then when retrieving a letter later in the game, most slots hold #-signs.
##E################O#
So a typical random like
randomNumberIndex = int(random(listOfLetters.length()));
would most times fail, so I would have to repeat it until hitting a letter. Bad.
But what is the most efficient way of solving this? An ArrayList and then shorten the ArrayList ?
Thanks!
Best, Chrisir ;-)
Answers
Shuffle the array! Then pick each
char
from beginning to end. *-:)A pity Processing doesn't provide a shuffle() array utility like it does for sort(). :(
There's 1 for p5.js. It's a piece of cake to convert it to Java: :)>-
https://GitHub.com/processing/p5.js/blob/master/src/utilities/array_functions.js#L207-#L223
thanks a lot!
You were fast! Here's mine as well. Just finished it: :P
thanks a lot!
shuffle is much better than shortening an ArrayList on the way as my first idea was........ ;-)
Well, for lists, how about IntList? It's got a shuffle() method already: *-:)
https://Processing.org/reference/IntList_shuffle_.html
Besides
int[]
, we can use it forchar[]
,short[]
,byte[]
and evenboolean[]
.Just use int() to convert the array type to
int[]
, passing it to IntList's constructor:https://Processing.org/reference/intconvert_.html
After shuffle(), use array() to get an
int[]
again from it:https://Processing.org/reference/IntList_array_.html
Finally, use char(), byte() or boolean() in order to get the original array type back: :ar!
Of course, that's miles slower than implementing our own shuffle() for each desired array type. 8-X
P.S. Shuffle already exists -
Collections.shuffle()
I was asking that for doing Scrabble...
;-)
And I used
Collections.shuffle()
;)But, as you already know, I posted that because that's what this forum is for - if anyone wants to shuffle, they can find it here now.
char[]
arrays. \m/@GoToLoop I didn't suggest you don't know, just that others on this forum may not know.