Showing posts with label palindrome. Show all posts
Showing posts with label palindrome. Show all posts

Javascript: Check if Input is Palindrome

Sep 4, 2014
I had a past post about how to check if input is palindrome in C#.

This one is another Javascript exercise with the same goal.

Instructions:
-create a function that determines the string input as palindrome
-use arrays and loops to check if the string is a palindrome (try reading .split and join function, DO NOT USE REVERSE FUNCTION in javascript)
-use text box to for string input
-use button to determine output
-insert text "is a palindrome" below the text box if string is a palindrome else "not a palindrome" --> use ternary operator for this


Here is my solution.

index.html

<!DOCTYPE html>
<html>
 <head>
  <script type="text/javascript" src="palindrome.js">
  </script>
 </head>
 <body>
  <input type="text" id="input_text"></input>
  <button onClick="isPalindrome()">Check</button>
  <br />
  <label id="output_text"></label>
 </body>
</html>


palindrome.js

function isPalindrome(){
 var inputString = document.getElementById("input_text").value.toLowerCase();
 var revString = [];
 
 inputString = inputString.replace(/[^a-zA-Z-]/g, ''); //removes all non-alphabet letters, including white space;
  
 for(var indx = inputString.length-1; indx >= 0; indx--){
  revString.push(inputString[indx]);
 }
 
 revString = revString.join('');
 
 document.getElementById("output_text").innerHTML = ""; //set to empty; to 'delete' any value already existing in the node;
 document.getElementById("output_text").innerHTML += (inputString === revString) ? "is a palindrome" : "not a palindrome";
 
}

FIDDLE

For clarifications and/or better solutions, please feel free to leave a message on the comments section.
Read more ...

C#: Check if Input is Palindrome

Mar 5, 2014
Here is one algorithm I find a challenge back on my student days.

* Check if string value entered by user is a palindrome or not.

/// <summary>
/// Checks if entered string value is a palindrome or not.
/// </summary>
/// <param name="p_word">Value entered by user</param>
/// <returns>If palindrome, returns true; otherwise, returns false</returns>
public bool IsPalindrome(string p_word)
{
 string revWord = string.Empty;
 char[] wordChar = p_word.ToCharArray();

 for (int index = p_word.Length - 1; index >= 0; index--)
 {
  revWord += wordChar[index];
 }

 if (revWord.Equals(p_word))
  return true;
 else
  return false;
}

If you have any better solution, please don't hesitate to share them on the comments section. (:

::EDIT::

Here's another solution by .NET GENE.

using System.Linq;

public bool IsPalindromeEnum(string p_word)
{
 string revWord = new string(p_word.Reverse().ToArray());

 if (revWord.Equals(p_word))
  return true;
 return false;
}

Thanks! :D

Read more ...