I am trying to rebuild a paragraph of words randomly without repeating the same word in JavaScript:
var para = 'dashing through the snow' +
' in a one horse open sleigh' +
' over the fields we go' +
' laughing all the way';
console.log(para);
function getRandomNumber(min, max)
{
return Math.floor(Math.random() * (max - min)) + min;
}
var words = para.split(' ');
var newPara = '';
for(var i = 0; i < words.length - 1; i++)
{
var curWord = words[getRandomNumber(0,words.length - 1)];
if(newPara.indexOf(curWord) == -1)
{
newPara += curWord + ' ';
console.log(newPara);
} else
{
i--;
}
}
The code splits a paragraph into an array of words (19 in all). I then use a loop to loop through this array and select a word at random, checking if the word has been added to the newPara string. If it has not, I add it. If it has, I subtract 1 from the loop run. The problem is that the script causes the browser to freeze when I use the else statement to subtract one from the loop. Any help on this problem is appreciated.
Based on comments I made this edit:
if(newPara.length <= words.length)
{
if(newPara.indexOf(curWord) == -1)
{
newPara += curWord + ' ';
console.log(newPara);
} else
{
i--;
}
}
However, I am still getting the same error.
else { i--; }?else { i-- }will subtract one from the loop run if the word already exists in the new paragraph. @Press I see what you are saying I think. You mean here:words[getRandomNumber(0,words.length - 1)];or do you meani--;