Count number of ways to reach a given score in a game


Let us consider a game, in which a player can get some score with 3, 5 or 10 in each move. A target score is also given. Our task is to find how many possible ways are there to reach that target score with those three points.

By the dynamic programming approach, we will create a list of all score from 0 to n, and for each value of 3, 5, 10, we simply update the table.

Input and Output

Input:
The maximum score to reach using 3, 5 and 10. Let the input is 50.
Output:
Number of ways to reach using (3, 5, 10)50: 14

Algorithm

countWays(n)

There is only 3 possible score, they are 3, 5 and 10

Input: n is the maximum score to reach.

Output − The number of possible ways to reach score n.

Begin
   create table of size n+1
   set all table entries to 0
   table[0] := 1

   for i := 3 to n, do
      table[i] := table[i] + table[i-3]
   done

   for i := 5 to n, do
      table[i] := table[i] + table[i-5]
   done

   for i := 10 to n, do
      table[i] := table[i] + table[i-10]
   done

   return table[n]
End

Example

#include <iostream>
using namespace std;

// Returns number of ways to reach score n
int countWay(int n) {
   int table[n+1], i;    //table to store count for each value of i

   for(int i = 0; i<=n; i++) {
      table[i] = 0;    // Initialize all table values as 0
   }

   table[0] = 1;       //set for 1 for input as 0
   for (i=3; i<=n; i++)    //try to solve using 3
      table[i] += table[i-3];

   for (i=5; i<=n; i++)    //try to solve using 5
      table[i] += table[i-5];

   for (i=10; i<=n; i++)    //try to solve using 10
      table[i] += table[i-10];

   return table[n];
}

int main() {
   int n;
   cout << "Enter max score: ";
   cin >> n;
   cout << "Number of ways to reach using (3, 5, 10)" << n <<": " << countWay(n);
}

Output

Enter max score: 50
Number of ways to reach using (3, 5, 10)50: 14

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 16-Jun-2020

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements