惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
TaoSecurity Blog
TaoSecurity Blog
T
Threat Research - Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tenable Blog
C
Cybersecurity and Infrastructure Security Agency CISA
GbyAI
GbyAI
Microsoft Security Blog
Microsoft Security Blog
N
Netflix TechBlog - Medium
AWS News Blog
AWS News Blog
Security Latest
Security Latest
L
LINUX DO - 热门话题
Blog — PlanetScale
Blog — PlanetScale
T
Threatpost
Stack Overflow Blog
Stack Overflow Blog
Vercel News
Vercel News
S
Securelist
I
Intezer
D
Darknet – Hacking Tools, Hacker News & Cyber Security
H
Heimdal Security Blog
T
The Exploit Database - CXSecurity.com
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Hacker News
The Hacker News
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Hackread – Cybersecurity News, Data Breaches, AI and More
U
Unit 42
The Register - Security
The Register - Security
NISL@THU
NISL@THU
S
Schneier on Security
M
MIT News - Artificial intelligence
The Last Watchdog
The Last Watchdog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hugging Face - Blog
Hugging Face - Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
Y
Y Combinator Blog
Know Your Adversary
Know Your Adversary
罗磊的独立博客
MongoDB | Blog
MongoDB | Blog
美团技术团队
W
WeLiveSecurity
P
Privacy International News Feed
Forbes - Security
Forbes - Security
H
Hacker News: Front Page
小众软件
小众软件
博客园 - 【当耐特】
P
Proofpoint News Feed
P
Privacy & Cybersecurity Law Blog
T
Tor Project blog

博客园 - ZefengYao

Markdown 入门与 Word 使用指南 关于崩溃报告的日志以及dump文件 hdu 6223 Infinite Fraction Path 2017南宁现场赛E The Champion ACM-ICPC 2018 南京赛区网络预赛 Sum c语言几个字符串处理函数的简单实现 各种类型排序的实现及比较 两个栈实现队列 面试杂题 面试题——栈的压入、弹出顺序 C++ 智能指针的简单实现 openGL初学函数解释汇总 foj Problem 2107 Hua Rong Dao foj Problem 2282 Wand UVA-1400 Ray, Pass me the dishes! 《挑战程序设计竞赛》 利用后缀数组求最长回文串 Uva 11174 Stand in a Line UVA 11375 Matches poj 3729 Facer’s string
随机洗牌算法Knuth Shuffle和错排公式
ZefengYao · 2018-08-16 · via 博客园 - ZefengYao

Knuth随机洗牌算法:譬如现在有54张牌,如何洗牌才能保证随机性。可以这么考虑,从最末尾一张牌开始洗,对于每一张牌,编号在该牌前面的牌中任意一张选一张和当前牌进行交换,直至洗到第一张牌为止。参考代码如下:

void knuth() {
        for (int i = 54; i > 1; i--) {
            int id = rand() % (i - 1) + 1;
            swap(a[i], a[id]);
        }
    }

由上述方法可知,每一张牌经过洗牌之后一定不会出现在原来位置,那么一共会有多少情况呢,这其实就是错排的定义,n个数的错排数有如下递推公式:

f(n)=(n-1)(f(n-1)+f(n-2))

公式的推导:首先让我们假设已知n-1个数和n-2个数的错排数,这时又在原来基础上加了一个数字,那么如果这n个数要构成错排,新加入的数字一定不能出现在自己的位置上,所以它只能选择其余的n-1个位置,不妨设选择了第k个位置,那么原本在第k个位置上的数又会跑到哪里去呢,这里有两种情况,原本的第k个数跑到第n个数的位置上去了,这时这两个数只是相互交换了位置,其余的n-2个数怎么排列完全不受影响,故此时有f(n-2)种情况;再考虑原本第k个数不在第n个数的位置上,那么除去第n个数,其余的n-1个数任然构成错排,错排数为f(n-1)。至此就可得递推式f(n)=(n-1)(f(n-1)+f(n-2));