Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

Palindrome no. problem

Pawan Arora
Ranch Hand
Posts: 105

The above program trying to show wheather any character is palindrome or not by having an input at command prompt. But when I entered an input radar, it is showing me an outofbound Exception.

why and how can I get my desire result?

Henry Wong
author
Marshal
Posts: 21748
85
The above program trying to show wheather any character is palindrome or not by having an input at command prompt. But when I entered an input radar, it is showing me an outofbound Exception.

The stackstace for the out of bounds exception, not only tells you the exact method and line number where it is happening -- it also tells you the index as well. This way, you can tell if you overflowed or underflow.

But in your case, are you sure you actually want to deference the array? Shouldn't you be checking start? not e[start]?

Henry
[ December 16, 2008: Message edited by: Henry Wong ]

Pawan Arora
Ranch Hand
Posts: 105
Thanks Henery. Now I'm getting my desire result.

Martijn Verburg
author
Bartender
Posts: 3275
5
More of a common issue, moving to appropriate forum.

Rob Spoor
Sheriff
Posts: 20709
68
One remark on how to slightly improve your algorithm:

you only need to go half-way. After you have hit the half-way point you will compare the same elements again. For instance, the last comparison is that of e[e.length - 1] and e[0] - but you've already compared e[0] with e[e.length - 1].

So the check can become
Should e.length be odd, this will miss one element but that is one element that you would compare with itself.

Sunil Kumar
Ranch Hand
Posts: 76

Just a piece of advice, you don't need to traverse the whole array. As you are moving from both sides each traversing the halves from both end. Your loop should run half way only i.e round(e.length/2)+1, because anyways after length/2 it is going to compare the same elements
For example
it checks
R=R --> f=0,l=4
A=A --> f=1,l=3
D=D --> f=2,l=2
A=A --> f=3,l=1 ---> useless
R=R --> f=4,l=0 ---> useless

so you just need round(5/2)+1 = 3 iterations

Campbell Ritchie
Sheriff
Posts: 50729
83
Originally posted by Sunil Kumar:
so you just need round(5/2)+1 = 3 iterations

You don't need 5 / 2 + 1; you need 5 / 2. The middle element will probably not differ a lot from itself.

Sunil Kumar
Ranch Hand
Posts: 76
Ahh.. thanks for correcting that. I just missed it!!
You shouldn't have used the word "probably" . That was funny.

Campbell Ritchie
Sheriff
Posts: 50729
83
I was quite right to say "probably"; I then know whether you are awake