lambdabot

scalar-product

Feb 22nd, 2016
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 1.68 KB | None | 0 0
  1. ;; Enter your code here. Read input from STDIN. Print output to STDOUT
  2. ;;; (pgroup '(1 2 3 4)) => ((1 2) (3 4))
  3. (defun pgroup (s)
  4.   "Do pairs of elements of a given list."
  5.   (cond ((null s) s)
  6.     ((null (cdr s)) s)
  7.     (t (cons (list (car s) (cadr s))
  8.          (pgroup (cddr s))))))
  9.  
  10. ;;; (gen 5 0 '(4 0)) => ((4 3) (2 0) (2 2))
  11. (defun gen (n i s &optional (m 5))
  12.   "Gen algorirthm from hackerrank."
  13.   (cond ((> i n) (pgroup (cddr (reverse s))))
  14.     (t (gen n (1+ i) (cons (mod (+ (car s) (cadr s)) m) s)))))
  15.  
  16. ;;; (dot-product '(4) '(5)) => 20
  17. (defun dot-product (a b)
  18.   "Compute the mathematical dot product of two vectors."
  19.   (apply #'+ (mapcar #'* a b)))
  20.  
  21. (defparameter *ps* '())
  22.  
  23. ;;; (comb 2 '(1 2 3) #'print) =>
  24. ;;; (3 2)
  25. ;;; (3 1)
  26. ;;; (2 1)
  27. (defun comb (m list fn)
  28.   "Find all possible combinations of a given list."
  29.   (labels ((comb1 (l c m)
  30.          (when (>= (length l) m)
  31.            (if (zerop m) (return-from comb1 (funcall fn c)))
  32.            (comb1 (cdr l) c m)
  33.            (comb1 (cdr l) (cons (first l) c) (1- m)))))
  34.     (comb1 list nil m)))
  35.  
  36. ;;; (explanation '(4 0) 5 3) => (8 14 4)
  37. (defun explanation (c m n)
  38.   "Explanation algorithm from hackerrank."
  39.   (setf *ps* '())
  40.   (comb 2 (gen (+ 2 n) 0 c m)
  41.     (lambda (s) (push (dot-product (car s) (cadr s)) *ps*))))
  42.  
  43. ;;; (diff (loop :for x in *ps* :collect (mod x 5)) => (3 4)
  44. (defun diff (s)
  45.   "Remove duplicated atoms of a list."
  46.   (cond ((null s) s)
  47.     ((member (car s) (cdr s))
  48.      (diff (cdr s)))
  49.     (t (cons (car s) (diff (cdr s))))))
  50.  
  51. ;;; hackerrank I/O
  52. (setq *ps* (explanation (list (read) 0) (read) (read)))
  53.  
  54. (format t "~a" (length (diff (loop :for x in *ps* :collect (mod x (third *ps*))))))
Advertisement
Add Comment
Please, Sign In to add comment