shuffle
shuffle(array &$array): true
随机打乱数组元素(值保留、键重排为整数;关联键丢失);非加密安全,可播种性靠全局 mt_srand。
C C23
#include <stdio.h>
#include <stdlib.h>
static void fisher_yates(int *a, int n) {
for (int i = n - 1; i > 0; i--) {
int j = rand() % (i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
static int equal(const int *a, const int *b, int n) {
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) return 0;
}
return 1;
}
int main(void) {
/* C 没有内建 shuffle:手写 Fisher-Yates;srand(种子) 让排列可重复
(同一 libc 内同种子重跑必然一致) */
int orig[5] = {1, 2, 3, 4, 5};
int a[5], b[5];
srand(2026);
for (int i = 0; i < 5; i++) a[i] = orig[i];
fisher_yates(a, 5);
srand(2026);
for (int i = 0; i < 5; i++) b[i] = orig[i];
fisher_yates(b, 5);
printf("%d\n", equal(a, b, 5));
/* 派生事实:打乱后排序即可还原原数组 */
int c[5] = {1, 2, 3, 4, 5};
srand(7);
fisher_yates(c, 5);
for (int i = 1; i < 5; i++) {
int key = c[i], j = i - 1;
while (j >= 0 && c[j] > key) { c[j + 1] = c[j]; j--; }
c[j + 1] = key;
}
printf("%d\n", equal(c, orig, 5));
return 0;
}
1 1
C++ C++26
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
int main() {
// std::shuffle 配播种过的 mt19937:同一二进制重跑排列可重复
// (分布映射由各标准库实现定义)
std::vector<int> original = {1, 2, 3, 4, 5};
std::vector<int> a = original;
std::mt19937 g1(2026);
std::shuffle(a.begin(), a.end(), g1);
std::vector<int> b = original;
std::mt19937 g2(2026);
std::shuffle(b.begin(), b.end(), g2);
std::cout << std::boolalpha << (a == b) << "\n";
// 派生事实:打乱后排序即可还原原数组
std::vector<int> c = original;
std::mt19937 g3(7);
std::shuffle(c.begin(), c.end(), g3);
std::sort(c.begin(), c.end());
std::cout << (c == original) << "\n";
return 0;
}
true true
C# v11.0.100
// 没有内建 shuffle:手写 Fisher-Yates 配可播种的 Random
int[] original = { 1, 2, 3, 4, 5 };
var rng1 = new Random(2026);
int[] a = (int[])original.Clone();
FisherYates(a, rng1);
var rng2 = new Random(2026);
int[] b = (int[])original.Clone();
FisherYates(b, rng2);
Console.WriteLine(a.SequenceEqual(b));
// 派生事实:打乱后排序即可还原原数组
var rng3 = new Random(7);
int[] c = (int[])original.Clone();
FisherYates(c, rng3);
Array.Sort(c);
Console.WriteLine(c.SequenceEqual(original));
static void FisherYates(int[] arr, Random rng)
{
for (int i = arr.Length - 1; i > 0; i--)
{
int j = rng.Next(i + 1);
(arr[i], arr[j]) = (arr[j], arr[i]);
}
}
True True
Go v1.27.4
package main
import (
"fmt"
"math/rand"
"sort"
)
func shuffled(seed int64, src []int) []int {
// rand.Shuffle 搭配独立的 *rand.Rand:固定种子即可精确复现排列
r := rand.New(rand.NewSource(seed))
out := append([]int(nil), src...)
r.Shuffle(len(out), func(i, j int) { out[i], out[j] = out[j], out[i] })
return out
}
func main() {
original := []int{1, 2, 3, 4, 5}
fmt.Println(fmt.Sprint(shuffled(2026, original)) == fmt.Sprint(shuffled(2026, original)))
restored := shuffled(7, original)
sort.Ints(restored)
fmt.Println(fmt.Sprint(restored) == fmt.Sprint(original))
}
true true
Java v27.0.1
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Collections.shuffle 接受显式 Random:固定种子即可精确复现排列
List<Integer> original = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> a = new ArrayList<>(original);
Collections.shuffle(a, new Random(2026));
List<Integer> b = new ArrayList<>(original);
Collections.shuffle(b, new Random(2026));
System.out.println(a.equals(b));
// 派生事实:打乱后排序即可还原原数组
List<Integer> c = new ArrayList<>(original);
Collections.shuffle(c, new Random(7));
Collections.sort(c);
System.out.println(c.equals(original));
}
}
true true
JavaScript v26.13.1
// JS 没有内建 shuffle:手写 Fisher-Yates(PHP shuffle /
// Python random.shuffle 内部同款算法)。Math.random 不可播种,
// 所以只打印派生事实
function shuffle(arr) {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const original = [1, 2, 3, 4, 5, 6];
const mixed = shuffle(original);
console.log(mixed.length === original.length);
console.log([...mixed].sort((x, y) => x - y).join() === original.join());
console.log(original.join());
true true 1,2,3,4,5,6
PHP v8.6.0
// shuffle 保留值但重建整数键(关联键丢失)
$a = ['k1' => 'v1', 'k2' => 'v2', 'k3' => 'v3'];
shuffle($a);
var_dump(array_keys($a) === range(0, 2));
var_dump(count(array_diff(['v1', 'v2', 'v3'], $a)) === 0);
// 派生事实:打乱后 sort 即可精确还原原数组
$b = range(1, 6);
shuffle($b);
sort($b);
var_dump($b === range(1, 6));
// 手册:随机源是全局 Mt19937——mt_srand 固定种子即可让 shuffle
// 可重复,尽管 shuffle 本身没有种子参数
$x = range(1, 5);
mt_srand(2026);
shuffle($x);
$y = range(1, 5);
mt_srand(2026);
shuffle($y);
var_dump($x === $y);
bool(true) bool(true) bool(true) bool(true)
Python v3.15.2
import random
# random.shuffle 可经 random.Random(seed) 播种:同种子同排列
# (PHP shuffle 没有种子参数,只能靠手册写明的全局 mt_srand 复现)
rng = random.Random(2026)
a = [1, 2, 3, 4, 5]
rng.shuffle(a)
b = [1, 2, 3, 4, 5]
random.Random(2026).shuffle(b)
print(a == b)
# 派生事实:打乱后排序即可还原原列表
c = [1, 2, 3, 4, 5, 6]
random.Random(7).shuffle(c)
print(sorted(c) == [1, 2, 3, 4, 5, 6])
True True
Rust v1.99.1
use rand::prelude::*;
fn main() {
// rand crate:可播种的 RNG 即可精确复现排列;
// SliceRandom::shuffle 内部就是 Fisher-Yates
let original = [1i32, 2, 3, 4, 5];
let mut a = original;
let mut rng1 = StdRng::seed_from_u64(2026);
a.shuffle(&mut rng1);
let mut b = original;
let mut rng2 = StdRng::seed_from_u64(2026);
b.shuffle(&mut rng2);
println!("{}", a == b);
// 派生事实:打乱后排序即可还原原 vec
let mut c = original;
let mut rng3 = StdRng::seed_from_u64(7);
c.shuffle(&mut rng3);
c.sort_unstable();
println!("{}", c == original);
}
true true
TypeScript v26.13.1
// 没有内建 shuffle:对带类型数组手写 Fisher-Yates;
// Math.random 不可播种,所以只打印派生事实
function shuffle<T>(arr: T[]): T[] {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const original: number[] = [1, 2, 3, 4, 5, 6];
const mixed = shuffle(original);
console.log(mixed.length === original.length);
console.log([...mixed].sort((x, y) => x - y).join() === original.join());
console.log(original.join());
true true 1,2,3,4,5,6
语言差异说明
C:无内建——手写 Fisher-Yates(从尾向头、每步与 rand() % (i+1) 交换);srand(种子) 后可重复(同一 libc 内同种子序列固定;跨 libc 算法不同但各自内部自洽)。rand() % n 有轻微模偏差,教学外场景用 random 或除法采样。
C++:std::shuffle + 播种 std::mt19937——标准库统一算法接口;注意 uniform_int_distribution 的映射按实现定义,跨标准库不保证同排列,但同一二进制重跑必一致。
C#:无内建——手写 Fisher-Yates 配 new Random(seed)(.NET 6+ 无参构造已换随机源,但带种构造仍是可复现的兼容算法)。
Go:rand.Shuffle(内部 Fisher-Yates)+ 独立 rand.New(rand.NewSource(seed))——把 RNG 显式传参,可重复性天然成立;全局 rand.Go1.22 起自动播种(不可复现)。
Java:Collections.shuffle(list, new Random(seed))——第二个参数传 RNG 即可复现;不传则用全局共享 Random(内部 synchronized)。
JavaScript:无内建——手写 Fisher-Yates;Math.random 标准未定义种子机制,无法可重复(只能输出派生事实)。
PHP:shuffle 值保留、键重排为整数索引(关联键全丢——手册明示「新键为连续整数」);手册 Caution 两连:非加密安全(要加密用 random_int/Random\Randomizer)+ 随机源是全局 Mt19937(与 mt_rand 共享状态);重要事实(手册明示、实测验证):shuffle 虽无种子参数,mt_srand(固定值) 播种后输出可精确复现——与直觉「PHP shuffle 不可播种」相反。本条目确定性策略:不预置具体排列,只输出「sort 还原==原数组」与「键重排」「同种子两次一致」三个布尔派生事实。
Python:random.shuffle(Fisher-Yates)——模块级用全局实例(random.seed 可播种),或传独立 random.Random(seed) 实例;与 PHP 的差异在「种子是一等 API」而非隐藏的全局状态。
Rust:rand crate SliceRandom::shuffle(内部 Fisher-Yates)+ StdRng::seed_from_u64 显式播种;rand::seq::index::sample 可做无替换采样。
TypeScript:同 JavaScript——手写 Fisher-Yates、Math.random 不可播种;需要可复现时传自实现的种子 RNG。