Skip to content

Instantly share code, notes, and snippets.

@fuzzyalej
Created April 17, 2014 16:05
Show Gist options
  • Save fuzzyalej/10994631 to your computer and use it in GitHub Desktop.
Save fuzzyalej/10994631 to your computer and use it in GitHub Desktop.
Histogram exercise to learn arrays. Example from "Common Lisp: A gentle introduction to symbolic computation"
(defvar *total-points* nil)
(defvar *hist-array* nil)
(defun record-value (n)
(if (or (> n 10)
(< n 0))
(break "The supplied argument is not between 0 and 10"))
(setf (aref *hist-array* n) (+ 1 (aref *hist-array* n)))
(setf *total-points* (+ 1 *total-points*)))
(defun print-hist-line (n)
(if (or (> n 10)
(< n 0))
(break "The supplied argument is not between 0 and 10"))
(let ((value (aref *hist-array* n)))
(format t "~%~2S[~3S]" n value)
(dotimes (i value)
(format t "*"))))
(defun print-histogram ()
(dotimes (i 11)
(print-hist-line i)))
(defun new-histogram (&optional (times 200))
(setf *total-points* 0)
(setf *hist-array* (make-array 11 :initial-element 0))
(format t "~&Testing how well (RANDOM) works!")
(dotimes (i times)
(record-value (random 11)))
(print-histogram)
(format t "~%~%Total: ~S" times))
(new-histogram)
;;Example output
;; Testing how well (RANDOM) works!
;; 0 [20 ]********************
;; 1 [19 ]*******************
;; 2 [18 ]******************
;; 3 [19 ]*******************
;; 4 [20 ]********************
;; 5 [10 ]**********
;; 6 [14 ]**************
;; 7 [17 ]*****************
;; 8 [25 ]*************************
;; 9 [17 ]*****************
;; 10[21 ]*********************
;;
;; Total: 200
@svetlyak40wt
Copy link

Thanks for the idea. I've made a more generic function:

https://gist.github.com/svetlyak40wt/57739e2238485a83a9d7e01dbcda09dd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment