I am solving challenges in hackerrank. I came across this question. I am using Dev C++ in my laptop for solving problems and later upload the code into hackerrank. For some test cases, my local Dev C++ IDE showing correct output but hackerrank is showing the wrong output for the same test case.
Code:
#include<bits/stdc++.h>
using namespace std;
bool ransomeNote(int m, int n, string magazine, string note) {
string temp = ""; int st = 0, end;
bool flag = false;
for (int i = 0; i < note.length(); i++) {
if (note[i] != ' ') {
temp += note[i];
}
if (note[i] == ' ' || i == note.length() - 1){
if ((magazine.find(temp) != string::npos)) {
st = magazine.find(temp);
magazine.replace(st, temp.length() - 1, "");
flag = true;
temp = "";
} else {
flag = false;
return flag;
}
}
}
return flag;
}
int main() {
int m,n;
cin >> m >> n;
string magazine;
string note;
fflush(stdin);
getline(cin, magazine);
getline(cin, note);
if (ransomeNote(m, n, magazine, note)) {
cout << "Yes";
} else {
cout << "No";
}
return 0;
}
Output in my IDE :
Hackerrank output :
For test cases with output No both are showing the same output but for output Yes they are showing different outputs.
Is there any problem in my code?
Thanks for your help :)
Related
I need help in figuring out the logic or code to when I want my string not to fall in the middle of another string. For example my given word is "Birthday!" and the other string to look for it is "Happy Birthday Scott". It's going to return a false value because it's missing an exclamation point. Here is the code that I've worked
int Words::matchWords(const char* string, const char* sentence, int wordNum){
int wordCount = words(sentence); // the words function counts the number of words in the sentence
int strLength = strlen(str);
int sentLength = strlen(sentence);
int i = 0;
char strTemp[100];
char sentenceTemp[100];
strcpy(strTemp, str);
strcpy(sentenceTemp, sentence);
if (wordNum > wordCount) {
return false;
}
char* temp;
for (i = 0; i < strLength; i++) {
strTemp[i] = tolower(str[i]);
}
for (i = 0; i < sentLength; i++) {
sentenceTemp[i] = tolower(str[i]);
}
temp = strstr(sentenceTemp, strTemp);
if (temp != NULL) {
return true;
if (strTemp[i] != sentenceTemp[i]) {
return false;
}
else
return true;
}
else
return false;
}
Here is a super simple program for you to look at.
All you have to do for this problem is create your strings using std::string, determine if they are inside the big string using find(), and lastly check if it was found using string::npos.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string bday = "Birthday!";
string str1 = "Happy Birthday Scott";
int found1 = str1.find(bday);
string str2 = "Scott, Happy Birthday!";
int found2 = str2.find(bday);
if (found1 == string::npos) //if Birthday! is NOT found!
{
cout << "str1: " << "FALSE!" << endl;
}
if (found2 != string::npos) //if Birthday! IS found!
{
cout << "str2: " << "TRUE!" << endl;
}
}
Note that for string::npos, you use == for something NOT being found and != for something that IS found.
I have to write a programs that takes an input of string which has some '$' and digits. The output of the program is set of all possible strings where the '$ in the string is replaced by all the other digits.
I have written the following code for it.
#include<bits/stdc++.h>
using namespace std;
int numberOf(string in)
{
int count = 0;
for(int i = 0; i <= in.size()-1; i++)
if(in[i] == '$')
count++;
return count;
}
void solve(string in, string in1, vector <string> &s,
int index)
{
if(numberOf(in) == 0)
{
s.push_back(in);
return;
}
if(index == in.size())
{
return;
}
if(in1.empty())
{
return;
}
else
{
if(in[index] == '$')
{
string in2 = in;
in2[index] = in1[0];
string in3 = in1;
in3.erase(in3.begin());
solve(in2, in1, s, index+1);
solve(in, in3, s, index);
return;
}
else
{
solve(in, in1, s, index+1);
return;
}
}
}
void replaceDollar(string in)
{
string in1 = in;
int count = 0;
for(int i = 0; i <= in.size()- 1; i++)
{
if(in[i] != '$')
{
in1.push_back(in[i]);
count++;
}
}
count = in.size() - count;
cout << "Number is " << count << "\n";
vector <string> s;
solve(in, in1, s, 0);
for(auto i = s.begin(); i != s.end(); i++)
cout << *i << " ";
cout << "\n";
}
int main()
{
int t;
cin >> t;
while(t--)
{
string in;
cin >> in;
replaceDollar(in);
}
return 0;
}
For following input
1
$45
The expected output should be
445 545
But it returns
445 545 445 545
Can anyone please explain why is it outputting repeated strings?
Also can anyone suggest a better approach to this question?
Thanks in advance!
Assuming that this is homework:
Start over. Your code is way too complex for this problem.
I would treat everything as type char
Loop/iterate over said string, using std::string::replace() to replace each instance of $ with each digit.
-- If your teacher doesn't want you using std libraries, then add another loop and compare yourself.
3a. Of course, add a check, so that you don't replace $ with $
Create a new copy of the string on each iteration.
Print each to stdout as you create them.
See this post:
How to replace all occurrences of a character in string?
p.s. Pro tip: don't use using namespace. Use the full namespace in your calls; e.g.:
Bad
using namespace std;
string = "hello world";
Good
std::string = "hello world";
I'm learning about functions in C++ and I saw this code on Tutorialspoint which tells us whether the
input is an int or a string.
Link to the Tutorialspoint article : https://www.tutorialspoint.com/cplusplus-program-to-check-if-input-is-an-integer-or-a-string
This is the original code:
#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
int main() {
string str = "sunidhi";
if (check_number(str))
cout<<str<< " is an integer"<<endl;
else
cout<<str<< " is a string"<<endl;
string str1 = "1234";
if (check_number(str1))
//output 1
cout<<str1<< " is an integer";
else
//output 2
cout<<str1<< " is a string";
}
The original one works perfectly fine, but my code either only shows ouput 1 or only shows output 2 no matter whether you enter an int or a string.
My code:
Note : my code was written on an online compiler. Link to the compiler : https://www.onlinegdb.com
#include <iostream>
using namespace std;
//the function which checks input
bool check(string s){
for(int i = 0; i < s.length(); i++)
if(isdigit(s[i]) != true)
return false;
return true;
}
//driver code
int main(){
string str = "9760";
if(check(str)){
//output 1
cout<<"Thanks! the word was " <<str;
}
else{
//output 2
cout<<"Oops! maybe you entered a number!";
}
}
Ouput when executing my program : Thanks! the word was 9760
Link to the code project: https://onlinegdb.com/HkcWVpFRU
Thank you!
You are checking if the char is a digit and returning false if it is, you should change it to
bool check(string s){
for(int i = 0; i < s.length(); i++)
if(isdigit(s[i])
return false;
return true;
}
a sidenote, if you want to check for false you can do (!bool) instead of (bool != true) it looks cleaner
For a project, we have to make a Caesar Cipher using classes and save the encrypted message inside of a file so a user can decipher it with the program.
I input the message and it has no problem encrypting the message according to the displacement/key I input (since I gave an option for the user to place the displacement they please).
However, the problem lies in decripting the message. It seems to only decript the penultimate or last letter of what I inputted and it doesnt even bother to show the remaining characters of the message.
I have currently no idea why its acting the way it is, I figured I would have to change the message to take char variables instead of string, but that would mean rewriting a large chunk of the code, and at the moment, I would like to avoid having to rewrite the code from scratch. If there are no other options, then I guess I will have to rewrite the code.
Here is the code, (hope that helps and sorry if my message may seem messy, this is the first time I post anything here):
#include<iostream>
#include<string>
#include<fstream>
#include<ctime>
#include<cstdlib>
/* This is a program that will grab a message from the user and encrypt it, then decrypt it
It will also generate a random 8-digit character password used to access the encrypted file
It will also have the ability to allow the user to choose how many spaces the cipher will take into account */
using namespace std;
//Implement a set displacement and get displacement
class Cipherer
{
private:
int displacement;
string message;
//string decryptMessage;
public:
void setDisplacer(int key);
int getDisplacer()const;
void msgEncripter(string, int);
string getMessage()const;
void msgDecripter(string);
string getDecription()const;
};
void Cipherer::setDisplacer(int key)
{
displacement = key;
}
int Cipherer::getDisplacer()const
{
return displacement;
}
void Cipherer::msgEncripter(string msg, int key)
{
string encriptedMsg = msg;
//.size returns the number of elements
for (unsigned int i = 0; i < msg.size(); i++)
{
if (msg[i] == 32) //32 is the value in ASCII of the space character
{
continue;
}
else
{
if ((msg[i] + key) > 122)
{
int temp = (msg[i] + key) - 122;
encriptedMsg[i] = 96 + temp;
}
else if (msg[i] + key > 90 && msg[i] <= 96)
{
int temp = (msg[i] + key) - 90;
encriptedMsg[i] = 64 + temp;
}
else
{
encriptedMsg[i] += key;
}
}
}
message = encriptedMsg;
}
string Cipherer::getMessage()const
{
return message;
}
void Cipherer::msgDecripter(string msg)
{
string decriptedMsg;
for (unsigned int i = 0; i < msg.size(); i++)
{
if (msg[i] == 32)
{
continue;
}
else
{
if ((msg[i] - displacement) < 97 && (msg[i] - displacement) > 90)
{
decriptedMsg[i] = (msg[i] - displacement) + 26;
}
else if ((msg[i] - displacement) < 65)
{
decriptedMsg[i] = (msg[i] - displacement) + 26;
}
else
{
decriptedMsg = msg[i] - displacement;
}
}
}
message = decriptedMsg;
}
string Cipherer::getDecription()const
{
return message;
}
static const char PASSWORD_POOL[] =
"0123456789";
int poolSize = sizeof(PASSWORD_POOL) - 1;
char getRandChar()
{
return PASSWORD_POOL[rand() % poolSize];
}
int main()
{
srand(time(0));
string pass, input, msg;
int key;
Cipherer message;
ofstream outputFile;
ifstream inputFile;
outputFile.open("SecretMSG.txt");
cout << "Write a message: \n";
getline(cin, msg);
cout << "Choose the displacement of the message (0-25): ";
cin >> key;
message.setDisplacer(key);
message.msgEncripter(msg, key);
outputFile << msg;
outputFile.close();
for (int count = 0; count < 1; count++)
{
for (int i = 0; i <= 7; i++)
{
pass += getRandChar();
}
cout << pass << endl;
}
cout << "Input password " << pass << " ";
cin >> input;
if (input == pass)
{
//Make a local variable to read file
string encryptedMessage;
inputFile.open("SecretMSG.txt");
inputFile >> encryptedMessage;
inputFile.close();
cout << message.getMessage() << endl;
cout << "If you wish to decrypt the message, type in the password once again " << pass << ": ";
cin >> input;
if (input == pass)
{
message.msgDecripter(encryptedMessage);
cout << message.getDecription() << endl;
}
else
{
exit(EXIT_FAILURE);
}
}
else
{
exit(EXIT_FAILURE);
}
system("pause");
return 0;
}
In msgDecripter your string decriptedMsg creates a string with the size 0, so any decriptedMsg[i] = is undefined behavior.
In your msgEncripter you write string encriptedMsg = msg;, and because you create a copy of mgs the encriptedMsg has the same size.
So either you do string decriptedMsg = msg or string decriptedMsg = std::string(msg.size(), ' ');
But a more c++ like approach would be to use transform.
string encriptedMsg = msg;
std::transform(encriptedMsg.begin(), encriptedMsg.end(), encriptedMsg.begin(),
[](unsigned char c) -> unsigned char {
if( c == ' ') {
return c;
} else {
// ... your other encrypting logic ...
}
});
Or using msg as source and an empty string as target and utilize std::back_inserter.
I've attempted to write a code that checks whether or not a string is a palindrome. Here is the code:
#include <iostream>
#include <string>
using namespace std;
bool pal(string str)//This block of code checks if input string is a palindrome
{
bool valid;
int i;
for (i = 0; i < str.length(); i++)
{
if (str[-i] == str[i])
{
valid = true;
}
else
{
valid = false;
}
}
return valid;
}
int main()
{
string s;
cin >> s;
if (!pal(s))
{
cout << "NO" << endl;
}
else
{
cout << "YES" << endl;
}
return 0;
}
Currently I am getting "Debug Assertion Fail" error.
str[-i] == str[i]
is a problem since negative indices are not valid indices in C++.
You need to change the strategy a little bit.
bool pal(string str)
{
int i = 0;
int j = str.length() - 1;
for ( ; i < j; ++i, --j)
{
if (str[i] != str[j])
{
// No need for any more checks.
return false;
}
}
// If we come here, the string is a palindrome.
return true;
}
C++ Provides us with an inbuilt function reverse() which can be used to reverse the Input string and compare it with un reversed string and print the output. The code goes as follows.
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
string str;
cin>> str;
string rev;
rev = str;
reverse(str.begin(), str.end()); // string reverse operation
if(rev == str){
cout<<"YES"<<endl; // Prints "Yes" if string is palindrome
}else{
cout<<"NO"<<endl; // Prints "No" if string is not palindrome
}
return 0;
}