Search code examples
c++algorithmvariablesc++14

The "sticks" variable cannot be re-assigned to 0 in C++14


I am writing a program to resolve the request:

Count the number of match sticks used to create numbers in each test case

Image

Although it is a simple problem, the thing that makes me quite confusing is that the program has no error but the output is not as expected.

Source Code:

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<char,int> digits={
    {'0',6},{'1',2},{'2',5},{'3',5},{'4',4},{'5',5},{'6',6},{'7',3},{'8',7},{'9',6}
    };
    map<char,int> peterMap;
    int t; cin >> t;
    string peterNum[t];
    for(string &a:peterNum) cin >> a;
    for(string b:peterNum){
        int sticks = 0;
        string tomNum, n;
        for(char c:b) ++peterMap[c];
        for(auto d:peterMap) sticks += d.second*digits[d.first];
        cout << sticks << ' ';
    }
    return 0;
}

Input:

5              (Number of test cases)
1 0 5 10 15 

Output:

2 8 13 21 28 

Expected Output:

2 6 5 8 7

Solution

  • There are 3 problems with your code

    Try this instead:

    #include <iostream>
    #include <map>
    #include <string>
    using namespace std;
    
    int main() {
        map<char,int> digits = {
            {'0',6},{'1',2},{'2',5},{'3',5},{'4',4},{'5',5},{'6',6},{'7',3},{'8',7},{'9',6}
        };
        int t; cin >> t;
        for (int i = 0; i < t; ++i) {
            string a; cin >> a;
            int sticks = 0;
            for(char ch : a) sticks += digits[ch];
            cout << sticks << ' ';
        }
        return 0;
    }
    

    Online Demo