Advertisement
Guest User

numbers.el

a guest
May 2nd, 2012
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 1.02 KB | None | 0 0
  1. (require 'cl)
  2.  
  3. (defun find-missing (source)
  4.   "Given a function, SOURCE, that returns a series of numbers
  5. between 1 and n, missing one number and terminating by returning
  6. nil, return the missing number. Runs in O(n) time and O(1) space,
  7. provided you staty within the integer limits of your
  8. platform (n=95533 on 32-bit)."
  9.   (let ((sum 0)
  10.         (max 1)
  11.         (x 0))
  12.     (while (setf x (funcall source))
  13.       (incf sum x)
  14.       (setf max (max max x)))
  15.     (- (/ (* max (1+ max)) 2) sum)))
  16.  
  17. (defun sample-source (n)
  18.   "Creates a number source function which outputs all of the
  19. numbers from 1 to N in random order, then emits nil."
  20.   (lexical-let ((list (number-sequence 1 n)))
  21.     ;; Shuffle
  22.     (setf list (map 'list 'identity
  23.                     (shuffle-vector (apply 'vector list))))
  24.     (lambda ()
  25.       (let ((ret (car list)))
  26.         (setf list (cdr list))
  27.         ret))))
  28.  
  29. ;;; Example Usage
  30.  
  31. (setq source (sample-source 95533))
  32. (funcall source) ;; Remove one number and see what it is
  33. (find-missing source)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement