2020-05-27 12:25:46 +02:00
|
|
|
/*
|
2024-10-04 13:19:50 +02:00
|
|
|
* Copyright (c) 2020, Andreas Kling <andreas@ladybird.org>
|
2020-05-27 12:25:46 +02:00
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-05-27 12:25:46 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
|
|
#include <AK/Platform.h>
|
2023-04-02 13:08:43 -04:00
|
|
|
#include <AK/Span.h>
|
2022-12-09 16:46:13 +03:00
|
|
|
#include <AK/StdLibExtras.h>
|
2020-05-27 12:25:46 +02:00
|
|
|
#include <AK/Types.h>
|
2023-04-02 12:33:15 -04:00
|
|
|
#include <stdlib.h>
|
2020-05-27 12:25:46 +02:00
|
|
|
|
2020-10-17 16:25:13 -04:00
|
|
|
#if defined(__unix__)
|
2020-05-27 12:25:46 +02:00
|
|
|
# include <unistd.h>
|
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
|
namespace AK {
|
|
|
|
|
|
2025-04-11 22:14:59 +02:00
|
|
|
void fill_with_random([[maybe_unused]] Bytes bytes);
|
2020-05-27 12:25:46 +02:00
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
|
inline T get_random()
|
|
|
|
|
{
|
|
|
|
|
T t;
|
2023-04-02 13:08:43 -04:00
|
|
|
fill_with_random({ &t, sizeof(T) });
|
2020-05-27 12:25:46 +02:00
|
|
|
return t;
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-14 17:16:06 +02:00
|
|
|
u32 get_random_uniform(u32 max_bounds);
|
2023-12-30 16:23:59 +01:00
|
|
|
u64 get_random_uniform_64(u64 max_bounds);
|
2021-05-14 17:16:06 +02:00
|
|
|
|
2022-12-09 16:46:13 +03:00
|
|
|
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]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-05-27 12:25:46 +02:00
|
|
|
}
|
2020-10-16 15:59:53 -04:00
|
|
|
|
2022-11-26 12:18:30 +01:00
|
|
|
#if USING_AK_GLOBALLY
|
2020-10-16 15:59:53 -04:00
|
|
|
using AK::fill_with_random;
|
|
|
|
|
using AK::get_random;
|
2021-05-14 17:16:06 +02:00
|
|
|
using AK::get_random_uniform;
|
2022-12-09 16:46:13 +03:00
|
|
|
using AK::shuffle;
|
2022-11-26 12:18:30 +01:00
|
|
|
#endif
|