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.
This commit is contained in:
parent
30abd47099
commit
1cdd3bb74f
Notes:
sideshowbarker
2024-07-17 03:21:31 +09:00
Author: https://github.com/kuzux Commit: https://github.com/SerenityOS/serenity/commit/1cdd3bb74f Pull-request: https://github.com/SerenityOS/serenity/pull/16386 Reviewed-by: https://github.com/AtkinsSJ
1 changed files with 12 additions and 0 deletions
12
AK/Random.h
12
AK/Random.h
|
@ -7,6 +7,7 @@
|
|||
#pragma once
|
||||
|
||||
#include <AK/Platform.h>
|
||||
#include <AK/StdLibExtras.h>
|
||||
#include <AK/Types.h>
|
||||
|
||||
#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<typename Collection>
|
||||
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
|
||||
|
|
Loading…
Add table
Reference in a new issue