對這個問題的研究始於一次在群里看到朋友發的洗牌面試題。當時也不知道具體的解法如何,於是隨口回了一句:每次從剩下的數字中隨機一個。過后找相關資料了解了下,洗牌算法大致有3種,按發明時間先后順序如下:
一、Fisher–Yates Shuffle
算法思想就是從原始數組中隨機抽取一個新的數字到新數組中。算法英文描述如下:
- Write down the numbers from 1 through N.
- Pick a random number k between one and the number of unstruck numbers remaining (inclusive).
- Counting from the low end, strike out the kth number not yet struck out, and write it down elsewhere.
- Repeat from step 2 until all the numbers have been struck out.
- The sequence of numbers written down in step 3 is now a random permutation of the original numbers.
python實現代碼如下:
#Fisher–Yates Shuffle ''' 1. 從還沒處理的數組(假如還剩k個)中,隨機產生一個[0, k]之間的數字p(假設數組從0開始); 2. 從剩下的k個數中把第p個數取出; 3. 重復步驟2和3直到數字全部取完; 4. 從步驟3取出的數字序列便是一個打亂了的數列。 ''' import random def shuffle(lis): result = [] while lis: p = random.randrange(0, len(lis)) result.append(lis[p]) lis.pop(p) return result r = shuffle([1, 2, 2, 3, 3, 4, 5, 10]) print(r)
二、Knuth-Durstenfeld Shuffle
Knuth 和Durstenfeld 在Fisher 等人的基礎上對算法進行了改進。每次從未處理的數據中隨機取出一個數字,然后把該數字放在數組的尾部,即數組尾部存放的是已經處理過的數字。這是一個原地打亂順序的算法,算法時間復雜度也從Fisher算法的O(n2)提升到了O(n)。算法偽代碼如下:
以下兩種實現方式的差異僅僅在於遍歷的方向而已。下面用python實現前一個:
#Knuth-Durstenfeld Shuffle def shuffle(lis): for i in range(len(lis) - 1, 0, -1): p = random.randrange(0, i + 1) lis[i], lis[p] = lis[p], lis[i] return lis r = shuffle([1, 2, 2, 3, 3, 4, 5, 10]) print(r)
三、Inside-Out Algorithm
Knuth-Durstenfeld Shuffle 是一個in-place算法,原始數據被直接打亂,有些應用中可能需要保留原始數據,因此需要開辟一個新數組來存儲打亂后的序列。Inside-Out Algorithm 算法的基本思想是設一游標i從前向后掃描原始數據的拷貝,在[0, i]之間隨機一個下標j,然后用位置j的元素替換掉位置i的數字,再用原始數據位置i的元素替換掉拷貝數據位置j的元素。其作用相當於在拷貝數據中交換i與j位置處的值。偽代碼如下:
python代碼實現如下:
#Inside-Out Algorithm def shuffle(lis): result = lis[:] for i in range(1, len(lis)): j = random.randrange(0, i) result[i] = result[j] result[j] = lis[i] return result r = shuffle([1, 2, 2, 3, 3, 4, 5, 10]) print(r)
四、后話
前面用python實現了三種洗牌算法,其實python random模塊也有個shuffle方法,用法如下:
其內部實現正是使用Knuth-Durstenfeld Shuffle算法,不信您看代碼:-):
參考:
http://en.wikipedia.org/wiki/Fisher-Yates_shuffle