You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.6 KiB
69 lines
1.6 KiB
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <time.h>
|
|
|
|
enum Flags {
|
|
LIST_ALL = 0x1,
|
|
SHOW_SUM = 0x2,
|
|
};
|
|
|
|
unsigned int roll_one(unsigned int sides) {
|
|
return (rand() % sides) + 1;
|
|
}
|
|
|
|
void roll(unsigned int sides, unsigned int num_rolls, unsigned int* buffer) {
|
|
for (unsigned int i = 0; i < num_rolls; i++) {
|
|
buffer[i] = roll_one(sides);
|
|
}
|
|
}
|
|
|
|
int read_roll(const char* arg, unsigned int* sides, unsigned int* num_rolls) {
|
|
return sscanf(arg, "%ud%u", num_rolls, sides);
|
|
}
|
|
|
|
int main(int argc, char** argv) {
|
|
if (argc != 2) {
|
|
printf("You must provide exactly one argument.\n");
|
|
exit(1);
|
|
}
|
|
unsigned int sides, num_rolls;
|
|
time_t t;
|
|
if (!read_roll(argv[1], &sides, &num_rolls)) {
|
|
printf("Invalid arguments! Must be of format <N>d<M>, where N is the number of dice to roll and <M> is the sides on the die.\n");
|
|
exit(2);
|
|
}
|
|
enum Flags flags = 0x0;
|
|
for (int argi = 0; argi < argc; argi++) {
|
|
if (strcmp(argv[argi], "-s") ||
|
|
strcmp(argv[argi], "--sum")) {
|
|
flags |= SHOW_SUM;
|
|
} else if (strcmp(argv[argi], "-a") ||
|
|
strcmp(argv[argi], "--all")) {
|
|
flags |= LIST_ALL;
|
|
}
|
|
}
|
|
// default if no arguments supplied: show only the sum
|
|
if (flags == 0x0) {
|
|
flags |= SHOW_SUM;
|
|
}
|
|
unsigned int rolls[256] = {0};
|
|
// seed random number generator
|
|
srand((unsigned) time(&t));
|
|
|
|
roll(sides, num_rolls, rolls);
|
|
unsigned int sum = 0;
|
|
for (unsigned int i = 0; i < num_rolls; i++) {
|
|
sum += rolls[i];
|
|
if ((flags & LIST_ALL) == LIST_ALL) {
|
|
printf("%u", rolls[i]);
|
|
if (i == num_rolls-1) {
|
|
printf("\n");
|
|
}
|
|
}
|
|
}
|
|
if ((flags & SHOW_SUM) == SHOW_SUM) {
|
|
printf("%u\n", sum);
|
|
}
|
|
}
|