Last active
August 29, 2015 14:05
-
-
Save Sebbyastian/3888f468412dbe37e7c4 to your computer and use it in GitHub Desktop.
Bucky Roberts dice challenge. LUL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <time.h> | |
#define DICE_COUNT 3 | |
#define SIDE_COUNT 6 | |
unsigned int roll(unsigned int side_count) { | |
int n; | |
/* When RAND_MAX isn't evenly divisible by side_count, we'll have a bias problem. | |
* Lets analyse the problem: If rand() only returns a value from [ 0, 1, 2, 3, 4, 5 ] | |
* for a six-sided dice, then each side has equal distribution. However if you tack | |
* another number onto the end of that, and we have to use modulo to reduce the set of | |
* seven numbers to six, then one side will occur twice as often as the any of others. | |
* We can eliminate the bias by discarding any numbers greater than or equal to the | |
* largest multiple of six that's less than RAND_MAX. */ | |
do { | |
n = rand(); | |
} while (RAND_MAX - n <= RAND_MAX % side_count); | |
return n % side_count + 1; | |
} | |
int main(void) { | |
srand(time(NULL)); | |
unsigned long int last_total = 0, next_total = 0; | |
for (unsigned int x = DICE_COUNT; x > 0; x--) { | |
last_total += roll(SIDE_COUNT); | |
next_total += roll(SIDE_COUNT); | |
} | |
printf("The last %u rolls totaled to %lu\n", DICE_COUNT, last_total); | |
printf("Will the next %u rolls total [h]igher, [l]ower or [s]ame?\n", DICE_COUNT); | |
int c = getchar(); | |
if (c == EOF) { | |
puts("EOF encountered :("); | |
exit(EXIT_FAILURE); | |
} | |
if (strchr("hls", c) == NULL) { | |
puts("Invalid selection :("); | |
exit(EXIT_FAILURE); | |
} | |
printf((c == 'h' && next_total > last_total) | |
|| (c == 'l' && next_total < last_total) | |
|| (c == 's' && next_total == last_total) | |
? "Aww, crikey!\n" | |
: "Nah, m8. I reckon ur full of shit, m8. The next rolls have totaled %lu\n", next_total); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment