Well, I can't really post the code in C++ because I can't remember the details of how to program in C++, but I guess I'll just post the Java code. The algorithm isn't particularly efficient either; I just threw it together to test formulas. I suppose the advantage of that is that it should be easy to understand and convert to C++ on your own.
public class Dice {
public static void main(String[] args) {
int n = 3;
int s = 6;
int r = 4;
int[] dice = new int[n];
for(int i = 0; i < dice.length; i++)
dice[i] = 1;
int sum = 0;
int count = 0;
do {
sum += count(dice, r);
count++;
dice = next(dice, s);
} while(!done(dice));
double average = (double)sum / count;
System.out.println(average);
}
public static int count(int[] arr, int r) {
int sum = 0;
for(int i = 0; i < arr.length; i++)
sum += arr[i];
if (sum <= r)
return 0;
return sum - r;
}
public static int[] next(int[] arr, int s) {
for(int i = 0; i < arr.length; i++) {
arr[i]++;
if (arr[i] <= s)
return arr;
arr[i] = 1;
}
return arr;
}
public static boolean done(int[] arr) {
for(int i = 0; i < arr.length; i++) {
if (arr[i] != 1)
return false;
}
return true;
}
}
Now, I'm not going to leave you completely in the dark as to how to translate the code. Lemme see, here's some important notes that should help you a lot...
- All Java programs are in classes, but this code doesn't need to be in a class when in C++. That means that when you copy the functions over you don't need the "public static" parts of the function names and you don't need to put them into classes.
- "public static void main(String[] args)" is the default entry point into a Java program, much like "void main()" is for C++. This can be changed without consequence because I never used args.
- "arr.length" is the length of the array; you could simply pass "n" as a parameter into the functions that use it and use "n" instead of "arr.length"
- "System.out.println()" is just standard output (like printf or cout).
- "int[] dice = new int[n];" creates an array of "n" integers. I don't recall if this can be done as easily in C++.
As you can see, the code is not particularly complex\special, is short (brute force methods can be that way sometimes), but gets the job done. It can also be sped up but for small enough N it's fast enough.
Also, if Xebra is right and there isn't a single formula to calculate this, I suppose at least you could take advantage of the R <= N+S and R <= N formulas to create something that works for a lot of cases.