75°

经典洗牌算法

# -*-coding:utf-8 -*-
'''
背景
https://www.jianshu.com/p/4be78c20095e
在n个不同的数中随机取出不重复的m个数。洗牌算法是将原来的数组进行打散,
使原数组的某个数在打散后的数组中的每个位置上等概率的出现,刚好可以解决该问题。
洗牌算法
由抽牌、换牌和插牌衍生出三种洗牌算法,其中抽牌和换牌分别对应
Fisher-Yates Shuffle和Knuth-Durstenfeld Shhuffle算法。
'''

"""
Author:
Yao Zhian
Blog:
https://www.cnblogs.com/shnuxiaoan
Modify:
2020-01-18
"""
import random

def loadSimpData():
"""
创建初始牌数组元素
Parameters:

Returns:
dataMat - 牌数据
"""
num = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
color = ['♣️', '♦️', '♠️', '♥️']
num_color = []
for i in range(len(num)):
for j in range(len(color)):
num_color.append(num[i]+color[j])
return num_color

def shuffle_cards(start_cards, m):
"""
数据可视化
Parameters:
start_cards - 初始牌的数组
m - 需要的m张不同的牌
Returns:
end_cards - 挑选的m张不重复的牌
"""
length = len(start_cards)
for i in range(m):
n = length - i - 1
k = random.randint(0, n)
temp = start_cards[k]
start_cards[k] = start_cards[n]
start_cards[n] = temp

end_cards = start_cards[length-m:length]
return end_cards


if __name__ == '__main__':
num_color = loadSimpData()
# print(num_color)
cards = shuffle_cards(num_color, 17)
print(cards)

本文转载自博客园,原文链接:https://www.cnblogs.com/shnuxiaoan/p/12209265.html

全部评论: 0

    我有话说: