-1

I need to generate a different array each time in JS , where it's length should be exact 16 elements , each element should be between 0 to 7 , and each element should occur exactly twice. for eg. [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] or [0,1,2,3,4,5,6,7,7,6,5,4,3,2,1,0]

I need a function that will generate different array each time.

let sequence=[0,1,2,3,4,5,6,7]
let seq1=[0,1,2,3,4,5,6,7]
let seq2=[0,1,2,3,4,5,6,7]
let arr1=[]
let arr2=[]
let arr3

function generateArray(arr,seq){
    for(let i=0;i<8;i++){
        let numb=Math.trunc(Math.random()*(seq.length))
        arr.push(seq[numb])
        seq.splice(numb,1)
    }
}

generateArray(arr1,seq1)
generateArray(arr2,seq2)

arr3=[...arr1,...arr2]
console.log(arr3)

I've used the above function , but the drawback is that it firsts generates randomly all the numbers from 0 to 7 , and then does the same again.

  • Does this answer your question? [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – pilchard Mar 05 '22 at 11:01

1 Answers1

0

There's two functions:

  • xArray(num) Instantiates a new Array and fills it with consecutive numbers to the given length

  • shuffle(arr) It shuffles any type of Array using the Fisher–Yates shuffle algorithm

const xArray = x => [...new Array(x)].map((_, i) => i);

const shuffle = array => {
  let qty = array.length, temp, i;
  while (qty) {
    i = Math.floor(Math.random() * qty--);
    temp = array[qty];
    array[qty] = array[i];
    array[i] = temp;
  }
  return array;
};

let a = shuffle(xArray(8));
let b = shuffle(xArray(8));

console.log([...a, ...b]);
zer00ne
  • 36,692
  • 5
  • 39
  • 58