Two Palindrome Exercises
October 6, 2017
Many of the people who read my blog are programming students. It is October, about the middle of the Fall Semester at many universities, and my student readers need exercises to cement their understanding of their studies. Here are two exercises about palindromes.
- A number like 123454321 is palindromic; it decimal digits are the same left-to-right as they are right-to-left. Write a program that determines if a given input number is palindromic.
- Given a list of strings, for instance {“a” “bcd” “ef” “g” “f” “ed” “c” “ba”}, write a program to determine if the individual letters of the strings form a palindrome. Note that the letters might be distributed into the individual words differently when read in opposite directions.
Your task is to write two programs that recognize palindromes. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
We can avoid separate calls to
quotient
andremainder
by usingfloor/
which returns both.With SRFI 13, we can eliminate converting strings to lists and back, and just say:
That said, the successors of SRFI 13 do not support string-reverse, because it is only useful in artificial examples like these. In a Unicode world, “Hägar the Horrible”, when expressed in decomposed form (as here). reverses not to “elbirroH eht ragäH” but to “elibrroH eht rag̈aH”, with the umlaut on the “g” rather than the first “a”.
A Haskell version.
(defun palindromic-p (str)
(equal (string-reverse str) str))
(defun palindromic-integer-p (n)
(palindromic-p (int-to-string n)))
(defun palindromic-list-p (list)
(palindromic-p (apply #’concat list)))
;; (palindromic-integer-p 123454321)
;; t
;; (palindromic-integer-p 1234544321)
;; nil
;; (palindromic-list-p ‘(“a” “bcd” “ef” “g” “f” “ed” “c” “ba”))
;; t
;; (palindromic-list-p ‘(“a” “bcd” “ef” “xg” “f” “ed” “c” “ba”))
;; nil