Here's a link to the problem I am trying to solve: http://usaco.org/index.php?page=viewproblem2&cpid=187
Here's a link to the solution of the problem: http://usaco.org/current/data/sol_cowfind.html
Here's my solution that I wrote:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string n; int answer = 0;
ifstream fin("cowfind.in");
fin >> n;
fin.close();
int c = 0;
//process for finding the number of possible outputs
for(int i = 0; i < n.size(); i++)
{
if(n[i-1] == '(' && n[i] == '(') //increment the variable c for each pair of "hind" legs
c++;
if(n[i-1] == ')' && n[i] == ')') //increment answer for each pair of front legs
answer++;
}
answer = answer * c; //number of pairs of hind legs * number of pairs of front legs
ofstream fout("cowfind.out");
fout << answer;
fout.close();
return 0;
}
With that being said, what is wrong with my code? It keeps producing incorrect outputs, and I'm not sure why.
Your calculation is incorrect. Lets look at this input: ))((. There is no solution here but your code will produce 1 solution.
Try to iterate the string searching for the first literal ((. Once found - iterate the rest of the string to find )) and add them to the solution sum.
Good luck!
Related
I am writing a code in C++ to reverse all the words in a string without changing the order of the list
This is my code:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s = "God Ding";
int n = s.size();
int i = 0, j = 0;
while(j < n){
if(s[j] == ' ' || j == n-1){
reverse(s.begin()+i, s.begin()+j);
j++;
i = j;
}
else{
j++;
}
}
cout << s;
return 0;
}
Expected Output: "doG gniD"
My output: doG Ding
2nd input: "Let's take LeetCode contest"
Expected Output: "s'teL ekat edoCteeL tsetnoc"
My Output: "s'teL ekat edoCteeL contest"
Everything is working fine but only the last word is not getting reversed
You need either to detect in your if the special situation of processing the last character, or add an extra reverse after the while, if the last word was not processed (i.e. the last char was not a space).
In your case, you've added the detection of last character, but did not process the reverse before the increment, as would be the case if the word ended with a space. To correct this situation, you must take into account this special situation:
if(s[j] == ' ' || j == n-1){
reverse(s.begin()+i, s.begin()+j+(j==n-1?1:0));
// ^ (if it's last, take +1)
...
I think this would be a better implementation for your code:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string s = "God Ding", reversed_string;
std::string word;
std::istringstream ss(s); // Declaring an in string stream
while (std::getline(ss, word, ' ')) // Here getline gets every word in ss and stores it in the variable 'word'
{
// This loop reverses the variable 'word'
for (int i = word.size() - 1; i >= 0; i--)
{
reversed_string.push_back(word[i]);
}
reversed_string.push_back(' ');
}
std::cout << reversed_string;
return 0;
}
Also look up to why is "using namespace std" considered as a bad practice.
Here you have a working example:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s = "God Ding";
int i = 0;
int j = 0;
while (i <= s.length()) {
if (i == s.length() || s[i] == ' ') {
std::reverse(s.begin() + j, s.begin() + i);
j = i + 1;
}
i++;
}
std::cout << s << std::endl;
return 0;
}
I changed a lot of things.
These are the issues you need to fix:
Make your loop go beyond the last char.
Reverse if j (from your code) is beyond the last char.
In order to reverse a word, you need i to index the first char, and j to index the char after the last one.
However, your loop exits whenever j indexes the char after the last one. That's why it never reverses the last word.
The simplest fix is to do one more check after the loop exits, and reverse the last word if there is one:
while(j < n) {
if(s[j] == ' ') { // remove the `j==n-1` test
reverse(s.begin()+i, s.begin()+j);
j++;
i = j;
} else {
j++;
}
}
if(i < j) {
reverse(s.begin()+i, s.begin()+j);
}
The alternative would be to rewrite the loop in some way that finesses the problem. I don't really recommend this, given that you have something that almost works and that you know how to fix.
I have written a code in c++ to count zeros. The input have to take as string. The input will be a digit with 1 and 0.
Example:
Input: 1000000001
Output: 8
The answer should be 8 but my code is showing 0. Where is the problem in the code.
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string players;
cin >> players;
int count = 0;
for (int j = 0; j < players.length(); j++)
{
if (players[j] == 0)
{
count++;
}
}
cout << count;
return 0;
}
Please help me to find and solve it.
Thank you.
you need to compare with char not int:
if (players[j] == '0')
if condition for players[j] == 0 is wrong, your input is string type while you are trying to compare with the integer type 0. The correct if check is players[j] == '0'. Using bits/stdc++.h and using namespace std; is a big no in C++.
#include <iostream>
#include <string>
int main()
{
std:: string players;
std:: cin >> players;
int count = 0;
for(const char &player : players)
{
if (player == '0')
{
count += 1;
}
}
std:: cout << count;
return 0;
}
the condition is wrong.
write code like
players[j] == "0"
your condition means that
player[j] == NULL
Hi I'm trying to make a program that takes a sum as an input lets say 1+2+3+2+2+1 and must sort the sum out as 1+1+2+2+2+3
this is the code
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main() {
string s;
char w[100];
char x[100];
cin>>s;
//moving string s to array w to remove the '+' charachter for sorting
for (int i=0; i>s.size() ;i++){
if (s.at(i) = '+')continue;
else s.at(i) == w[i];
}
//sorting array w
sort(w,w+100);
//moving array w to array x and re-adding the '+' after sorting
for (int y=0; y > s.size();y++){
w[y]==x[y];
x[y+1]=='+';
}
cout<<x;
return 0;
}
but when i run it, it gives me a blank output
this is my first time at a c++ program im still a beginner at it
thanks for the help in advance!
I can see that you are new to the language, as you lack some understanding of basic concepts. I will first give you some tips and explanation on your mistakes, then I'll give you a more suitable solution.
First of all, try avoiding using C-styled arrays like you do with w and x. They are prone to errors because of no bounds checking, look into using std::vector or std::array instead.
== and = are NOT the same! == is used when comparing two things and = is used for assigning the right side to the left side.
Your loops are completely wrong, using
for (int i=0; i>s.size() ;i++)
will never even enter the loop. Use i < s.size() of course. I also recommend using ++i instead of i++ but that is not too important.
Your "thinking in code" is sometimes weird too
for (int i=0; i>s.size() ;i++){
if (s.at(i) = '+')continue;
else s.at(i) == w[i];
}
(not minding the > and = mistakes), why not check if it is not '+' instead of continueing and then doing something?
this code should logically be
for (int i=0; i>s.size() ;i++){
if (s.at(i) != '+') s.at(i) == w[i];
}
Last but not least, try to be consistent. First you use i as loop variable and the second time you use y. Not that it matters, but consistency is always good when coding.
I made a quick solution for your problem:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string input;
cin >> input;
vector<int> nrs = vector<int>(); //initialising this is not really needed
for (char c : input) //range based for loop, prevents mistakes with indices
{
if (c != '+')
{
nrs.push_back(c - '0'); // a char minus '0' gives the numerical value
}
}
sort(nrs.begin(), nrs.end());
string answer;
for (int nr : nrs) //range based for loop again
{
answer += to_string(nr); //use to_string to convert an int to a string
if (nr != nrs.back()) //to avoid adding the '+' after the last character
{
answer += '+';
}
}
cout << answer << endl;
return 0;
}
**Example:-Animals ( Reptiles Birds ( Eagles Pigeons Crows ) ) as input? **
I am not getting the answer for this input Animals ( Reptiles Birds ( Eagles Pigeons Crows ) )
#include<vector>
#include<string>
#define ll long long
#include <iostream>
using namespace std;
int main()
{
ll n,m,k,cb=0,ob=0;
cin>>n;
string c;
vector<string> s;
while(cb!=ob)
{
cin>>c;
if(c=="(")
ob++;
else if(c==")")
cb++;
s.push_back(c);
}
for(ll i=0;i<s.size();i++)
cout<<s[i];
return 0;
}
First problem is that the first thing you read is a long long value. Animal just isn't.
You are checking for while(cb!=ob). Some lines above cb and ob are both initialized with 0. so your loop will never run.
Even if you fix your loop the next problem will be that your input doesn't start with a (. So after reading Animal your loop will exit.
The third problem is your output. You don't flush cout when you are done.
Also: Why do you use long long for i? std::vector::size() returns size_t. So please stick with that.
One "easy" solution would be something like this:
#include<vector>
#include<string>
#include <iostream>
using namespace std;
int main()
{
int cb = 0, ob = 0;
string c;
vector<string> s;
while((ob==cb && ob==0) || ob!=cb)
{
cin >> c;
if (c == "(")
ob++;
else if (c == ")")
cb++;
s.push_back(c);
}
for (size_t i = 0; i < s.size(); i++)
{
cout << s[i];
}
cout << endl;
return 0;
}
One other thing: This code won't work if the parenthesis won't match (endless loop or premature break) and won't handle text behind the last closing parenthesis.
As your question isn't really specific about what you want my answer is just for showing you the main problems.
I would also suggest that you check your input stream for errors.
I'm supposed to read an integer n from the user, which is the followed by n words, and then what follows after that is a sequence of words and punctuation terminated by the word END. For example:
2 foo d
foo is just food without the d . END
The n words are to be "redacted" from the second line. So it would show up as:
*** is just food without the * .
I think I can figure out the redacting part. I just cannot seem to figure out how to read the words in... any help is much appreciated!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cin >> n;
string *redact = new string[n]
for(int i = 0; i < n; ++i)
cin >> redact[i] // this part works!
return 0;
}
Following code will cater the purpose.
#include <iostream>
#include <string>
#include <set>
int main()
{
int n;
std::cin >> n;
std::set<std::string> redact;
std::string word;
for(int i = 0; i < n; ++i)
{
std::cin >> word;
redact.insert(word);
}
while( std::cin>> word && word != "END" )
{
if ( redact.find(word) == redact.end() )
std::cout<<word<<' ';
}
std::cout<<'\n';
return 0;
}
I believe you are a learning C++, please note a point use typesafe, bound-safe and scope-safe C++.
So, no new delete unless you can call yourself an adept. Use the algorithms and containers provided by C++, instead of inventing your own.