Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Memory Random (version 2)

View mem_random_v2.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#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
Something went wrong with that request. Please try again.