Randomly selecting from a list

Is there a way to randomly select an entry in a list?

Had this come up a couple times in my development and usually just work around it, but now asking the question. In this case, I have a list of people. The below works fine, but was curious if there was a more-official way.

ResearchAndDev is a room. 

Jamie is a person in ResearchAndDev. Sam is a person in ResearchAndDev. Henry is a person in ResearchAndDev. Ulwazi is a person in ResearchAndDev. Nuwa is a person in ResearchAndDev. Shifa is a person in ResearchAndDev.

IdleAction is a list of people that varies.
BoredPerson is a person that varies.

When play begins:
	now IdleAction is {Henry, Jamie, Nuwa, Sam, Shifa, Ulwazi};

The description of ResearchAndDev is "[BoredPerson] looks bored.".

Every turn when the player is in ResearchAndDev:
	sort IdleAction in random order;
	now BoredPerson is entry 1 of IdleAction;

I thought §21.9 in the documentation would get me there but I’ve missed it, if so.

I don’t think it’s a built-in thing, but:

To decide which K is a random element/value of/from (source - list of values of kind K):
	let count be the number of entries in source;
	if count is zero, decide on the default value of K; [potential issue]
	let N be a random number from one to count; 
	decide on entry N of source.

When play begins:
	showme a random value from {1, 2, 3, 4, 5};
	showme a random element of {"one", "two", "three", "four", "five"};
	let P be a list of things; [initializes empty list of things]
	showme a random element from P.

As you an see from the last line of the when play begins rule, a list with no entries will still return a probably-unexpected value, so some care is needed when using this phrase.

4 Likes

I don’t recall a built-in phrase for this, but to avoid sorting, you could:

Every turn when the player is in ResearchAndDev:
	let n be the number of entries in IdleAction;
	let bored be a random number from 1 to n;
	now BoredPerson is entry bored of IdleAction;

Edit: Otis got there first I see.

2 Likes