I’ve got a bunch of constant lists from which I would like to choose random entries. Is there a nice way to do this? This doesn’t compile:
Every turn: say a random entry in {1, 2, 3, 4, 5}.
I suppose I could define a random entry from a list by getting the length of the list, choosing N randomly from 1 to the length, and choosing the Nth entry, but is there a quicker way to do it?
To decide what thing is a random member of (L - a list of things):
let N be the number of entries in L;
let K be a random number between 1 and N;
decide on entry K of L.
Which doesn’t seem totally satisfactory, because it’d require a new definition if you wanted to choose from a list of numbers – but I only have lists of one kind of thing, so it works for me.
To decide what thing is a random member of (L - a list of values):
let N be the number of entries in L;
let K be a random number between 1 and N;
decide on entry K of L.
Thanks Victor and George! Victor, somehow I missed your post when I posted the second time; I’d thought of that, too, but this is something I’ll be calling several times a turn, and resorting the lists seems like it’d be too computationally intensive.
To decide what K is a random member of (list - list of values of kind K):
let the count be the number of entries in the list;
let the index be a random number between one and the count;
decide on entry index of the list.
See WI 21.7.