C vs. Lisp Program Example

I was curious to see how a program to solve the same problem would look like in C and in Lisp. I went ahead and solved the problem below in both languages, using a very similar approach. Take your own conclusions!

James got hold of a love letter that his friend Harry has written for his girlfriend. Being the prankster that James is, he decides to meddle with it. He changes all the words in the letter into palindromes.

While modifying the letters of the word, he follows 2 rules:

(a) He always reduces the value of a letter, e.g. he changes ‘d’ to ‘c’, but he does not change ‘c’ to ‘d’.
(b) If he has to repeatedly reduce the value of a letter, he can do it until the letter becomes ‘a’. Once a letter has been changed to ‘a’, it can no longer be changed.

Each reduction in the value of any letter is counted as a single operation. Find the minimum number of operations he carries out to convert a given string into a palindrome.

Input Format
The first line contains an integer T, i.e., the number of test cases.
The next T lines will contain a string each.

Output Format
A single line containing the number of minimum operations corresponding to each test case.

1 ≤ T ≤ 10
1 ≤ length of string ≤ 104
All characters are lower cased english letters.

Sample Input


Sample Output


C Solution

#include <stdio.h>
#include <string.h>

int solve(char buffer[]){
  int count = 0;
  int i;
  int len = strlen(buffer);
  int dif;  

      dif = buffer[i] - buffer[len-1-i];
      count += dif;  

  return count;

int main(){
  int cases,k;
  char buffer[10001];

  scanf("%d", &cases);


  return 0;

Lisp Solution

(defun cost (line position)
  (if (eql (char line position) (char line (- (length line) 1 position)))
    (abs (- (char-code (char line position)) (char-code (char line (- (length line) 1 position)))))

(defun calculate (line position) 
  (if (= position (truncate (/ (length line) 2))) 0
    (+ (cost line position) (calculate line (+ position 1)))

(defun main (iteration) 
  (if (> iteration 0)
      (setq line (read-line))
      (format t "~d" (calculate line 0))
      (if (> iteration 1) (format t "~%"))
      (main (- iteration 1)))

(setq line (read-line))
(setq tests (parse-integer line))

(main tests)

One thought on “C vs. Lisp Program Example

  1. rajdeep

    i didnt known how to solve this inc++
    sample input
    sample output
    find no of cases its mean words where no are string
    logic developpment


Leave a Reply to rajdeep Cancel reply

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