/* * tn.c * Copyright (c) 1999 by Scott M. Harrison. All rights reserved. */ /* * This program determines the chances to roll a specific * number of successes with a specific target number on a * specific number of dice. */ #include #include #include /* * This routine determines the percentage chance * to roll the provided target number on one die * using the rule of six. */ double targetNumberPercentage(int tn) { double retval; int divValue = (tn - 1) / 6; int modValue = (tn - 1) % 6; retval = (double)(6 - modValue) / pow(6.0, (double)(divValue + 1)); return retval; } /* * This routine determines the factorial of the * provided number. */ double factorial(int number) { double retval = 1.0; int i; for (i = 2; i <= number; i++) retval *= (double) i; return retval; } /* * This routine determines the number of possible * combinations of a set in a group. */ double combination(int set, int group) { return (factorial(group) / (factorial(set) * factorial(group - set))); } void main(int argc, char *argv[]) { int retval = 0; if (argc != 4) { fprintf(stderr, "Usage: %s \n", argv[0]); retval = 1; } else { int tn = atoi(argv[1]); int successes = atoi(argv[2]); int dice = atoi(argv[3]); if (tn < 2) { fprintf(stderr, "The target number must be at least 2.\n"); retval = 2; } else if (successes < 1) { fprintf(stderr, "The number of successes must be at least 1.\n"); retval = 3; } else if (dice < 1) { fprintf(stderr, "The number of dice must be at least 1.\n"); retval = 4; } else if (successes > dice) { fprintf(stderr, "The number of successes is more than the number of dice rolled.\n"); retval = 5; } else { int i; double result = 0.0; double chance, inverseChance; chance = targetNumberPercentage(tn); inverseChance = 1.0 - chance; fprintf(stdout, "The chance to roll TN %d on a die is %g%%.\n", tn, chance * 100.0); for (i = successes; i <= dice; i++) { result += combination(i, dice) * pow(chance, (double) i) * pow(inverseChance, (double) (dice - i)); } fprintf(stdout, "The chance to roll at least %d successes of TN %d on %d dice is %g%%.\n", successes, tn, dice, result * 100.0); } } exit(retval); }