Different output on online judge - c++

I was trying a problem in hackerrank(online judge). The task is to take an input string and then print the characters of the even indices first, followed by a space and then the characters in the odd indices for a given number of test cases 'n'. I was able to solve it. However I get different output on my compiler and a different one in the online judge. The output i get on my computer is correct one but i am not getting the same in the online judge. Here is my code :-
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main()
{
int n;
cin>>n;
getchar();
char s[1000];
for(int i=0;i<n;i++)
{
cin.getline(s,1000);
int len;
len=strlen(s);
for(int j=0;j<=len;j++)
{
if(j%2==0)
cout<<s[j];
}
cout<<" ";
for(int m=0;m<len;m++)
{
if(m%2!=0)
{
cout<<s[m];
}
}
cout<<endl;
}
return 0;
}
Input given
1
Hacker
Output when running on my computer using g++
Hce akr
Output when running on the online judge
Hce
Please Help.
Note: 0 is considered an even index.

for(int j=0;j<=len;j++)
{
if(j%2==0)
cout<<s[j];
}
You wrote <= instead of <.
Here, when the word length is even (as is "Hacker"), you're accidentally printing the terminating NULL as well.
The result of this depends on your execution environment. Apparently your terminal just ignores it, and this "online judge" of which you speak does not, instead using it as a NULL terminator for your program output!! (Which is poor coding if you ask me)
N.B. You don't get program output from your compiler. You get it from executing your program, over which the compiler has no control.
Also, please, for the love of Cthulhu, indent your code and use meaningful variable names?

Related

Giving the change using a "greedy "method - what(): std::bad_allock

After expanding my program to include change such as 0.01,0.02,0.05,0.1,0.2,0.5 (zł) I was given:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Process returned 3 (0x3) execution time : 56.358 s
Press any key to continue.
It isn't the first time I have gotten this message, but it only happens upon using vectors.
The program would be working fine had I refrained from adding the update, but I'm curious as to why this message pops out, and what the cause of it may be. I suppose it has to do with the bad placement of something in the memory?
Thank you for your help people.
#include <iostream>
#include <vector>
using namespace std;
int main(){
int iloscMonet=9;
double monety[iloscMonet]={0.01,0.02,0.05,0.1,0.2,0.5,1,2,5};
double resztaDoWydania=4.01;
int licznikMonet=0;
vector <int> jakieMonety;
while(resztaDoWydania){
int nominal = 0;
for(int i=0;i<iloscMonet;i++){
if((monety[i]<=resztaDoWydania)&&(monety[i]>nominal)){
nominal=monety[i];
}
}
resztaDoWydania-=nominal;
jakieMonety.push_back(nominal);
licznikMonet++;
}
cout<<"ile monet?: "<<licznikMonet<<endl;
cout<<"jakie monety?: ";
for(int i=0;i<jakieMonety.size();i++){
cout<<jakieMonety.at(i)<<" ";
}
return 0;
}
Calculation of floating-point number may contain errors.
When I add #include <cstdio> in top of your code and printf("%.30f\n", resztaDoWydania); after licznikMonet++;, I found that the value of resztaDoWydania stacking at 0.009999999999999786837179271970.
You should avoid using floating-point numbers as much as you can.
In this case, you can multiply each of the values by 100 to make them integers.
#include <iostream>
#include <vector>
using namespace std;
int main(){
int iloscMonet=9;
int monety[iloscMonet]={1,2,5,10,20,50,100,200,500};
int resztaDoWydania=401;
int licznikMonet=0;
vector <int> jakieMonety;
while(resztaDoWydania){
int nominal = 0;
for(int i=0;i<iloscMonet;i++){
if((monety[i]<=resztaDoWydania)&&(monety[i]>nominal)){
nominal=monety[i];
}
}
resztaDoWydania-=nominal;
jakieMonety.push_back(nominal);
licznikMonet++;
}
cout<<"ile monet?: "<<licznikMonet<<endl;
cout<<"jakie monety?: ";
for(int i=0;i<jakieMonety.size();i++){
cout<<jakieMonety.at(i)<<" ";
// if you want outpuf of floating-point numbers as the original
//cout<<(jakieMonety.at(i)/100.0)<<" ";
}
return 0;
}
try while(resztaDoWydania>0)

Trying to add elements to a Vector classified with a Struct

I'm making a program to basically show the statistics about words the user enters. The rest of the program is fine so far, but I'm having a hard time adding words to a vector of type WordCount.
I have looked around and found several answers, which I would've thought could solve my issue, but I either get a very weird compiler error or it just does not work. I have tried using emplace_back and push_back with calls I thought was right. In essence, my problem code is as follows:
#include <iostream>
#include <string>
#include <vector>
using namespace std; //for simplicity here
struct WordCount {
string word;
int count;
//I have tried using this too:
WordCount(string _word, int _count) : word{_word}, count{_count} {}
};
//...//
void wordToVector(/**...**/,string addStr, vector<WordCount>& wordStats){
/**... code that I've tested to work; basically determined if the
word was already said as I need to have unique words only...**/
wordStats.push_back(WordCount(addStr, 1));
/** also tried: (some had "#include <istream>" when using emplace_back
but that didn't seem to make a difference for me in any case)
wordStats.emplace_back(WordCount(addStr, 1));
wordStats.emplace_back({addStr, 1});
wordStats.push_back(addStr, 1)
wordStats.push_back(addStr).word; (and wordStats.push_back(1).count;)
**/
}
int main() {
vector<WordCount> wordStats(1); //"1" to initialize the size
wordStats.at(0).word = "";
wordStats.at(0).count = 0;
/**There's already a part to change the first values to what they should
be, and it worked last I tested it. Below is a part was for my
personal use to see if anything came out... if it worked**/
for (int i = 0; i < 3; i++) {
cout << wordStats.at(i).word << endl;
cout << wordStats.at(i).count << endl;
}
return 0;
}
I must use a vector for this and cannot use pointers (as I've seen suggested) or #include <algorithm> per the instructions. If I typed in "Oh happy day!", it should be able to print (when fixed, with the current cout statements):
OH
1
HAPPY
1
DAY
1
(There's an earlier part that capitalizes every letter, which I tested to work).
This is my first post here because I'm lost. Please let me know if I provided too much or not enough. **Edited formatting
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct WordCount {
string word;
int count;
};
void wordToVector(string addStr, vector<WordCount>& wordStats){
for (int i = 0; i < wordStats.size(); i++) {
if (wordStats[i].word == addStr) {
wordStats[i].count = wordStats[i].count + 1;
return;
}
}
struct WordCount wc;
wc.word = addStr;
wc.count = 1;
wordStats.push_back(wc);
}
int main() {
vector<WordCount> wordStats;
wordToVector("hehe", wordStats);
wordToVector("hehe", wordStats);
wordToVector("haha", wordStats);
for (int i = 0; i < wordStats.size(); i++) {
cout << wordStats.at(i).word << endl;
cout << wordStats.at(i).count << endl;
}
return 0;
}
Using this code I get output:
hehe
2
haha
1
Is there anything else that needs to be added?
If you want to split the input by the spaces and check for occurrences of every word in the input it could be quite inefficient for longer texts to check for every word (Would be linear I think with M*N complexity), so if you are allowed I do suggest to use a map with word as key and value as the amount of occurrences - or something in that fashion.

For and while loop not working in a globally defined function

#include <iostream>
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
int help(int i,int money,int denomination[]){
int sum=0;
int j=0;
while(i>0){
if(i&1) sum+=denomination[j];
i=i>>1;
j+=1;
}
return sum==money?1:0;
}
int ans(int numOfNotes,int money,int denomination[]){
for(int i=0;i<(1<<numOfNotes);i++){
if(help(i,money,denomination)){
return 1;
}
}
return 0;
}
int main() {
int testCases,numOfNotes,money;
cin>>testCases;
while(testCases>0){
cin>>numOfNotes>>money;
int denomination[numOfNotes];
int i=0;
while(numOfNotes){
cin>>denomination[i];
i++;
numOfNotes--;
}
testCases--;
ans(numOfNotes,money,denomination)==1?cout<<"Yes"<<endl:cout<<"No"<<endl;
}
return 0;
}
If there exists a subset of array denomination such that it amounts to money, program should show "Yes", else "No".
But for the following simple input
1
3 3
1
1
1
output is coming out to be
No
whereas it should be
Yes
According to me, the for and while loops are not working in the ans and help functions. Is there any other bug in the program?
You're modifying numOfNotes in the inner while loop in main, which means its value is 0 when later passed to ans. The loops in the functions are working, you're just giving them other limits than you expected.
You can easily solve issues like this yourself by stepping through your program in a debugger and inspecting variable values and control flow along the way. This is a vital programming skill. See also How to debug small programs by Eric Lippert.
Unrelated to the problem at hand, but please also see these SO questions about what's wrong with including bits/stdc++.h and declaring using namespace std;.

Programming Principles and Practice using C++ while-loop drill. Can't find a way to exit the loop

I'm going through Bjarne Stroustrup's 'Programming : Principles and Practice using C++" and I've got a drill which tells me to write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them and that it should exit when "|" is entered. I've written the program(I'm sure there's a easier way of writing it, but I've got the "gift" of overcomplicating things), but I can't find a way of exiting the loop. Here's the code:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> answers;
int answer;
int intCounter=0;
while(answers.size()<=2 )
{
if(answer=='|')
{
return 0;
}
std::cin>>answer;
answers.push_back(answer);
++intCounter;
if(intCounter==2)
{
for(int x : answers)
{
std::cout<<x<<'\n';
}
answers.clear();
intCounter=0;
}
}
return 0;
}
Basically if I write an if statement to check if answer is equal to '|', the compiler thinks i meant the int value of it(124 or something like that) and terminates the loop when I write 124, and that's clearly not what I want. I've tried to look over the internet for a way of converting an int into a char, but I haven't understood anything from there. The simplest solution would be the best.
cin >> answer will fail when the next non-whitespace character to be read is not a number. You can use that behavior to end the loop.
// Break inside the loop.
while( true )
{
std::cin>>answer;
// If there was an error in reading, break out of the loop.
if ( !std::cin )
break;
answers.push_back(answer);
++intCounter;
if(intCounter==2)
{
for(int x : answers)
{
std::cout<<x<<'\n';
}
answers.clear();
intCounter=0;
}
}
Two changes:
If your task is to just print numbers you could just use string.
You are checking value of answer to | before its even been input.
So
#include<iostream>
#include <vector>
#include<string>
using namespace std;
int main(){
std::vector<string> answers;
string answer;
int intCounter=0;
while(answers.size()<=2 ){
std::cin>>answer;
//after input
if(answer=="|"){
return 0;
}
answers.push_back(answer);
++intCounter;
if(intCounter==2){
for(int x=0;x< answers.size();x++){
std::cout<<answers[x]<<'\n';
}
answers.clear();
intCounter=0;
}
}
return 0;
}

C++ Int getting random value after function that isn't supposed to change it

Okay - yes, this is homework, but it isn't mine. I have a friend taking an introductory C++ course who asked me for help, and I helped them write this program, but there is one weird bug that I can't figure out. Any helpful suggestions would be greatly appreciated. Thanks!!
The following is the code. The problem is that after the add_loop function, the int loop_size gets a random value. Within the function, it has the value it is supposed to have, but afterwards, it changes.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define STRING_SIZE 50
void get_template (char StemLoop [])
{
char Template [STRING_SIZE];
cout<<"Please enter a template for the stem:";
cin>> Template;
strcpy (StemLoop, Template);
}
void add_loop (char StemLoop[], int loop_size)
{
char random_loop [STRING_SIZE];
int random_array[STRING_SIZE];
for (int i=0; i<loop_size; i++)
{
random_array[i] = rand() % 4;
if (random_array[i]==0)
random_loop[i]='A';
else if (random_array[i]==1)
random_loop [i]='U';
else if (random_array[i]==2)
random_loop [i]='G';
else if (random_array[i]==3)
random_loop [i]='C';
}
strcat (StemLoop, random_loop);
}
void add_complement(char StemLoop[], int loop_size)
{
int x =strlen(StemLoop);
int j=0;
char complement [STRING_SIZE]="";
for (int i=0; i<(x-loop_size); i++)
{
if (StemLoop[i]=='A')
complement[j]='U';
else if (StemLoop[i]=='U')
complement[j]='A';
else if (StemLoop[i]=='G')
complement[j]='C';
else if (StemLoop[i]=='C')
complement[j]='G';
j++;
}
strcat(StemLoop,complement);
}
void main()
{
int loop_size=0;
cout<<"Please enter the size of the loop: ";
cin>>loop_size;
char StemLoop [STRING_SIZE];
//Part1: the template
get_template (StemLoop);
//This is supposed to be the function that adds the loop of random "genes".
//It works, and within it the int loop_size is the correct value...
add_loop (StemLoop, loop_size);
/*...but here it is a random number. It's as if the random value generated
within the function is getting assigned to it. And of course, it's throwing off the
entire program.
*/
//Part#3: the complement
add_complement (StemLoop, loop_size);
cout<<"The complete stem-loop strand is:"<<StemLoop<<endl;
}
You're not 0-terminating random_loop before you use it in strcat, so strcat can write all over your stack. Try this:
random_loop[i] = 0;
strcat (StemLoop, random_loop);
A more serious problem could be that you're not checking you have enough room to strcat.