From 1cdd3bb74ff0106d0738f97301f02cb67660b3f6 Mon Sep 17 00:00:00 2001 From: Arda Cinar Date: Fri, 9 Dec 2022 16:46:13 +0300 Subject: [PATCH] AK: Add a shuffle utility function This implements a shuffle function in AK/Random.h which works on any container with size() and curly brace operators. It uses fisher-yates shuffle. --- AK/Random.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/AK/Random.h b/AK/Random.h index e21905fe0a..1fc7c81c03 100644 --- a/AK/Random.h +++ b/AK/Random.h @@ -7,6 +7,7 @@ #pragma once #include +#include #include #if defined(AK_OS_SERENITY) || defined(AK_OS_ANDROID) @@ -52,10 +53,21 @@ inline T get_random() u32 get_random_uniform(u32 max_bounds); +template +inline void shuffle(Collection& collection) +{ + // Fisher-Yates shuffle + for (size_t i = collection.size() - 1; i >= 1; --i) { + size_t j = get_random_uniform(i + 1); + AK::swap(collection[i], collection[j]); + } +} + } #if USING_AK_GLOBALLY using AK::fill_with_random; using AK::get_random; using AK::get_random_uniform; +using AK::shuffle; #endif