1 | /* |
2 | This file is part of the KDE libraries |
3 | |
4 | SPDX-FileCopyrightText: 1999 Matthias Kalle Dalheimer <kalle@kde.org> |
5 | SPDX-FileCopyrightText: 2000 Charles Samuels <charles@kde.org> |
6 | SPDX-FileCopyrightText: 2005 Joseph Wenninger <kde@jowenn.at> |
7 | |
8 | SPDX-License-Identifier: LGPL-2.0-or-later |
9 | */ |
10 | |
11 | #ifndef KRANDOM_H |
12 | #define KRANDOM_H |
13 | |
14 | #include <kcoreaddons_export.h> |
15 | |
16 | #include <QRandomGenerator> |
17 | #include <QString> |
18 | |
19 | #include <limits> |
20 | |
21 | /** |
22 | * \headerfile krandom.h <KRandom> |
23 | * |
24 | * @short Helper class to create random data |
25 | * |
26 | * This namespace provides methods which generate random data. |
27 | * KRandom is not recommended for serious random-number generation needs, |
28 | * like cryptography. |
29 | */ |
30 | namespace KRandom |
31 | { |
32 | /** |
33 | * Generates a random string. It operates in the range [A-Za-z0-9] |
34 | * @param length Generate a string of this length. |
35 | * @return the random string |
36 | */ |
37 | KCOREADDONS_EXPORT QString randomString(int length); |
38 | |
39 | /** |
40 | * Reorders the elements of the given container randomly using the given random number generator. |
41 | * |
42 | * The container needs to implement size() and T &operator[] |
43 | * |
44 | * @since 5.73 |
45 | */ |
46 | template<typename T> |
47 | void shuffle(T &container, QRandomGenerator *generator) |
48 | { |
49 | Q_ASSERT(container.size() <= std::numeric_limits<int>::max()); |
50 | // Fisher-Yates algorithm |
51 | for (int index = container.size() - 1; index > 0; --index) { |
52 | const int swapIndex = generator->bounded(highest: index + 1); |
53 | qSwap(container[index], container[swapIndex]); |
54 | } |
55 | } |
56 | |
57 | /** |
58 | * Reorders the elements of the given container randomly. |
59 | * |
60 | * The container needs to implement size() and T &operator[] |
61 | * |
62 | * @since 5.73 |
63 | */ |
64 | template<typename T> |
65 | void shuffle(T &container) |
66 | { |
67 | shuffle(container, QRandomGenerator::global()); |
68 | } |
69 | |
70 | } |
71 | |
72 | #endif |
73 | |