Guest User

Untitled

a guest
Mar 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. </head>
  8. <body>
  9. <script>
  10. /* Returns if a text is a palindrome */
  11. function isPalindrome(text) {
  12. let valid = true;
  13. // Iterate over half of the characters
  14. for (var i = 0; i < text.length / 2; i++) {
  15. if (text.charAt(i) !== text.charAt(text.length - i - 1)) valid = false;
  16. }
  17.  
  18. // Returns if its valid
  19. return valid;
  20. }
  21.  
  22. /* Returns the character code at the position */
  23. function getCharCode(text, pos) {
  24. return text.charCodeAt(pos) - 'a'.charCodeAt(0);
  25. }
  26.  
  27. /* Returns if a text is a permutation of a palindrome */
  28. function isPermutationofPalindrome(text) {
  29. const hash = new Array(26);
  30. // Goes over each character
  31. for (let i = 0; i < text.length; i++) {
  32. const charCode = getCharCode(text, i);
  33. hash[charCode] = (hash[charCode] || 0) + 1;
  34. }
  35. // Counts the number of characters that appear even times
  36. let evenCount = 0;
  37. for (let i = 0; i < hash.length; i++) {
  38. if (hash[i] % 2 === 1) evenCount += 1;
  39. }
  40. // It can be a palindrome if there is at most one even character
  41. return evenCount <= 1;
  42. }
  43.  
  44. // Test
  45. //const word = 'catac';
  46. const word = 'xyz';
  47. document.write(`${word}:<br/>`);
  48. document.write(`isPalindrome: ${isPalindrome(word)}<br/>`);
  49. document.write(`isPermutationofPalindrome: ${isPermutationofPalindrome(word)}<br/>`);
  50. </script>
  51.  
  52.  
  53. </body>
  54. </html>
Add Comment
Please, Sign In to add comment