Home > Back-end >  Randomize wordset javascript array
Randomize wordset javascript array

Time:11-06

I found the following code for randomization of one word but what I need is randomization of a word pair 2 words. How can I do this?

let words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];

let getRandomWord = function () {
    return words[Math.floor(Math.random() * words.length)];
};

let word = getRandomWord();

console.log(word);

document.getElementById("word").textContent = word;

CodePudding user response:

I hope the commented code below helps you:

let words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];

let getRandomWord = function () {
    return words[Math.floor(Math.random() * words.length)];
};

//generating first word
let word1 = getRandomWord();
let word2
do{
    //getting the second word and making sure it is diferent from the first word
    word2 = getRandomWord();
}while(word1==word2)

console.log(word1, word2);
document.getElementById("word").textContent = word1   ' '   word2;

CodePudding user response:

you can simply shuffle your array

const words = 
  [ 'monitor', 'program', 'application', 'keyboard'
  , 'javascript', 'gaming', 'network'
  ]
for (let i = words.length; --i;)  // shuffle Array
  {
  let j = Math.floor(Math.random() * (i   1));
  [words[i], words[j]] = [words[j], words[i]]
  }

// get 2 random words
console.log( words[0], words[1] )
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

A standard algorithm to select a random number, say r elements from an array, n long is as follows - the trick is to move the last element to the position you just selected then reduce n by 1.

    function select(arr,r){
        let out=[];
        let n=arr.length;
        for (let i=0;i<r;i  ){
            let j=Math.floor(Math.random()*n);
            out.push(arr[j])
            if(j<n-1) arr[j]=arr[n-1];
            n--;
        }
        return out;   //contains the random selection
    }
  • Related