| 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 | * \namespace KRandom |
| 23 | * \inmodule KCoreAddons |
| 24 | * |
| 25 | * \brief Helper to create random data. |
| 26 | * |
| 27 | * This namespace provides methods which generate random data. |
| 28 | * KRandom is not recommended for serious random-number generation needs, |
| 29 | * like cryptography. |
| 30 | */ |
| 31 | namespace KRandom |
| 32 | { |
| 33 | /*! |
| 34 | * Generates a random string. It operates in the range [A-Za-z0-9] |
| 35 | * |
| 36 | * \a length Generate a string of this length. |
| 37 | * |
| 38 | * Returns the random string |
| 39 | */ |
| 40 | KCOREADDONS_EXPORT QString randomString(int length); |
| 41 | |
| 42 | /*! |
| 43 | * Reorders the elements of the given container randomly using the given random number generator. |
| 44 | * |
| 45 | * The container needs to implement size() and T &operator[] |
| 46 | * |
| 47 | * \since 5.73 |
| 48 | */ |
| 49 | template<typename T> |
| 50 | void shuffle(T &container, QRandomGenerator *generator) |
| 51 | { |
| 52 | Q_ASSERT(container.size() <= std::numeric_limits<int>::max()); |
| 53 | // Fisher-Yates algorithm |
| 54 | for (int index = container.size() - 1; index > 0; --index) { |
| 55 | const int swapIndex = generator->bounded(highest: index + 1); |
| 56 | qSwap(container[index], container[swapIndex]); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /*! |
| 61 | * Reorders the elements of the given container randomly. |
| 62 | * |
| 63 | * The container needs to implement size() and T &operator[] |
| 64 | * |
| 65 | * \since 5.73 |
| 66 | */ |
| 67 | template<typename T> |
| 68 | void shuffle(T &container) |
| 69 | { |
| 70 | shuffle(container, QRandomGenerator::global()); |
| 71 | } |
| 72 | |
| 73 | } |
| 74 | |
| 75 | #endif |
| 76 | |