voidfisherYatesShuffle(std::vector<int>& arr){ std::random_device rd; std::mt19937 g(rd()); for (size_t i = arr.size() - 1; i > 0; --i) { std::uniform_int_distribution<size_t> dist(0, i); size_t j = dist(g); std::swap(arr[i], arr[j]); } }
1 2 3 4 5 6 7 8 9 10 11 12 13
using System;
publicclassShuffleAlgorithm { publicstaticvoidFisherYatesShuffle(int[] array) { Random random = new Random(); for (int i = array.Length - 1; i > 0; i--) { int j = random.Next(0, i + 1); // [0, i] int temp = array[i]; array[i] = array[j]; array[j] = temp; } } }
1 2 3 4 5 6
function fisherYatesShuffle<T>(array: T[]): void { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); // [0, i] [array[i], array[j]] = [array[j], array[i]]; } }
1 2 3 4 5 6 7
functionfisher_yates_shuffle(array) math.randomseed(os.time()) for i = #array, 2, -1do local j = math.random(1, i) -- Lua随机数范围[1,i] array[i], array[j] = array[j], array[i] end end