File indexing completed on 2024-05-19 03:56:22
0001 /* 0002 This file is part of the KDE libraries 0003 0004 SPDX-FileCopyrightText: 1999 Matthias Kalle Dalheimer <kalle@kde.org> 0005 SPDX-FileCopyrightText: 2000 Charles Samuels <charles@kde.org> 0006 SPDX-FileCopyrightText: 2005 Joseph Wenninger <kde@jowenn.at> 0007 0008 SPDX-License-Identifier: LGPL-2.0-or-later 0009 */ 0010 0011 #ifndef KRANDOM_H 0012 #define KRANDOM_H 0013 0014 #include <kcoreaddons_export.h> 0015 0016 #include <QRandomGenerator> 0017 #include <QString> 0018 0019 #include <limits> 0020 0021 /** 0022 * \headerfile krandom.h <KRandom> 0023 * 0024 * @short Helper class to create random data 0025 * 0026 * This namespace provides methods which generate random data. 0027 * KRandom is not recommended for serious random-number generation needs, 0028 * like cryptography. 0029 */ 0030 namespace KRandom 0031 { 0032 /** 0033 * Generates a random string. It operates in the range [A-Za-z0-9] 0034 * @param length Generate a string of this length. 0035 * @return the random string 0036 */ 0037 KCOREADDONS_EXPORT QString randomString(int length); 0038 0039 /** 0040 * Reorders the elements of the given container randomly using the given random number generator. 0041 * 0042 * The container needs to implement size() and T &operator[] 0043 * 0044 * @since 5.73 0045 */ 0046 template<typename T> 0047 void shuffle(T &container, QRandomGenerator *generator) 0048 { 0049 Q_ASSERT(container.size() <= std::numeric_limits<int>::max()); 0050 // Fisher-Yates algorithm 0051 for (int index = container.size() - 1; index > 0; --index) { 0052 const int swapIndex = generator->bounded(index + 1); 0053 qSwap(container[index], container[swapIndex]); 0054 } 0055 } 0056 0057 /** 0058 * Reorders the elements of the given container randomly. 0059 * 0060 * The container needs to implement size() and T &operator[] 0061 * 0062 * @since 5.73 0063 */ 0064 template<typename T> 0065 void shuffle(T &container) 0066 { 0067 shuffle(container, QRandomGenerator::global()); 0068 } 0069 0070 } 0071 0072 #endif