Skip to content

Instantly share code, notes, and snippets.

@ForTheYin
Created June 19, 2014 18:47
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 ForTheYin/d5771ed80175e5c0c613 to your computer and use it in GitHub Desktop.
Save ForTheYin/d5771ed80175e5c0c613 to your computer and use it in GitHub Desktop.
Memory Random (version 2)
#include <stdio.h>
#include <stdlib.h>
// returns a random number, less segfaults, slower though
int mem_random(int seed, int sprout){
// now the seed pointer is the size of a integer and float!
int* seed_ptr = (int*) malloc(sizeof(int) + sizeof(float));
// set the first part to the seed
*seed_ptr = seed;
// pi is pretty random, though we'll only use *part* of it
// so it's pretty much guaranteed to be random
float pi = 0;
// increase the iterations
int max = 2*(seed % sprout) + 1;
int i = 0;
for (i = 0; i < max; i++){
float neg = i % 2 ? -1 : 1;
pi += neg/(2*i +1);
}
// set the second part to the float!
*(seed_ptr + 1) = pi;
// create four 1 byte characters, so we can shift the pointer later
// increase the randomness by using the seed and sprout
char bits[4];
bits[0] = *(((char*)seed_ptr) + seed % 6);
bits[1] = *(((char*)seed_ptr) + sprout % 6);
bits[2] = *(((char*)seed_ptr) + seed % 8);
bits[3] = *(((char*)seed_ptr) + sprout % 8);
// total + bits = tits, logical
void *tits = bits;
// cast as int, and we're good to go!
int output = *((int *) tits);
// don't forget memory leak!
free(seed_ptr);
return output;
}
int main(void)
{
printf("output: %d\n", mem_random(18,31));
printf("output: %d\n", mem_random(6223,1325));
printf("output: %d\n", mem_random(1234, 424));
printf("output: %d\n", mem_random(1345, 323));
printf("output: %d\n", mem_random(4000, 31421));
printf("output: %d\n", mem_random(4567, 4127));
printf("output: %d\n", mem_random(1231234, 31531));
printf("output: %d\n", mem_random(132344125, 748452));
printf("output: %d\n", mem_random(914685690, 124125));
printf("output: %d\n", mem_random(1898756907, 42415));
// some cool tests
int i = 0;
for (i = 0; i < 99; i++){
int val = mem_random(23*i, 51);
if (val) {
printf("output: %d\n", val);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment