Advertisement
alfaro-murillo

FInd missing and repeated number

May 4th, 2012
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 1.86 KB | None | 0 0
  1. ;; Answer to "Two Elisp Challenges", from http://irreal.org/blog/?p=808
  2.  
  3. ;; 1. Given a list of integers from 1 to n but with one of the
  4. ;; integers missing, write an efficient algorithm for finding the
  5. ;; missing integer.
  6.  
  7.  
  8. ;; 2. Given a list of integers from 1 to n but with one of the
  9. ;; integers missing and another integer repeated, write an efficient
  10. ;; algorithm for finding the missing and repeated integers.
  11.  
  12.  
  13. (defun sum-until-n-minus-sum-l-plus-x (l x)
  14.   "For a list l of size n, calculates 1+...+n minus the sum of all the numbers in l, and adds x it."
  15.   (if l (sum-until-n-minus-sum-l-plus-x (cdr l) (+ (length l) (- (car l)) x)) x))
  16.  
  17.  
  18. (defun sum-squares-until-n-minus-sum-squares-l-plus-x (l x)
  19.   "For a list l of size n, calculates 1^2+...+n^2 minus the sum of the squares of all the numbers in l, and adds x to it."
  20.   (if l (sum-squares-until-n-minus-sum-squares-l-plus-x (cdr l) (+ (expt (length l) 2) (- (expt (car l) 2)) x)) x))
  21.  
  22. (defun find-missing (l)
  23.   "For a list l containing all the numbers 1,...,n except one with non of them repeated, returns the missing one. It is based on the fact that if S is the sum of the elements in the list l, then 1+...+n-S is the number missing in l."
  24.   (sum-until-n-minus-sum-l-plus-x l (+ (length l) 1)))
  25.  
  26. (defun find-missing-and-repeated (l)
  27.   "For a list l containing all the numbers 1,...,n except one with only one of them repeated, returns a list (m r) with two elements the missing one m and the repeated one r. It is based on the fact that if S is the sum of the elements in the list l and SS is the sum of the squares, then 1+...+n -S=m-r and 1^2+...+n^2-SS=r^2-m^2=(m-r)*(m-r)."
  28.   (let* ((diff-sq (sum-squares-until-n-minus-sum-squares-l-plus-x l 0))
  29.      (m-minus-r (sum-until-n-minus-sum-l-plus-x l 0))
  30.      (m-plus-r (/ diff-sq r-minus-m)))
  31.     (list (/ (+ m-plus-r m-minus-r) 2) (/ (- m-plus-r m-minus-r) 2))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement