# Count ways to reach a score using 1 and 2 with no consecutive 2s in C++

C++Server Side ProgrammingProgramming

Given a score of runs. The goal is to reach that score in a way that the batsman can take either 1 or 2 runs only in a single ball. The restriction is that no 2 runs can be taken consecutively. For example, to reach the given score 6, one can take runs like: 1+2+1+2 but not 2+2+1+1 or any other way with two consecutive 2’s.

For Example

## Input

score=4

## Output

Count of ways to reach a score using 1 and 2 with no consecutive 2s are: 4

## Explanation

The ways in which we can reach the score 4 in following ways:
1+1+1+1, 1+1+2, 1+2+1, 2+1+1

## Input

score=5

## Output

Count of ways to reach a score using 1 and 2 with no consecutive 2s are: 6

## Explanation

The ways in which we can reach the score 6 in following ways:
1+1+1+1+1, 2+1+1+1, 1+2+1+1 , 1+1+2+1, 1+1+1+2, 2+1+2

Approach used in the below program is as follows

In this approach we will use a flag to mark that previous score was two or not, in case it was 2 we will cover the score with the next run as 1 else 2.

• Take an integer variable score.

• Take flag variable check = false initially.

• Function ways_reach_score(int score, bool check) tells the count of ways to reach a score using 1 and 2 with no consecutive 2s.

• Take the initial count as 0.

• If the score is 0 return 0.

• If the check is false means previous run was 1, so in case current score is greater then ways will be count = ways_reach_score(score − 1, false) + ways_reach_score(score − 2, true).

• Otherwise the previous run was 2, so the consequent run will be 1 only so ways will be ways_reach_score(score − 1, false).

• At the end we will get total ways in count.

• Return count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int ways_reach_score(int score, bool check){
int count = 0;
if (score == 0){
return 1;
}
if (check == false && score > 1){
count += ways_reach_score(score − 1, false) + ways_reach_score(score − 2, true);
} else {
count += ways_reach_score(score − 1, false);
}
return count;
}
int main(){
int score = 4;
bool check = false;
cout<<"Count of ways to reach a score using 1 and 2 with no consecutive 2s are: "<<ways_reach_score(score, check);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of ways to reach a score using 1 and 2 with no consecutive 2s are: 4