Skip to content

Instantly share code, notes, and snippets.

@607011
Last active October 20, 2015 15:38
Show Gist options
  • Save 607011/37f7762149c6bda29c2a to your computer and use it in GitHub Desktop.
Save 607011/37f7762149c6bda29c2a to your computer and use it in GitHub Desktop.
Fisher-Yates-Shuffle (shuffling of array elements)
// using Qt
QByteArray shuffled(const QByteArray &ba)
{
QByteArray result = ba;
int n = result.count();
char *c = result.data();
while (n) {
int j = qrand() % n--;
char tmp = *(c + n);
*(c + n) = *(c + j);
*(c + j) = tmp;
}
return result;
}
QString shuffled(const QString& s)
{
QString result = s;
int n = result.count();
QChar *c = result.data();
while (n) {
int j = qrand() % n--;
QChar tmp = *(c + n);
*(c + n) = *(c + j);
*(c + j) = tmp;
}
return result;
}
// see http://bost.ocks.org/mike/shuffle/
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment