I am writing a program to resolve the request:
Count the number of match sticks used to create numbers in each test case
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
CodePudding user response:
There are 3 problems with your code
don't use
<bits/stdc .h>
, it is non-standard and promotes bad practice.variable-length arrays are not standard C , use
std::vector
instead. But this is actually not necessary in this case, because...peterMap
is completely unnecessary and needs to be removed, it is screwing up your result.
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;
}
CodePudding user response:
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:
- Don't use
#include <bits/stdc .h>
. I hate hackerrank for using this in their solution template. - Using
string peterNum[t];
is not standard as mentioned in comments. - From my point of view, you don't need to use
std::map
forpeterMap
at least. Just iterate over characters of each string.