I am trying to make a simple simulator for dice rolls. The program needs the following parms. 1) The NUMBER of dice to roll. 2) The number of FACES on each dice. 3) Lastly, it needs how many simulations to walk through (COUNT). Either I let the user take the default or they need to enter the parms when starting the program.
The code is kind of slow to execute and I am wondering if I did something really foolish. I have never write a simulation program like this before. Any suggestion would be helpful.
Code:#include <stdio.h> #include <stdlib.h> int main(long argc, char *argv[]) { unsigned long a = 0, b = 0, number = 0; long stime = 0, ltime = 0; unsigned long *dice, *numbers, COUNT, NUMBER, FACES = 6, TOTAL; if ( argc == 4 )//Did they want to define all parms { COUNT = atol(argv[1]); NUMBER = atol(argv[2]); FACES = atol(argv[3]); } else if ( argc == 3 )//Did they want to define sim count and number of die, but defaulted to only 6 faces { COUNT = atol(argv[1]); NUMBER = atol(argv[2]); FACES = 6; } else if ( argc == 2 )//Default to only 6 Faces on the dice and roll 1 dice, but let they set sim count { COUNT = atol(argv[1]); NUMBER = 1; FACES = 6; } else if ( argc == 1 )//Default 100 sims, 1 dice, and use a 6 sided die. { COUNT = 100; NUMBER = 1; FACES = 6; } else // They have used too many parms { fprintf(stderr, "\nUsage: %s [COUNT] [NUMBER] [FACES]\n\n", argv[0]); exit(1); } //Seed for Random Numbers ltime = time(NULL); stime = (unsigned) (ltime)/2; srand(stime); //Determine total options or max rolled number TOTAL = FACES*NUMBER; //Create memory for needed dices dice = malloc((NUMBER) * sizeof(NUMBER)) ; if (!dice) { fprintf(stderr, "Memory Allocation Error\n"); exit(2); } else { //Set Dice Faces to Zero for ( a = 0; a < (NUMBER); a++) { dice[a] = 0; } } //Create memory for Sum of dice counts numbers = malloc( (TOTAL) * sizeof(long) ); if (!numbers) { fprintf(stderr, "Memory Allocation Error\n"); exit(2); } else { //Set number aggrate to 0 all around for ( a = 0; a <= (TOTAL); a++) { numbers[a] = 0; } } //Start running sim for COUNT Rolls for (a = 1; a <= COUNT; a++) { //Roll the dice number = 0; for (b = 0; b < NUMBER; b++) { dice[b] = (unsigned long) (rand() % FACES) + 1; number = number + dice[b]; } //Count the rolls totals for (b = 1; b <= TOTAL; b++) { if ( number == b ) { numbers[b]++; } } //Show every millionth sim if ( a % 1000000 == 0 ) { fprintf(stderr, "%ld\n", a); } } //Display totals for (b = NUMBER; b <= TOTAL; b++) printf("%-20ld %-20ld %%%-20.2f\n", b, numbers[b], (float) numbers[b]/COUNT*100); return 0; }



LinkBack URL
About LinkBacks


