Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 132,121 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,975 people online right now. Registration is fast and FREE... Join Now!




Palindrome using recursion

2 Pages V  1 2 >  
Reply to this topicStart new topic

Palindrome using recursion, I need help with my program for a palindrome

Rating  3
guyanesedee918
post 6 Oct, 2008 - 09:27 AM
Post #1


New D.I.C Head

*
Joined: 6 Oct, 2008
Posts: 1

I have written this code and it is supposed to tell us if the string entered is a palindrome. it must be done using recursion and it needs to use a string reverse function and it hasto be written in .c I dont know where i am going wrong with this.


CODE
#include <stdio.h>
#include <string.h>

void string_reverse(char* str, int first, int last);
void palindrome(char* str, char newstring, int first, int last);

int main (void)
{
    char str[1024];
    char newstring[1024];
    char answer [5];
    
    
    printf("Palindrome Checker\n");
    // Read a string from the user
    
do
{      
    printf("Enter a string\n");
    scanf("%s", str);
    
    //check if it is palidrome by if the reverse equal the entered one
    string_reverse(str, 0, strlen(str)-1);
    printf("Result: %s\n", str);
    scanf("%s", newstring);
    
    void palindrome(char* str, char newstring, int first, int last);
        
    printf("Another? (y/n)\n");
    scanf("%s", &answer);
    }while(answer =='y'|| answer =='Y');
    
    
    system("PAUSE");
    return 0;
}

void string_reverse(char* str, int first, int last)
{
     char temp;
    
     // base case
      if(first >= last)
      return;
    
     //recursive case
     temp = str[first];
     str[first] = str[last];
     str[last] = temp;
    
     string_reverse(str, first +1, last -1);
    
}

void palindrome(char* str, char newstring, int first, int last)
{
     //base case
     if(strlen <=1)
     printf("The string you entered was a palindrome\n");
     //base case
     if(first == last && str[first]+1 != str[last]-1);
     printf("The string you entered was a palindrome\n");
     return;
    
     //recursive
     if(first != last && str[first]+1 != str[last]-1)
     printf("The string you entered was not a palindrome\n");
}

User is offlineProfile CardPM

Go to the top of the page

Amadeus
post 6 Oct, 2008 - 10:17 AM
Post #2


g++ -o drink whiskey.cpp

Group Icon
Joined: 12 Jul, 2002
Posts: 12,169



Thanked 33 times

Dream Kudos: 25
My Contributions


Are you getting errors? If so, can you please post them? Are you getting undesired behaviour? If so, can you describe it?
User is online!Profile CardPM

Go to the top of the page

gabehabe
post 6 Oct, 2008 - 01:25 PM
Post #3


Working Girl.

Group Icon
Joined: 6 Feb, 2008
Posts: 5,402



Thanked 94 times

Dream Kudos: 2625

Expert In: Dingleberries

My Contributions


I just answered this question here

Do you know each other? smile.gif
User is offlineProfile CardPM

Go to the top of the page

baavgai
post 6 Oct, 2008 - 06:25 PM
Post #4


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,957



Thanked 95 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


Well, since Gabe offered the C++ version...

There's no need for reverse string, you just need to burn the candle at both ends. Here's one possible solution:
cpp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int isPalindrome(char* str, int end) {
if (end<1) { return 1; } // we've passed center, it's true
if (str[0] != str[end]) { return 0; } // character doesn't match, it fails
// note, we move the front one, the end one
// then the end another one, to allow for the front movement
return isPalindrome(str+1, end-2);
}

void checkPalindrome(char* str) {
printf("'%s' is ", str);
if(!isPalindrome(str, strlen(str)-1)) { printf("not "); }
printf("a palindrome\n");
}

int main() {
checkPalindrome("space cats");
checkPalindrome("star rats");
}


Hope this helps.
User is online!Profile CardPM

Go to the top of the page

gabehabe
post 7 Oct, 2008 - 02:33 AM
Post #5


Working Girl.

Group Icon
Joined: 6 Feb, 2008
Posts: 5,402



Thanked 94 times

Dream Kudos: 2625

Expert In: Dingleberries

My Contributions


OK, time to show off. cool.gif
I know ternary can get ugly and hard to read, but I love it~ it's challenging.

Here is a one line method to check if a string is a palindrome.
cpp
bool recursivePalindrome(std::string str, unsigned int index = 0) {
return (str[index] == str[str.length()-index-1] ? recursivePalindrome(str, ++index) : index > (str.length()/2) ? true : false);
}

It's a long line.

Enjoy! tongue.gif

EDIT:
Oh yeah, it's in C++ and you wanted C. DAMN!

Meh~
User is offlineProfile CardPM

Go to the top of the page

baavgai
post 7 Oct, 2008 - 04:35 AM
Post #6


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,957



Thanked 95 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


QUOTE(gabehabe @ 7 Oct, 2008 - 06:33 AM) *

OK, time to show off. cool.gif

It's still C++, rather than the poster's C. Worse, it's still calling the string length function every single time; a waste of effort. The division by 2 is also unnecessary.

Sorry, you kind of asked for it. decap.gif
User is online!Profile CardPM

Go to the top of the page

gabehabe
post 7 Oct, 2008 - 04:42 AM
Post #7


Working Girl.

Group Icon
Joined: 6 Feb, 2008
Posts: 5,402



Thanked 94 times

Dream Kudos: 2625

Expert In: Dingleberries

My Contributions


But the length()/2 is used to exit half way along the string, as opposed to going through the whole thing~ it saves going through the entire string, which improves the speed of the end result, right?

And I edited my post, I realised it was C++ when the OP was looking for C.

I see what you mean about calling the length() method each time though. I never thought of that when I was writing it~ sleep.gif
User is offlineProfile CardPM

Go to the top of the page

gabehabe
post 7 Oct, 2008 - 04:58 AM
Post #8


Working Girl.

Group Icon
Joined: 6 Feb, 2008
Posts: 5,402



Thanked 94 times

Dream Kudos: 2625

Expert In: Dingleberries

My Contributions


OK baavgai, it's time to compare.
I just rewrote it, and timed both. The first took 115 milliseconds.

The new version actually says 0

cpp
bool recursivePalindrome(std::string str, unsigned int index = 0, unsigned int len = 0) {
if (len == 0) len = str.length();
return (str[index] == str[len-index-1] ? recursivePalindrome(str, ++index) : index > (len/2) ? true : false);
}

However, it's now 2 lines long. tongue.gif

Dammit. Yours actually said 0 for the time in milliseconds, too... sleep.gif

It's a draw.

EDIT:
Still, I managed to dramatically improve the performance of mine tongue.gif
User is offlineProfile CardPM

Go to the top of the page

baavgai
post 7 Oct, 2008 - 08:21 AM
Post #9


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,957



Thanked 95 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


QUOTE(gabehabe @ 7 Oct, 2008 - 08:58 AM) *

OK baavgai, it's time to compare.


Oh, so you want to play speed tests? I love this game. Unfortunately, I probably need a slower computer for this.

Here's my test code:
cpp

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;


bool recursivePalindrome(std::string str, unsigned int index = 0, unsigned int len = 0) {
if (len == 0) len = str.length();
return (str[index] == str[len-index-1] ? recursivePalindrome(str, ++index) : index > (len/2) ? true : false);
}

int isPalindrome(char* str, int end) {
if (end<1) { return 1; } // we've passed center, it's true
if (str[0] != str[end]) { return 0; }
return isPalindrome(str+1, end-2);
}

void makeRandPalandrome(char *buffer, int size) {
char *head = buffer;
char *tail = head + (size-2);
int mid = (size-1)/2;

buffer[size-1] = 0;
while(mid-- >= 0) { *head++ = *tail-- = 'A' + (rand() % 26); }
}

void test(unsigned long size) {
unsigned long start, elapsed;
cout << "Testing for: " << size << endl;
char *pal = new char[size];
makeRandPalandrome(pal, size);
string strPal(pal);

start = clock();
cout << isPalindrome(pal, strlen(pal)-1) << endl;
elapsed = clock()-start;
cout << elapsed << " millisecs for isPalindrome." << endl;

start = clock();
cout << recursivePalindrome(strPal) << endl;
elapsed = clock()-start;
cout << elapsed << " millisecs for recursivePalindrome." << endl;

cout << endl << endl;

delete pal;
}


int main () {
srand ( time(NULL) );

for(unsigned long i=0; i<10; i++) {
test(10000 + (i*1000));
}

return EXIT_SUCCESS;
}


The results:
CODE

Testing for: 10000
1
0 millisecs for isPalindrome.
1
300000 millisecs for recursivePalindrome.


Testing for: 11000
1
0 millisecs for isPalindrome.
1
330000 millisecs for recursivePalindrome.


Testing for: 12000
1
0 millisecs for isPalindrome.
1
380000 millisecs for recursivePalindrome.


Testing for: 13000
1
0 millisecs for isPalindrome.
1
430000 millisecs for recursivePalindrome.


Testing for: 14000
1
0 millisecs for isPalindrome.
1
510000 millisecs for recursivePalindrome.


Testing for: 15000
1
0 millisecs for isPalindrome.
1
570000 millisecs for recursivePalindrome.


Testing for: 16000
1
0 millisecs for isPalindrome.
1
630000 millisecs for recursivePalindrome.


Testing for: 17000
1
0 millisecs for isPalindrome.
1
720000 millisecs for recursivePalindrome.


Testing for: 18000
1
0 millisecs for isPalindrome.
1
820000 millisecs for recursivePalindrome.


Testing for: 19000
1
0 millisecs for isPalindrome.
1
880000 millisecs for recursivePalindrome.


It should be noted that the original test was more optimistic, but the string didn't want to deal:
CODE

Testing for: 10000
1
0 millisecs for isPalindrome.
1
290000 millisecs for recursivePalindrome.


Testing for: 100000
1
0 millisecs for isPalindrome.
terminate called after throwing an instance of 'std::bad_alloc'
  what():  St9bad_alloc
/home/bam/.netbeans/6.1/bin/dorun.sh: line 103: 12413 Aborted                 "$pgm" "$@"



Curious, I took the std::string one out and just tested mine. I got this far before I blew the heap:
CODE

Testing for: 1000000
1
20000 millisecs for isPalindrome.


User is online!Profile CardPM

Go to the top of the page

gabehabe
post 7 Oct, 2008 - 08:38 AM
Post #10


Working Girl.

Group Icon
Joined: 6 Feb, 2008
Posts: 5,402



Thanked 94 times

Dream Kudos: 2625

Expert In: Dingleberries

My Contributions


...

Show off. sleep.gif
User is offlineProfile CardPM

Go to the top of the page

baavgai
post 7 Oct, 2008 - 08:49 AM
Post #11


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,957



Thanked 95 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


LOL. I don't ever whack the mole unless it sticks it head out and asks for it. splat.gif

I must admit, it results were far worse than I expected... Duh, you have a bug.

Tried this instead, results are now even:
cpp

bool recursivePalindrome(std::string &str, unsigned int index = 0, unsigned int len = 0) {
if (len == 0) len = str.length();
return (str[index] == str[len-index-1] ? recursivePalindrome(str, ++index) : index > (len/2) ? true : false);
}

User is online!Profile CardPM

Go to the top of the page

gabehabe
post 7 Oct, 2008 - 09:35 AM
Post #12


Working Girl.

Group Icon
Joined: 6 Feb, 2008
Posts: 5,402



Thanked 94 times

Dream Kudos: 2625

Expert In: Dingleberries

My Contributions


In any sense, I'm quite proud that I managed to write that~ I like recursion, and I like ternary. Both can be quite challenging. smile.gif

In addition, I've just posted my 2 methods (and yours, crediting you) in a recursion discussion/tutorial I just posted, here.

@OP:
You might benefit from taking a look at that. smile.gif
User is offlineProfile CardPM

Go to the top of the page

2 Pages V  1 2 >
Reply to this topicStart new topic
Time is now: 11/21/08 11:03AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month