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.

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

Sample Input

3
abc
abcba
abcd

Sample Output

2
0
4
———

C Solution

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

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

  for(i=0;i<len/2;i++){
    if(buffer[i]!=buffer[len-1-i]){
      dif = buffer[i] - buffer[len-1-i];
      if(dif<0)
        dif*=-1;
      count += dif;  
    }
  }

  return count;
}

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

  scanf("%d", &cases);

  for(k=0;k<cases;k++){
    scanf("%s",buffer);
    if(k>0)
      printf("\n");
    printf("%d",solve(buffer));    
  }

  return 0;
}

Lisp Solution

(defun cost (line position)
  (if (eql (char line position) (char line (- (length line) 1 position)))
    0    
    (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)
    (progn
      (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
    1111111111
    25114
    3333333333
    sample output
    89
    6
    1
    find no of cases its mean words where no are string
    logic developpment

    Reply

Leave a Reply

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