Solution to Gem Stones Problem Using Lisp


The problem:

John has discovered various rocks. Each rock is composed of various elements, and each element is represented by a lowercase latin letter from ‘a’ to ‘z’. An element can be present multiple times in a rock. An element is called a ‘gem-element’ if it occurs at least once in each of the rocks.

Given the list of N rocks with their compositions, display the number of gem-elements that exist in those rocks.

Input Format
The first line consists of N, the number of rocks.
Each of the next N lines contain rocks’ composition. Each composition consists of lowercase letters of English alphabet.

Output Format
Print the number of gem-elements that are common in these rocks. If there are none, print 0.

My Solution in Common Lisp

(defun processString (line position)
  (if (< position (length line))
    (progn
      (setf (nth (- (char-code (char line position)) 97) gemArray) (+ (nth (- (char-code (char line position)) 97) gemArray) 1))
      (processString line (+ position 1))
    )))

(defun outputResult (position n)
  (if (< position 26)
    (if (eql (nth position gemArray) n)
      (+ 1 (outputResult (+ position 1) n))
      (outputResult (+ position 1) n))
    0))

(defun main (iteration n)
  (if (> iteration 0)
    (progn
      (setq line (read-line))
      (processString (remove-duplicates line) 0)
      (main (- iteration 1) n))
    (outputResult 0 n)
  ))

(setq gemArray '(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
(setq line (read-line))
(setq tests (parse-integer line))

(format t "~d" (main tests tests))

Leave a Reply

Your email address will not be published. Required fields are marked *