Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;; Answer to "Two Elisp Challenges", from http://irreal.org/blog/?p=808
- ;; 1. Given a list of integers from 1 to n but with one of the
- ;; integers missing, write an efficient algorithm for finding the
- ;; missing integer.
- ;; 2. Given a list of integers from 1 to n but with one of the
- ;; integers missing and another integer repeated, write an efficient
- ;; algorithm for finding the missing and repeated integers.
- (defun sum-until-n-minus-sum-l-plus-x (l x)
- "For a list l of size n, calculates 1+...+n minus the sum of all the numbers in l, and adds x it."
- (if l (sum-until-n-minus-sum-l-plus-x (cdr l) (+ (length l) (- (car l)) x)) x))
- (defun sum-squares-until-n-minus-sum-squares-l-plus-x (l x)
- "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."
- (if l (sum-squares-until-n-minus-sum-squares-l-plus-x (cdr l) (+ (expt (length l) 2) (- (expt (car l) 2)) x)) x))
- (defun find-missing (l)
- "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."
- (sum-until-n-minus-sum-l-plus-x l (+ (length l) 1)))
- (defun find-missing-and-repeated (l)
- "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)."
- (let* ((diff-sq (sum-squares-until-n-minus-sum-squares-l-plus-x l 0))
- (m-minus-r (sum-until-n-minus-sum-l-plus-x l 0))
- (m-plus-r (/ diff-sq r-minus-m)))
- (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