- C Keeping Track of the Longest Streak
- int main(){
- int number_of_flips;
- int coin_flip;
- int previous_flip = 2;
- int head_count = 0;
- int tail_count = 0;
- int highest_head = 0;
- int highest_tail = 0;
- srand(time(NULL));
- cout << "Enter the number of coin flips:" << endl;
- cin >> number_of_flips;
- system("cls");
- for(int i = 0; i < number_of_flips; i++){
- coin_flip = rand() % 2;
- if(coin_flip == 0){
- cout << "Heads" << endl;
- if(coin_flip == previous_flip){
- head_count = head_count + 1;
- }
- else{
- if(head_count > highest_head){
- highest_head = head_count;
- }
- head_count = 0;
- }
- }
- if(coin_flip == 1){
- cout << "Tails" << endl;
- if(coin_flip == previous_flip){
- tail_count = tail_count + 1;
- }
- else{
- if(tail_count > highest_tail){
- highest_tail = tail_count;
- }
- tail_count = 0;
- }
- }
- previous_flip = coin_flip;
- }
- cout << "The longest run of heads is " << highest_head << endl;
- cout << "The longest run of tails is " << highest_tail << endl;
- system("pause");
- return 0;
- }
- Tails
- Tails
- Tails
- Heads
- Heads
- Tails
- Tails
- Tails
- Tails
- Heads
- The longest run of heads is 1
- The longest run of tails is 2
- int main(){
- int number_of_flips;
- int coin_flip;
- int previous_flip = 2;
- int head_count = 0;
- int tail_count = 0;
- int highest_head = 0;
- int highest_tail = 0;
- srand(time(NULL));
- cout << "Enter the number of coin flips:" << endl;
- cin >> number_of_flips;
- system("cls");
- for(int i = 0; i < number_of_flips; i++){
- coin_flip = rand() % 2;
- if(coin_flip == 0){
- cout << "Heads" << endl;
- if(coin_flip == previous_flip){
- head_count = head_count + 1;
- }
- else{
- if(head_count > highest_head){
- highest_head = head_count;
- }
- head_count = 1;
- }
- }
- if(coin_flip == 1){
- cout << "Tails" << endl;
- if(coin_flip == previous_flip){
- tail_count = tail_count + 1;
- }
- else{
- if(tail_count > highest_tail){
- highest_tail = tail_count;
- }
- tail_count = 1;
- }
- }
- previous_flip = coin_flip;
- }
- if(head_count > highest_head){
- highest_head = head_count;
- }
- if(tail_count > highest_tail){
- highest_tail = tail_count;
- }
- cout << "The longest run of heads is " << highest_head << endl;
- cout << "The longest run of tails is " << highest_tail << endl;
- system("pause");
- return 0;
- }
- Tails // Does not count this one because flip != last_flip
- Tails // tail_count is 1
- Tails // tail_count is 2
- Heads // Does not count first flip on flip switch, reset head_count to 0
- Heads // head_count is 1
- Tails // Does not count first flip, set max_tail to 2, reset tail_count to 0
- Tails // tail_count is 1
- Tails // tail_count is 2
- Tails // tail_count is 3 but will never be set unless we flip head, then tail.
- Heads // Does not count first switch, set max_head to 1, reset head_count to 0