C++ recursive algorithm for permutation [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The permute() function runs into an infinite loop and I can't seem to find why?
i tried checking the function by removing the recursive call and it seems to be working fine. I also have the base case, so don't know where is the problem.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string smallString(string s, int k){ // computes a string removing the character at index k
int i,j;
string res;
for(i=0,j=0;j<s.length();i++,j++){
if(i==k){j++;}
res.push_back(s[j]);
}
return res;
}
void permute(string s1, string s2, size_t len){
if(len==1)
{cout<<"length is equal to 1"<<(s1+s2)<<'\n'; return;} //base case
else{
for(int i =0;i<len;i++){
string temp= s2.substr(i,1);
s1.append(temp);
string fin = smallString(s2,i);
//cout<<temp<<'\t'<<s1<<'\t'<<fin<<'\t'<<fin.length()<<'\n';
permute(s1,fin,fin.length());
s1.erase((s1.length()-1));
//cout<<"printing s1 : "<<s1<<'\n';
}
}
}
int main(){
string s2="abc";
string s1="";
permute(s1,s2,s2.length());
return 0;
}

Your problem seems to be in the "smallString" function. In that function, OutOfRange is used in s[j]. I put print like
for(i=0,j=0;j<s.length();i++,j++)
{
if(i==k){j++;}
cout<<"smallString:: s ::"<<s<<'\t'<<"k::"<<k<<'\n';
res.push_back(s[j]); //Problem is here...
}
Now Output print is like
smallString:: s ::abc k::0
smallString:: s ::abc k::0
smallString:: s ::bc k::0
smallString:: s ::bc k::1
smallString:: s ::bc k::1
smallString:: s ::b k::0
smallString:: s ::b k::1
smallString:: s ::b k::1
.
.
So, At one point of time it comes as "s ::b k::1" so you are selecting the character at the position 1 from the string "b".
String is basically an char array which start from 0 to (n-1). For string "b" only 0th position is having character 'b'. but we are accessing an non-existing position.
So it throws error and start looping continuously from here.
FIX FOR YOUR ISSUE:
for(i=0,j=0;j<s.length();i++,j++)
{
if(i==k)
{
j++;
}
else
{
cout<<"smallString:: s ::"<<s<<'\t'<<"k::"<<k<<'\n';
res.push_back(s[j]);
}
}

Related

Caeser's Cipher not working for lower case characters [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Please someone run it , It runs fine for all uppercase values but if you include some x y or z the code breaks.
I found this in hackerrack and several test cases were passed but several failed.
#include<iostream>
using namespace std;
string caesarCipher(string, int);
int main() {
string s;
int places, length;
cin>>length;
cin>>s;
cin>>places;
if(places >26) {
places = places % 26 ;
}
s= caesarCipher(s,places);
cout<<s;
}
string caesarCipher(string S, int k){
for(int i=0;i<S.length();i++){
if(S[i]>='a' && S[i] <='z'){
S[i] = S[i]+k;
if(S[i]>'z'){
S[i]=S[i]-'z'+'a'-1;
}
}
else if(S[i]>='A' && S[i] <= 'Z'){
S[i] = S[i]+k;
if(S[i]>'Z'){
S[i]= S[i]-'Z'+'A'-1;
}
}
else
;
}
return S;
}```
To my own surprise, it looks like strings do not like certain values, not even temporarily.
If you use
S[i] = (S[i]-'a'+k)%26+'a'; instead of
S[i] = S[i]+k;, no value outside of a-z is ever written to the string, which as far as I tested avoids your problem.
An input of "Helloxyz" with a shift of 2 gets an output of "Jgnnqzab".
An the reverse, with a shift of 24 gets "Helloxyz" again.
With that, you do not need
if(places >26) {
places = places % 26 ;
}
/* ... */
if(S[i]>'z'){
S[i]=S[i]-'z'+'a'-1;
}
/* ... */
if(S[i]>'Z'){
S[i]= S[i]-'Z'+'A'-1;
}

runtime error: pointer index expression with base 0x000000000000 overflowed to 0xffffffffffffffff (basic_string.h) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
The question is to find the largest common prefix strings amongst the array of string.
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
This is what I have tried till now.
class Solution {
public:
string longestCommonPrefix(const vector<string>& v) {
if ( v.empty() )
{
return 0;
}
string smin = *min_element(v.begin(), v.end(),
[] (const std::string& s1, const std::string& s2) {
return s1.length() < s2.length(); }
);
string str="";
int i,j;
for(i=0; i<smin.size(); i++){
str+=smin[i];
for(j=0; j<v.size(); j++){
if(v[j].find(str)==string::npos){
str=str.substr(0, str.length() - 1);
return str;
}
}
}
return str;
}
};
Expected results have been given as an example above.
What I got as an error message is -:
Runtime error: pointer index expression with base 0x000000000000 overflowed to 0xffffffffffffffff
I have looked into similar answer for this and tried to implement them but the error isn't going. Please can somebody help me with this.
You have an empty string in the vector. At some point you calculate length minus 1. Then use it for the end index substr.
In general, you need to learn to use a debugger, which will tell you exactly what line you got the error and what the variables look like on that line.

simple C++ program to calculate number of instances of a substring [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
can someone point out the error in the following code . I am using a naive approach of comparing both strings character by charcter and updating variable 'u' then comparing it with length of substring . If this is true then variable 'c' is updated by one unit.
Program in C++ :
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
char s[50],a[20];
cin.getline(s,50);
cin.getline(a,20);
//int l=strlen(s);
int p=strlen(a);
int i,c=0,j,u=0,k;
for(i=0;s[i]!='\0';i++)
{
if(a[i]='\0')
{break;}
if(s[i]==a[0])
{
for(j=i,k=0;a[k]!='\0';j++,k++)
{
if(s[j]==a[k])
{
u++;
//continue;
}
//else
//break;
}
//cout<<endl<<u;
if(u==p)
{
c++;
}
}
u=0;
}
cout<<endl<<"count "<<c;
getch();
}
For any kind of input combination , I am getting output as 0.
The problem is with this part:
if (a[i] = '\0')
{
break;
}
First, you are using = instead of ==, but that is not the entire problem. Either change a[i] to s[i], or comment out the entire block. I don't see why it is needed.
My tip and my coding convention to avoid your bug that you use = instead of == in:
if(a[i]='\0')
is to put the rvalue in the left side of the operand and the lvalue in the right side, like this:
if ('\0' == a[i])
this convention will avoid bugs like that(you will get a compilation error):
if ('\0' = a[i])
this code will generate a compilation error:
Error C2106 '=': left operand must be l-value

C++ - Store part of string in another string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
The problem is that in my code (which there is a loop getting alphabets of a string) it can not save the current string input into another variable:
Here is the code:
if(isalpha(Str[i])){
while (isalpha(Str[i])){
i++;
}
Str.erase( 0, i);
return 0;
}
I want to have another string (like temp ) to save each alphabet into the while loop. something like this:
if(isalpha(Str[i])){
string temp;
while (isalpha(Str[i])){
temp[i]=Str[i];
i++;
}
Str.erase( 0, i);
return 0;
}
can anyone help that what is the problem here?
As you declare temp as 0 length string, using temp[i] would be undefined behavior.
You may solve this problem by using
temp.push_back(Str[i]);
instead of
temp[i]=Str[i];
You're passing a position and count to std::string::erase. You can use the same parameters to construct another string with the characters that are about to be erased.
while (isalpha(Str[i])) {
i++;
}
string temp(Str, 0, i);
Str.erase(0, i);

intersection code that prints the intersection of two arrays ( posting lists ) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I wrote this code to print the intersection of two arrays ( posting lists) using dev c++
the problem that when I run the program nothing is printed
can you help ?
I need to know where is the problem
and what if I wanted to use cout instead of printf?
#include <iostream>
#include <stdio.h>
using namespace std;
// Intersecting two postings lists (a “merge” algorithm)
// and I will assume that the two posting listst are sorted Ascendingly
// I will suppose that the first posting list is an array wich
// have n elements I wil name it fistPost
// I will suppose that the second posting list is an array wich have
// m elements I will name it secondPost
int main()
{
int firstPost[] ={3,5,7,8,13,15,30,34};
int secondPost[]={1,5,7,9,11,15,20,34,35};
int i,j=0;
int n = sizeof(firstPost)/sizeof(firstPost[0]);
int m = sizeof(secondPost)/sizeof(secondPost[0]);
while(i<n && j<m)
{
if (firstPost[i]<secondPost[j])
i++;
else if (firstPost[i]>secondPost[j])
j++;
else if (firstPost[i]=secondPost[j])
{
printf ("%i", secondPost[j++]);
i++;
}
}
system("PAUSE");
return 0;
}
You haven't initialized 'i' to 0, hence its taking some garbage value and not executing the while loop.
change int i, j = 0;
to int i = 0, j = 0;
change this printf ("%i", secondPost[j++]);
to
printf ("%d", secondPost[j++]);