KCoreAddons

krandom.h
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 */
30namespace 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 */
37KCOREADDONS_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 */
46template<typename T>
47void 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(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 */
64template<typename T>
65void shuffle(T &container)
66{
68}
69
70}
71
72#endif
Helper class to create random data.
Definition krandom.h:31
KCOREADDONS_EXPORT QString randomString(int length)
Generates a random string.
Definition krandom.cpp:30
void shuffle(T &container, QRandomGenerator *generator)
Reorders the elements of the given container randomly using the given random number generator.
Definition krandom.h:47
double bounded(double highest)
QRandomGenerator * global()
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri Jun 21 2024 12:03:20 by doxygen 1.10.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.