randomize all elements in an array (in-place algorithms) take no space and its fastest among all random algorithms.
//fastest algo to randomize array values without any space inplace
Array.prototype.swap=function(startIndex,endIndex=this.length-1)
{
let temp=this[startIndex];
this[startIndex]=this[endIndex];
this[endIndex]=temp;
return this;
};
Array.prototype.random=function()
{
const randomFunction=(min,max)=>{
return Math.round(Math.random()*(max-min))+min;
}
for(let i=0;i<this.length;i++)
{
this.swap(i,randomFunction(i,this.length-1));
}
return this;
}
var newArr=[10,9,8,7,21,12,13];
console.log(newArr.random())
Comments
Post a Comment