- This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
Viewing 5 posts - 1 through 5 (of 5 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › [1,2,3,4,5,6,7,8,9].shuffle()
I’m already broken my head with this exercise:
Make this code work:
[1,2,3,4,5,6,7,8,9].shuffle()
// [2, 4, 1, 8, 9, 6, 5, 3, 7]
Can somebody help? It seems I have to use prototype an maybe Math.randam(). Thanks
It’s from Object-oriented Javascript by Stoyan Stefanov, great book.
before sleep was that
Array.prototype.shuffle = function() {
var len = this.length;
for ( var i = 0; i < len; i++ ) {
var ele = this*, pos = this[Math.floor(Math.random()*len)];
if(pos == undefined) {
pos = ele;
}
}
return this;
};
Give me, please some tips, here my result (don’t want to look at Stock overflow, I know there is answer, want to properly uderstand):
Array.prototype.shuffle = function() {
var len = this.length,
shuffleArr = [];
for ( var i = 0; i < len; i++ ) {
var elem = this,
pos = Math.floor( Math.random() * len );
if ( shuffleArr[pos] == undefined) {
shuffleArr[pos] = elem
shuffleArr.push(elem);
}
}
return shuffleArr;
}
var a =[1,2,3,4,5,6,7,8,9];
a.shuffle()
It’s nice solution **shuffleArr.splice(pos, 0, elem);** I didn’t know how to make that elem go to different position, because Math.random() can repeat themselves, thats why there was this strange
if ( shuffleArr[pos] == undefined)
but, why you use:
pos = Math.floor( Math.random() * (shuffleArr.length + 1) )
this works too:
pos = Math.floor( Math.random() * len );
Thanks @CrocoDillon for your help