Instantly share code, notes, and snippets.

# CraigRodrigues/critical.c Last active Jun 19, 2016

[2016-06-13] Challenge #271 [Easy] Critical Hit
 #include #include #include /* [2016-06-13] Challenge #271 [Easy] Critical Hit * http://bit.ly/1sLH0bn * * Critical hits work a bit differently in this RPG. If you roll the maximum value on a die, you * get to roll the die again and add both dice rolls to get your final score. Critical hits can * stack indefinitely -- a second max value means you get a third roll, and so on. With enough * luck, any number of points is possible. * */ double p = 0; // probability of a favorable outcome double probability(double d, double h) { if (d < h) { return ((1/d) * probability(d,(h-d))); // recursive case. } if (d >= h) { return ((d-h)+1)/d; // base case of a favorable outcome in the number of sides is >= hp left } return 0; } int main(void) { // Disable stdout buffering setvbuf(stdout, NULL, _IONBF, 0); // Put the die numbers and hp numbers into arrays int arrd[] = {4,4,4,4,1,100,8}; int arrh[] = {1,4,5,6,10,200,20}; // Need to loop through arrays to be able to print out the outputs for (int i = 0; i < 7; i++) { // d and h just look better to me than using the arrd and arrh double d = arrd[i]; double h = arrh[i]; p = probability(d,h); printf("d = %i, h = %i, output = %.9f\n", arrd[i], arrh[i], p); //print to 9 decimal places } }
 d = 4, h = 1, output = 1.000000000 d = 4, h = 4, output = 0.250000000 d = 4, h = 5, output = 0.250000000 d = 4, h = 6, output = 0.187500000 d = 1, h = 10, output = 1.000000000 d = 100, h = 200, output = 0.000100000 d = 8, h = 20, output = 0.009765625
Owner Author

### CraigRodrigues commented Jun 19, 2016 • edited

 My solution to this coding problem on reddit: https://www.reddit.com/r/dailyprogrammer/comments/4nvrnx/20160613_challenge_271_easy_critical_hit/ I am using CS50's library as that is the only programming class I'm taking at the moment and am only on week 4. I am sure there is a way to simplify the probability formula as well. Biggest hurdle was thinking about what the recursive case and base case would be. The twist is that there is always a chance if you roll the largest number on the die so (1/d) * (the next probability) and so on and so forth. I am not so good with understanding how to use the data types so I chose double for everything since a lot of division was involved. Also I don't know a good way to format the output. I don't know how to put it into a nice grid or anything like that. Also I should be dealing with memory allocation and clearing, but I only just learned how in CS50 and haven't implemented it over there yet.