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

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

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;
}
Online Demo

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 for peterMap at least. Just iterate over characters of each string.

Related

Table in reverse order

I was doing basic programming to print the n's table in reverse order where n is a positive integer.
Here is my approach:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int multiplier = 10;
while (multiplier--)
{
n = n*multiplier;
cout << n << endl;
}
}
But its output is not what I expected. May I know where is the problem lying in this code? Also, please do provide me some advice as after 2 months I am having MS intern interview.
My input was
2
Output came out to be
18
144
1008
6048
30240
120960
362880
725760
725760
0
I guess you probably don't want to change n every iteration, so I suggest you assign the calculation to another (scoped) variable:
int main()
{
int n;
cin >> n;
int multiplier = 10;
while (multiplier--)
{
int nn = n*multiplier;
cout << nn << endl;
}
}
Another thing: you might want to actually see the 10*n printed first (and not the "0" at the end), so you could also multiply n by multiplier+1 (or do a do-while loop instead).

Strange output from C++ in Linux Terminal

I've recently started learning programming using the C++ language. I wrote a simple program that is supposed to reverse a string which I compile in the Terminal using gcc/g++.
#include <iostream>
using namespace std;
string reverse_string(string str)
{
string newstring = "";
int index = -1;
while (str.length() != newstring.length())
{
newstring.append(1, str[index]);
index -= 1;
}
return newstring;
}
int main()
{
string x;
cout << "Type something: "; cin >> x;
string s = reverse_string(x);
cout << s << endl;
return 0;
}
I've rewritten it multiple times but I always get the same output:
Type something: banana
��
Has anyone had a problem like this or know how to fix it?
Your code initializes index to -1, and then uses str[index] but a negative index has no rational meaning in C++. Try instead initializing it like so:
index = str.length() - 1;
I can see several issues with your code. Firstly, you are initializing index to -1, and then decrementing it. Maybe you meant auto index = str.length()-1;?
I recommend you look at std::reverse, which will do the job you're after.
Your main function then becomes:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x;
cout << "Type something: ";
cin >> x;
reverse(x.begin(), x.end());
cout << x << endl;
return 0;
}
If you really want to write your own reverse function, I recommend iterators over array indices. See std::reverse_iterator for another approach.
Note, the above will simply reverse the order of bytes within the string. Whilst this is fine for ASCII, it will not work for multi-byte encodings, such as UTF-8.
You should use a memory debugger like valgrind.
It's a good practice to scan your binary with it, and will make you save so much time.

Counting and getting highest number of digits after decimal

I want to get a count of highest number of digits from an array of decimal numbers.
For example, between 2.1 and 2.01, the resultant counter should be 2 since there are 2 digits after 2.01.
Can anyone please help me with this?
#include<conio.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
double z[100],x[100],sml;
int count=0,i=0,n;
cout<<"ENter number of elements\n";
cin>>n;
cout<<"Enter the numbers\n";
for(i=0;i<n;i++)
{
cin>>z[i];
}
x[0]=z[0]-int(z[0]);
i=0;
for(i=0;i<n;i++)
while(z[i]>=0.001&&i<n)
{
x[i]=z[i]-int(z[i]);
i++;
}
for(i=0;i<n;i++)
{
cout<<x[i]<<"\t";
}
sml=x[0];
for(i=0;i<n;i++)
if(sml>x[i])
sml=x[i];
sml=sml-int(sml);
while(sml>=0.001)
{
sml=sml*10;
count++;
sml=sml-int(sml);
}
cout<<endl<<count;
return 0;
}
It's not impossible, it should be pretty easy actually. Cast it to a string, get the substring of the results starting at the decimal and count the result.
For this you will need to look up:
-casting
-indexof
-substring
If you give it a try and can't figure out comment and I will offer you a little more guidance but you should try it yourself first.
EDIT:
I don't see much of an attempt to do what I suggested, it looks like you just posted the code you had. So here is some pseudo code for you to work with:
string stringNum = to_string(decimalNum);
int decimalPos = stringNum.find(".");
string newString = stringNum.substr(decimalPos);
int answer = newString.length();
I pretty well answered it for you, you need to figure out the syntax.
just go ahead and use this:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
float number[] = {1.234,5.64,2.001,7.11112,3.999};
int a,numAfterDecimal = 0;
for(a=0;a<sizeof(number)/sizeof(*number);a++){
ostringstream buff;
buff<<number[a];
string numStr= buff.str();
int pos = numStr.find(".");
string floatStr = numStr.substr(pos+1);
if(a == 0){
numAfterDecimal = floatStr.length();
}
else if(floatStr.length() > numAfterDecimal){
numAfterDecimal = floatStr.length();
}
}
cout << " higest number of digit after decimal is:"<< numAfterDecimal <<endl ;
}
Answer is already accepted. But just for the fun of it. Here a solution using C++ algorithms.
This will reduce the number of statements in main drastically.
Maybe it helps you to better understand modern C++
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
inline size_t getNumberOfDigitsForFraction(const std::string& s)
{
size_t positionOfDecimalPoint = s.find("."); // Look for decimal point
// And count the numbers of digits after the decimal point
return positionOfDecimalPoint == std::string::npos ? 0 : s.substr(positionOfDecimalPoint+1).size();
}
int main()
{
std::cout << "Enter the number of elements that you want to check: ";
size_t numberOfElementsToCheck{0};
// Read how many data the user wants to process
std::cin >> numberOfElementsToCheck;
// Hier we will store the values
std::vector<std::string> elements(numberOfElementsToCheck);
// Copy all wanted values from std::cin
std::copy_n(std::istream_iterator<std::string>(std::cin),numberOfElementsToCheck,elements.begin());
// Get the Element with maximum digits and print the number of digits
std::cout << "Max number of digits following decimal point: " <<
getNumberOfDigitsForFraction(
*std::max_element(elements.begin(), elements.end(),
[](const std::string &sLeft, const std::string &sRight)
{ return getNumberOfDigitsForFraction(sLeft) < getNumberOfDigitsForFraction(sRight);} )) << '\n';
return 0;
}

How to convert a string to a series of integers?

Making an RPG and want the currency to be represented in platinum, gold, silver and copper. Unfortunately, my professor wants the currency stored as a string (i.e. string class, not cStrings). For example -- 0.1.23.15 would be 0 platinum, 1 gold, 23 silver and 15 copper.
I would just like to know the big idea of how to implement this. For example -- could I use strtok (i.e. I believe this only works on cStrings) or some other C++ function to accomplish this?
Here's one solution:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
string str="0.1.23.15",temp;
stringstream s(str);
vector<int> v;
while(getline(s,temp,'.'))
{
v.push_back(stoi(temp));
}
for(int i: v) cout << i << endl;//C++11 style
//for(int i=0; i<v.size(); i++) cout << v[i] << endl; //Old school :D
system("pause");
return 0;
}

int and string parsing

If i have a int say 306. What is the best way to separate the numbers 3 0 6, so I can use them individually? I was thinking converting the int to a string then parsing it?
int num;
stringstream new_num;
new_num << num;
Im not sure how to do parse the string though. Suggestions?
Without using strings, you can work backwards. To get the 6,
It's simply 306 % 10
Then divide by 10
Go back to 1 to get the next digit.
This will print each digit backwards:
while (num > 0) {
cout << (num % 10) << endl;
num /= 10;
}
Just traverse the stream one element at a time and extract it.
char ch;
while( new_num.get(ch) ) {
std::cout << ch;
}
Charles's way is much straight forward. However, it is not uncommon to convert the number to string and do some string processing if we don't want struggle with the math:)
Here is the procedural we want to do :
306 -> "306" -> ['3' ,'0', '6'] -> [3,0,6]
Some language are very easy to do this (Ruby):
>> 306.to_s.split("").map {|c| c.to_i}
=> [3,0,6]
Some need more work but still very clear (C++) :
#include <sstream>
#include <iostream>
#include <algorithm>
#include <vector>
int to_digital(int c)
{
return c - '0';
}
void test_string_stream()
{
int a = 306;
stringstream ss;
ss << a;
string s = ss.str();
vector<int> digitals(s.size());
transform(s.begin(),s.end(),digitals.begin(),to_digital);
}
Loop string and collect values like
int val = new_num[i]-'0';