shuffle a deck of cards

来源:互联网 发布:淘宝6s官换机能买吗 编辑:程序博客网 时间:2024/06/06 01:42

Question:

You are given a deck of 52 cards, and you need to shuffle the cards and make sure the order is random.

Solution:

We can simply use the Durstenfeld and Knuth algorithm to shuffle the cards, which is shown below.

To shuffle an array a of n elements (indices 0..n-1):  for i from n − 1 downto 1 do       j ← random integer with 0 ≤ j ≤ i       exchange a[j] and a[i]