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
9*/
10
11#ifndef KRANDOM_H
12#define KRANDOM_H
13
15
16#include <QRandomGenerator>
17#include <QString>
18
19#include <limits>
20
21/**
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 */
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