Claire
Claire

Reputation: 3184

How To Randomize Sentence Length From Array

There is probably a simple solution to this, but for some reason I can't seem to find it on the site, or elsewhere on the net. Just trying to produce a sentence of RANDOM LENGTH from an array. Here is an example:

var words = ["yes", "ok", "java", "pull my hair out", "sleep"];

Here is the code that I'm currently using to randomize the contents of the array, but it always produces a sentence where every string is used once. I want varying sentence lengths.

function fisherYates(words) {
var i = words.length, j, tempi, tempj;
if ( i == 0 ) return false;
while ( --i ) {
   j = Math.floor( Math.random() * ( i + 1 ) );
   tempi = words[i];
   tempj = words[j];
   words[i] = tempj;
   words[j] = tempi;
   }
   return words;
}

Suggestions?

Upvotes: 3

Views: 208

Answers (2)

RobG
RobG

Reputation: 147403

If you don't want repeated strings, copy the array and splice random members from it to form the new collection. Just splice off a random number of strings from random positions.

function randWords(arr) {

  // Copy original array
  arr = arr.slice();

  // Random number of words to get
  var len = (Math.random() * arr.length + 1)|0;
  var result = [];

  // Randomly fill result from arr, don't repeat members
  while (len--) {
    result.push(arr.splice(Math.random()*arr.length|0, 1));
  }
  return result;
}

console.log( randWords(["yes", "ok", "java", "pull my hair out", "sleep"]).join(' ') );

Upvotes: 1

Aadit M Shah
Aadit M Shah

Reputation: 74204

I would suggest you select a random number m from 1 to n inclusive (where n is the maximum length of the sentence you want). Then you randomly select m items from the array and put them into a new array:

var words = ["yes", "ok", "java", "pull my hair out", "sleep"];

alert(randomize(words, 10).join(" ") + ".");

function randomize(array, maximum) {                 // array, n
    var length = Math.ceil(maximum * Math.random()); // m
    var result = new Array(length);
    var count  = array.length;
    var index  = 0;

    while (index < length) {
        result[index++] = array[Math.floor(count * Math.random())];
    }

    return result;
}

Hope that helps.

Java Sex

Perhaps not.

Upvotes: 2

Related Questions