Saturday, 29 October 2016

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

Consider a game where a player can score 3 or 5 or 10 points in a move. Given a total score n, find number of ways to reach the given score.

The idea is to create a table of size n+1 to store counts of all scores from 0 to n. For every possible move (3, 5 and 10), increment values in table and it can be solved in O(n) time and O(n) auxiliary space.


Following is the implementation in C++

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main(){
    int n;
    cout<<"Enter the score"<<endl;
    cin>>n;
    vector<int> v(n+1,0);
    v[0] = 1;
    for(auto i = 3;i!=v.size();++i){
        v.at(i)+=v.at(i-3);
    }
    for(auto i = 5;i!=v.size();++i){
        v.at(i)+=v.at(i-5);
    }
    for(auto i = 10;i!=v.size();++i){
        v.at(i)+=v.at(i-10);
    }
    cout<<*(v.end()-1);
    return 0;
}

You can change the value of the points in the game by changing the value of variable i in the three for loops...Enjoy the game!









No comments:

Post a Comment