Skip to content

Instantly share code, notes, and snippets.

@kajott
Last active August 8, 2019 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kajott/eb9f148aaa523bb11db23da6b4dc61a7 to your computer and use it in GitHub Desktop.
Save kajott/eb9f148aaa523bb11db23da6b4dc61a7 to your computer and use it in GitHub Desktop.
generate sequences of numbers with variable degree of randomness
#if 0
g++ -std=c++11 -Wall -Wextra -pedantic -Werror $0 || exit 1
exec ./a.out
#endif
// generate sequences of numbers 0..(1-n) with variable degree of randomness:
// r = 0.0 -> perfectly sorted
// r = 0.5 -> fully shuffled
// r = 1.0 -> perfectly reversed
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <algorithm>
inline float lerp(float a, float b, float t) {
return a + (b - a) * t;
}
std::vector<int> generateVariableRandomness(int n, float r) {
struct key {
float w;
int i;
inline bool operator<(const key& other) { return w < other.w; }
};
std::vector<key> keys(n);
float reverse = (r > 0.5f) ? 1.0f : 0.0f;
r = 1.0f - 2.0f * fabsf(r - 0.5f);
for (int i = 0; i < n; ++i) {
keys[i].i = i;
keys[i].w = lerp(fabsf(reverse - i / (float)(n - 1)), rand() / (float)RAND_MAX, r);
}
std::sort(keys.begin(), keys.end());
std::vector<int> result(n);
for (int i = 0; i < n; ++i) {
result[i] = keys[i].i;
}
return result;
}
int main() {
srand(0x47110815);
for (float r = 0.0f; r <= 1.0f; r += 1.0f / 16) {
printf("%5.3f: ", r);
std::vector<int> seq = generateVariableRandomness(26, r);
for (int i = 0; i < 26; ++i) {
putchar('A' + seq[i]);
}
printf("\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment