0

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
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
PxD
  • 3
  • 1
  • 2
    `string peterNum[t];` is not standard C++. – Jason Jun 18 '22 at 06:15
  • 1
    *"the program has no error but the output is not as expected."* -- no, the output being not as expected **is** an error. You probably meant no error reported by the compiler (i.e. a syntax error), which is hardly a reason to expect no semantic errors. – JaMiT Jun 18 '22 at 07:39

2 Answers2

3

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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

Problem is here:

        for(char c:b) ++peterMap[c]; // <<--here
        for(auto d:peterMap) sticks += d.second*digits[d.first];

You are increasing number in map and use it in next statement without reseting for next input entry.

But there are several problems with your code:

  1. Don't use #include <bits/stdc++.h>. I hate hackerrank for using this in their solution template.
  2. Using string peterNum[t]; is not standard as mentioned in comments.
  3. From my point of view, you don't need to use std::map for peterMap at least. Just iterate over characters of each string.
Afshin
  • 8,839
  • 1
  • 18
  • 53