Home > Enterprise >  The "sticks" variable cannot be re-assigned to 0 in C 14
The "sticks" variable cannot be re-assigned to 0 in C 14

Time:06-18

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

CodePudding user response:

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

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:

  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.
  • Related