为什么这种简单的洗牌算法会产生偏颇的结果？为什么是一个简单的原因？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (29)

```# suppose \$arr is filled with 1 to 52

for (\$i < 0; \$i < 52; \$i++) {
\$j = rand(0, 51);

# swap the items

\$tmp = \$arr[j];
\$arr[j] = \$arr[i];
\$arr[i] = \$tmp;
}```

```for (\$i < 0; \$i < 51; \$i++) {  # last card need not swap
\$j = rand(\$i, 51);        # don't touch the cards that already "settled"

# swap the items

\$tmp = \$arr[j];
\$arr[j] = \$arr[i];
\$arr[i] = \$tmp;
}```

2 个回答

```123
+- 123          - swap 1 and 1 (these are positions,
|   +- 213      - swap 2 and 1  not numbers)
|   |   +- 312  - swap 3 and 1
|   |   +- 231  - swap 3 and 2
|   |   +- 213  - swap 3 and 3
|   +- 123      - swap 2 and 2
|   |   +- 321  - swap 3 and 1
|   |   +- 132  - swap 3 and 2
|   |   +- 123  - swap 3 and 3
|   +- 132      - swap 2 and 3
|       +- 231  - swap 3 and 1
|       +- 123  - swap 3 and 2
|       +- 132  - swap 3 and 3
+- 213          - swap 1 and 2
|   +- 123      - swap 2 and 1
|   |   +- 321  - swap 3 and 1
|   |   +- 132  - swap 3 and 2
|   |   +- 123  - swap 3 and 3
|   +- 213      - swap 2 and 2
|   |   +- 312  - swap 3 and 1
|   |   +- 231  - swap 3 and 2
|   |   +- 213  - swap 3 and 3
|   +- 231      - swap 2 and 3
|       +- 132  - swap 3 and 1
|       +- 213  - swap 3 and 2
|       +- 231  - swap 3 and 3
+- 321          - swap 1 and 3
+- 231      - swap 2 and 1
|   +- 132  - swap 3 and 1
|   +- 213  - swap 3 and 2
|   +- 231  - swap 3 and 3
+- 321      - swap 2 and 2
|   +- 123  - swap 3 and 1
|   +- 312  - swap 3 and 2
|   +- 321  - swap 3 and 3
+- 312      - swap 2 and 3
+- 213  - swap 3 and 1
+- 321  - swap 3 and 2
+- 312  - swap 3 and 3```

```123 - 4 times
132 - 5 times
213 - 5 times
231 - 5 times
312 - 4 times
321 - 4 times
=============
27 times total```

```class Program
{
static void Main(string[] args)
{
Dictionary<String, Int32> occurances = new Dictionary<String, Int32>
{
{ "123", 0 },
{ "132", 0 },
{ "213", 0 },
{ "231", 0 },
{ "312", 0 },
{ "321", 0 }
};

Char[] digits = new[] { '1', '2', '3' };
Func<Char[], Int32, Int32, Char[]> swap = delegate(Char[] input, Int32 pos1, Int32 pos2)
{
Char[] result = new Char[] { input[0], input[1], input[2] };
Char temp = result[pos1];
result[pos1] = result[pos2];
result[pos2] = temp;
return result;
};

for (Int32 index1 = 0; index1 < 3; index1++)
{
Char[] level1 = swap(digits, 0, index1);
for (Int32 index2 = 0; index2 < 3; index2++)
{
Char[] level2 = swap(level1, 1, index2);
for (Int32 index3 = 0; index3 < 3; index3++)
{
Char[] level3 = swap(level2, 2, index3);
String output = new String(level3);
occurances[output]++;
}
}
}

foreach (var kvp in occurances)
{
Console.Out.WriteLine(kvp.Key + ": " + kvp.Value);
}
}
}```

```123: 4
132: 5
213: 5
231: 5
312: 4
321: 4```