Skip to content

Instantly share code, notes, and snippets.

@PrinOrange
Created May 31, 2022 12:06
Show Gist options
  • Save PrinOrange/46896a7a2c0a6e5ecab48849cdfb48d1 to your computer and use it in GitHub Desktop.
Save PrinOrange/46896a7a2c0a6e5ecab48849cdfb48d1 to your computer and use it in GitHub Desktop.
洗牌算法 这个代码很简单,只有两行代码,但是却可以实现这个功能:对于给定的 n 个元素,生成的那个排列,每一个元素都能等概率地出现在每一个位置。 换句话说,每一个位置都能等概率地放置每个元素。
for(int i = n - 1; i >= 0 ; i -- )
swap(arr[i], arr[rand(0, i)]) // rand(0, i) 生成 [0, i] 之间的随机整数
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment