I am trying to write a little program that calculates combinations in coin flipping:
1) the user types in input how many coin tosses he wants to perform.
2) the program has to return all the possible combinations based on user input.
Example:
1 coin toss --> result: HT
2 coin tosses --> result: HH HT TH TT
3 coin tosses --> result: HHH HHT HTH HTT THH THT TTH TTT
ecc...
I have tried this approach in C++:
#include <iostream>
#include <string>
using namespace std;
// function that returns the coin face using the indexes used in for loops below
string getCoinFace(int index) {
if(index == 0)
return "H";
return "T";
}
int main() {
string result = "";
// 3 nested loops because I toss the coin 3 times
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
result += getCoinFace(i) + getCoinFace(j) + getCoinFace(k) + '\n';
}
}
}
cout << result;
/* --OUTPUT--
HHH
HHT
HTH
HTT
THH
THT
TTH
TTT
*/
return 0;
}
This works only if 3 coin tosses are performed, but I need to handle N coin tosses instead.
Maybe I need to change my approach to the problem and apply recursion but I can't figure out how.
Do you have any suggestion ?
Thanks.
IncrementOdometer()function that moves the odometer from its current state to the next state, and aPrintOdometer()function that prints out the current state, and call them. - Jeremy Friesner