lundi 17 septembre 2018

How to randomize array DURING filter elements (NOT filter array then randomize elements)?

for example, suppose I have array :[13,7,15,1,10,7,3,18,4,20], I have 2 requirements :

  1. only select elements >10
  2. randomize result array

normal way to do:

let arr=[13,7,15,1,10,7,3,18,4,20];
let result=[];
for(let i=0;i<arr.length;i++){
    if(arr[i]>10){
      result.push(arr[i]);
    }
}

for(let i=0;i<result.length;i++){
  const r=Math.floor(Math.random()*result.length);
  const temp=result[i];
  result[i]=result[r];
  result[r]=temp;
}
for(let i=0;i<result.length;i++){
    console.log(result[i]);
}

But I believe I can do it at simpler way : I can put it into a random position DURING filtering instead of randomise the whole array after getting all result, I tried:

let arr=[13,7,15,1,10,7,3,18,4,20];
let result=[];
for(let i=0;i<arr.length;i++){
    if(arr[i]>10){
      result.splice(Math.floor(Math.random()*result.length),0,arr[i]);
    }
}

for(let i=0;i<result.length;i++){
    console.log(result[i]);
}

But I found it is not working : the last element is always 13:

18
20
15
13

20
15
18
13

whats wrong with the idea?




Aucun commentaire:

Enregistrer un commentaire