2

I am creating a hangman game and I am selecting a random word from a pre-defined array.

Like so:

// Select random word to guess
function getWord() {
  var a = new Array('one', 'two', 'three', 'four');
  return a[parseInt(Math.random() * a.length)];
}

Is what I would like to do is to stop it choosing the same word twice or more. Currently, when using a small array of words, it sometimes repeats the same word 2 or 3 times in a row.

I am not quite sure how to go about combatting this.

First I thought maybe inserting the word into a new variable and then comparing but not sure that is a great way to do.

Any ideas wuld be helpful. Thanks!

DLaverick
  • 655
  • 5
  • 16
  • 1
    You could [shuffle the array](http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array), and retrieve values from 0 to length - 1. – Teemu Mar 02 '15 at 13:03
  • You could use [`indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) method – hindmost Mar 02 '15 at 13:05

1 Answers1

2

You can remove the element at the random position with array splice and then when your array length is 0, re-initialize it
something like this:

var all_words = [];
function getWord() {
    if (all_words.length === 0) {
        all_words = new Array('one', 'two', 'three', 'four');
    }
    var randIndex = parseInt(Math.random() * all_words.length);
    var chosenWord = all_words.splice(randIndex, 1);
    return chosenWord;
}

Here a demo.

Tommaso Bertoni
  • 2,333
  • 1
  • 22
  • 22
  • 1
    `var a = new Array('one', 'two', 'three', 'four'); function getWord() { return a.splice(parseInt(Math.random() * a.length), 1)[0]; }` – dfsq Mar 02 '15 at 13:11