Choosing a random entry from a list

This is one of those things for which it really feels as though there should be an inbuilt phrase, but I can’t find one.

Eventually, I gave up and wrote this (which works):

To decide which K is a random entry listed/-- from/in (L - list of values of kind K):
	[if L is empty, decide on the default value of K; [if uncommented, this line avoids a runtime error in the case of an empty list- but in most instances we probably want instead to be sure that L is not empty before invoking this phrase]]
	decide on entry (a random number from 1 to the number of entries in L) from L.

Am I missing something obvious?

1 Like

I agree. One can be synthesized from the pieces in place:

To decide which K is a random entry/element listed/-- from/in (L - list of values of kind K):
	(- LIST_OF_TY_GetItem({L}, random(LIST_OF_TY_GetLength({L}))) -).
2 Likes

I think it should throw a runtime problem if you choose a random value from an empty list, honestly. Better to let the author know there’s a problem than to silently return the wrong value.

2 Likes

It’s weird because you can choose a random entry from a single-row table…

Table 1 - Creatures
Name
cat
chair
llama

instead of waiting:
	choose a random row in the Table of Creatures;
	let c be the Name entry;
	say "You try to examine [c].";
	try examining c;
1 Like

Yeah, it feels like an oversight

Testing this in 10.1 throws an error

It works in 9.3, though

So do I, generally.

I had missed a capital (LiST_ instead of LIST_), which apparently matters more in Inter. Fixed above – thanks for pointing it out!

1 Like

Thank you for sharing this awesome solution :smiley: It’d be lovely if it could be part of a more extensive library of useful list and table functions