Why garbage value showing up? - c++

User enters a string like '3+2+1' or '1+3+2+1+3+1'. And I just have to sort the string. But after 4-5 test cases error shows up.
Input - 2
Output - �
Input - 2+1+2+2+2+3+1+3+1+2
Output - �+1+1+1+2+2+2+2+2+3
#include<iostream>
using namespace std;
int main()
{
string s;
cin>>s;
for(int i=0;i<s.size();i+=2)
{
for(int j=0;j<(s.size()-i);j+=2)
{
if(s[j]>s[j+2])
{
swap(s[j],s[j+2]);
}
}
}
cout<<s;
return 0;
}

As ggorlen said, garbage is showing up because you're accessing a value that's out of bounds. Try checking if your "j" index plus 2 is out of bounds before doing any swap.
#include<iostream>
using namespace std;
int main()
{
string s;
cin>>s;
for(int i=0;i<s.size();i+=2)
{
for(int j=0;j<(s.size()-i);j+=2)
{
if(j+2 < s.size() && s[j]>s[j+2])
{
swap(s[j],s[j+2]);
}
}
}
cout<<s;
return 0;
}
Input 2+1+2+2+2+3+1+3+1+2
Output 1+1+1+2+2+2+2+2+3+3

Value of j is going out of bounds. Try using insertion sort:
#include <bits/stdc++.h>
using namespace std;
void insertionSort(string s)
{
int key, j;
for (int i = 1; i < s.size(); i++)
{
key = s[i];
j = i - 1;
while (j >= 0 && s[j] > key)
{
s[j + 1] = s[j];
j = j - 1;
}
s[j + 1] = key;
}
for (int i = 0; i < s.size(); i++)
cout << s[i] << " ";
cout << endl;
}
int main()
{
string s;
cin>>s;
insertionSort(s);
return 0;
}
Hope you understand the code.

Related

.exe file stopped working when i run a c++ program(no '/0')

When i run this program (i am using codeblock and its fully upgraded), it shows a box with:
''''.exe has stopped working
A problem caused the program to stop working correctly. Windows will close the program and notify if a solution is available.''''
#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
int main()
{
int no, hlf, arr[no], arrno;
cout << "ENTER A NUMBER";
cin >> no;
hlf = ceil(no/2);
for(int i = 1;i <= no;i++)
{
for(int j = 2;j <= hlf;j++)
{
int ij = i/j;
if(j != i && ij == 0)
{
goto cont;
}
else
{
continue;
}
}
arr[arrno] = i;
arrno++;
cont: ;
}
for(int k = 0;k <= arrno;k++)
{
cout << arr[k] << " ";
}
getch();
return 0;
}
There are few mistakes in your code
no need of #include <conio.h> and getch();
Array arr[no] declaration is wrong. It should be int arr[50];
Here is the corrected code that runs fine.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int no, hlf, arrno;
int arr[50];
cout << "ENTER A NUMBER";
cin >> no;
hlf = ceil(no/2);
for(int i = 1;i <= no;i++)
{
for(int j = 2;j <= hlf;j++)
{
int ij = i/j;
if(j != i && ij == 0)
{
goto cont;
}
else
{
continue;
}
}
arr[arrno] = i;
arrno++;
cont: ;
}
for(int k = 0;k <= arrno;k++)
{
cout << arr[k] << " ";
}
return 0;
}
thanks guys, i got the answer. it was my bad, i didn't post that i need to print prime numbers. its my first question in a web forum. never used one.
ps -> thanks again
include
include
using namespace std;
int main()
{
int numb = 12, half;
int arra[50], arrno = 0;
half = ceil(numb/2);
for(int r = 2;r <= numb;r++)
{
for(int t = 2;t <= half;t++)
{
if(r%t != 0 || t == r) continue;
else goto rpp;
}
arra[arrno] = r;
arrno++;
continue;
rpp:
continue;
}
for (int v = 0;v < arrno;v++)
{
cout << arra[v] << " ";
}
return 0;
}

display wheter or not an array entered by the user is unique or not

I am new to C++ I am making an array based off of user input and displaying whether the array is unique or not. my initial thought is I have to end up creating another array to store values and then compare the elements. My code compiles without errors but does not do what I want it to do. I can't used advanced methods such as hashmaps or vectors. Any help or insight is greatly appreciated!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int myArray[6];
string name;
int i, k;
int ov = 0;
int newVal = 0;
for (int index = 0; index < 6; index++)
{
cout << "Enter number a number: ";
cin >> myArray[index];
}//end loop for
for (i = 0; i < 6; i++)
{
ov = myArray[i];
}
for (k = i + 1; k < 6; k++)
{
if (ov == myArray[k])
{
newVal = 1;
}
}
if (newVal == 1)
{
cout << "Not all unique";
}
else
{
cout << "All unique";
}
cin.get();
return 0;
}

Checking Sort of String Array: Output doesn't match expected

So I am trying to create this program to check the sort of a list of words to see whether they are in ascending, or descending order. I am copying the words from a file to an array of strings. I am told the regular comparison operators function the same with strings as they do with ints. However, when I run the program, it always outputs that the list is unordered (even when it is). I would greatly appreciate any help one could offer me. Thank you!
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int checkArraySort(int array_max, string arr[]);
int main(void)
{
const int array_max = 20;
string arr[array_max];
int d;
ifstream myfile_in;
myfile_in.open ("words_in.txt");
string line;
for(int i = 0; i < array_max; i++)
{
getline(myfile_in, line);
}
d = checkArraySort(array_max, arr);
if(d == -1)
{
cout << "The array is sorted in descending order!" << endl;
}
if(d == 0)
{
cout << "The array is not sorted!" << endl;
}
if(d == 1)
{
cout << "The array is sorted in ascending order!" << endl;
}
myfile_in.close();
return 0;
}
int checkArraySort(int array_max, string arr[])
{
bool y = false;
int j = 0;
for(int i = 0; i < array_max; i++)
{
if(arr[i] < arr[i-1])
{
j++;
}
if(j == (array_max))
{
y = true;
return -1;
}
}
j = 0;
for(int i = 0; i < array_max; i++)
{
if(arr[i] > arr[i-1])
{
j++;
}
if(j == (array_max))
{
y = true;
return 1;
}
}
if(y = false)
{
return 0;
}
}
if(y = false)
should be
if(y == false)

Max Sum Of Integers

EDIT: solved! I was treating negative numbers test case as 0, instead of having the output be negative as well. thanks for the help!
Here is the challenge description: https://www.codeeval.com/open_challenges/17/
I keep getting a partially solved score. I want to know why. As in my eyes, this code works. And I believe that it is O(N) time. Thanks for looking!
Here is my code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int max(int a, int b)
{
if (a > b)
return a;
else return b;
}
int maxSubArray(vector<int> values)
{
int max_so_far = values[0];
int curr_max = values[0];
for(int i = 1; i < values.size(); ++i)
{
curr_max = max(values[i], curr_max + values[i]);
max_so_far = max(max_so_far, curr_max);
}
return max_so_far;
}
int main(int argc, char *argv[])
{
std::vector<vector<int> > Values; //to hold the values of the stock price change
ifstream file(argv[1]);
std::string line; //for the txt file input
int value = 0; //for holding the value of stock change
while (std::getline(file, line))
{
int pos = 0;
if(line.length() == 0)
continue;
else
{
std::istringstream iss(line);
std::vector<int> list; // temporary list of values to be pushed back into the 2-d vector
while (iss >> value)
{
list.push_back(value);
}
Values.push_back(list);
}
}
for(int i = 0; i < Values.size(); ++i)
{
cout << maxSubArray(Values[i]);
cout << endl;
}
/*
cout << " Printing the values : " << endl;
for (int j = 0; j < Values.size(); ++j)
{
for (int k = 0; k < Values[j].size(); ++k)
cout << Values[j][k] << " ";
cout << endl;
}
*/
return 0;
}
so I swapped out some code now. I get better score but I it's still a partial.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int max(int a, int b)
{
if (a > b)
return a;
else return b;
}
int maxSubArray(vector<int> values)
{
int max_so_far = values[0];
int curr_max = values[0];
if (curr_max < 0)
{
curr_max = 0;
max_so_far = 0;
}
for(int i = 1; i < values.size(); ++i)
{
curr_max = max(values[i], curr_max + values[i]);
curr_max = max(curr_max, 0);
max_so_far = max(max_so_far, curr_max);
}
return max_so_far;
}
int main(int argc, char *argv[])
{
std::vector<vector<int> > Values; //to hold the values of the stock price change
ifstream file(argv[1]);
std::string line; //for the txt file input
std::string token; //for the subtring that will be converted from char to int
int value = 0; //for holding the value of stock change
int count = 0;// for holding how many total cases
while (!file.eof())
{
int pos = 0;
getline(file, line);
if(line.length() == 0)
continue;
else
{
std::vector<int> list; // temporary list of values to be pushed back into the 2-d vector
while ((pos = line.find(",")) != std::string::npos )
{
token = line.substr(0,pos);
value = atoi(token.c_str());
line.erase(0, pos + 1);
list.push_back(value);
}
value = atoi(line.c_str());
list.push_back(value);
Values.push_back(list);
++count;
}
}
for(int i = 0; i < Values.size(); ++i)
{
cout << maxSubArray(Values[i]);
cout << endl;
}
cout << " Printing the values : " << endl;
for (int j = 0; j < Values.size(); ++j)
{
for (int k = 0; k < Values[j].size(); ++k)
cout << Values[j][k] << " ";
cout << endl;
}
return 0;
}
Why are you passing the vector by value here?
int maxSubArray(vector<int> values)
That looks like a significant optimization opportunity.
I think you don't read the problem exactly right. When they say 'all contiguous sub ararys', they mean you have to take the max over all i andj of for(idx = i; i < j; ++i) { total += vec[idx]; }. Right now your code basically assumes i = 0 which isn't what you are supposed to do.
Just from looking at the output examples they provide, I can see that your code isn't going to give the answer that they expect.
it seems right, the only thing I can think of is that when the list gets long, your result can overflow, so change int to long long.
Besides technical optimizations suggested in other answers, concerning the algorithm, i think a little fix can make your algorithm work. When curr_max drops to a negative value, due to encountering a negative integer that exceeds curr_max, you can simply drop all the previous integers including the current value and start over. This fix is simple, you can add one line to your loop like this:
for(int i = 1; i < values.size(); ++i)
{
curr_max = max(values[i], curr_max + values[i]);
curr_max = max(curr_max, 0); // <---------------- add this line
max_so_far = max(max_so_far, curr_max);
}

C++ - Adding Spaces to String

Hey so I am trying to write a simple program that adds spaces to a given string that has none in C++ here is the code I have written:
#include <iostream>
#include <string>
using namespace std;
string AddSpaceToString (string input)
{
const int arrLength = 5;
int lastFind = 0;
string output;
string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};
for (int i = 0; i < input.length(); i++)
{
for (int j = 0; j < arrLength; j++)
{
if(dictionary[j] == input.substr(lastFind, i))
{
lastFind = i;
output += dictionary[j] + " ";
}
}
}
return output;
}
int main ()
{
cout << AddSpaceToString("heywhatshelloman") << endl;
return 0;
}
For some reason the output only gives hey whats and then stops. What is going on I can't seem to make this very simple code work.
After reading "hey" and "whats", the value of i is more than the length of "hello" and hence no such substring exists for the code input.substr(lastFind, i).
You should check for the length of possible substring (dictionary[j]) and not i.
input.substr( lastFind, dictionary[j].size() )
Also you will have to change:
lastFind += dictionary[j].size();
So the if loop becomes:
if(dictionary[j] == input.substr(lastFind, dictionary[j].size() ))
{
lastFind += dictionary[j].size();
output += dictionary[j] + " ";
}
this works
#include <iostream>
#include <string>
using namespace std;
string AddSpaceToString (string input)
{
const int arrLength = 5;
unsigned int lastFind = 0;
string output;
string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};
for (int j = 0; lastFind < input.size() && j < arrLength; ++j)
{
if(dictionary[j] == input.substr(lastFind, dictionary[j].size()))
{
lastFind += dictionary[j].size();
output += dictionary[j] + " ";
j = -1;
}
}
return output;
}
int main ()
{
cout << AddSpaceToString("heywhatshelloman") << endl;
return 0;
}