0

I am trying to generate a random string output from an array that's getting triggered at random times. The issue that I am facing now is, sometimes the same output comes out twice in a row, or even more than two times. I wanted the output to be different every single time it gets triggered. I don't want the next output to be the same as the very previous output. Please take a look at the code below. Thanks!

function randAnnouncement() {
  var lastIndex, ann = ["one", "two", "three"];
  let randomAnnouncement = ann[Math.floor(Math.random() * ann.length)];
  //speakTTS(randomAnnouncement);
  console.log(randomAnnouncement);
}

function init() {
  var myFunction = function() {
    randAnnouncement();
    var rand = Math.round(Math.random() * (5000 - 1000)) + 500; // generate new time (between x sec and x + 500"s)
    setTimeout(myFunction, rand);
  }
  myFunction();
}

init();
rich
  • 71
  • 7
  • So you don't want a random output then. But if you don't want the same output as the last just store a reference to the last item and keep retrieving until they don't match. – pilchard Dec 01 '22 at 09:39
  • [randomize](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) it in `init` and then just pick the next item (e.g. `randomized.pop()`) – gog Dec 01 '22 at 09:48

1 Answers1

1

What you are asking for is a random string generator without replacement on the last selected value. The only way to do this is to store the last value somewhere so you can exclude it or repeat the random selection if the same value is selected.

As the web is stateless (i.e. doesn't remember the last value when the page reloads), I suggest that you create a transient or store the last value and read it again before each test.

Another option is to increase the size of the dataset from which your random selection is made. In your example of only 3 values, there is a 33% chance that the same value is selected again. Whereas if you had say 200 values then there would be only 0.5% change of a repeat value occurring.

I hope that this helps you get a solution that you can use.

Clinton
  • 1,111
  • 1
  • 14
  • 21