Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical error while creating Palindrome Program

Tags:

c#

I tried to make Palindrome program as small as possible. However, this program is giving logical error. When I enter palindrome string it gives "False" as result which is opposite of what is expected.

char[] phrase;
Console.WriteLine((phrase = Console.ReadLine().ToArray())==phrase.Reverse().ToArray());
Console.ReadLine();

I do not want to increase number of statements of this program.

like image 621
mssaggoo.blogspot.in Avatar asked Apr 23 '26 20:04

mssaggoo.blogspot.in


2 Answers

In .NET, arrays do not have an overloaded equality operator. Use Enumerable.SequenceEquals.

Reading your code more thoroughly, you are making things more complicated than necessary.

    string phrase = Console.ReadLine();
    var reversedPhrase = phrase.Reverse(); //Type is IEnumerable<char>
    Console.WriteLine(phrase.SequenceEquals(reversedPhrase));

I recommend that you don't burry side-effects inside of expressions in the way you did. That code could well have been a test question to see if a student can work it out.

like image 70
usr Avatar answered Apr 26 '26 11:04

usr


If you want to do it by array then you can try this

char[] phrase;
Console.WriteLine(phrase = Console.ReadLine().ToArray().SequenceEqual(phrase.Reverse().ToArray()));
Console.ReadLine();

just like usr said use sequenceequal

like image 28
Sid M Avatar answered Apr 26 '26 10:04

Sid M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!