Question

I have a game of guessing words something like hangman.

This is the code I use to select a word from the words list:

List<string> words = GetWordsList();
int index = new Random().Next(words.Count);
string random = words[index];

Is there a better way to get a random item from the words list?

EDIT 1:

by better I mean (better performance or better randomness or other improvements to consider)

EDIT 2:

I call these lines every 15-30 seconds based on how much time it took to the player to guess the word.

EDIT 3:

I don't know if it is useful, but to have more information about the context, I remove the item from the list after these lines of code.

Was it helpful?

Solution

I would look at doing something like this:

var rnd = new Random();
var words = new Stack<string>(GetWordsList().OrderBy(w => rnd.Next()));

Then you just .Pop() the next value from the stack to get the next random word.

Just be mindful to instantiate the Random instance only once in your app to avoid producing non-random values related to calling your code in quick succession.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top