Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an array like this:

(我有一个像这样的数组:)

var arr1 = ["a", "b", "c", "d"];

How can I randomize / shuffle it?

(如何随机/随机播放?)

  ask by Click Upvote translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
223 views
Welcome To Ask or Share your Answers For Others

1 Answer

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.

(实际无偏混洗算法是Fisher-Yates(aka Knuth)混洗。)

See https://github.com/coolaj86/knuth-shuffle

(参见https://github.com/coolaj86/knuth-shuffle)

You can see a great visualization here (and the original post linked to this )

(您可以在此处看到出色的可视化效果 (以及与此链接相关的原始文章))

 function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } // Used like so var arr = [2, 11, 37, 42]; arr = shuffle(arr); console.log(arr); 

Some more info about the algorithm used.

(有关使用的算法的更多信息。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...