Skip to content

Instantly share code, notes, and snippets.

@svetlyak40wt
Created June 5, 2017 08:50
Show Gist options
  • Save svetlyak40wt/57739e2238485a83a9d7e01dbcda09dd to your computer and use it in GitHub Desktop.
Save svetlyak40wt/57739e2238485a83a9d7e01dbcda09dd to your computer and use it in GitHub Desktop.
A module to print ASCII histogram.
(defpackage #:histogram
(:use #:cl)
(:export
#:print-histogram))
(in-package histogram)
(defun min-value (values)
"Ищет минимальное по любому количеству элементов."
(loop for value in values
minimizing value))
(defun max-value (values)
"Ищет максимальное по любому количеству элементов."
(loop for value in values
maximizing value))
(defun print-histogram (data &key
(step 0.1)
(width 40) ;; number of symbols in a chart for the largest bucket
min-value
max-value)
(let* ((min-value (or min-value
(min-value (coerce data 'list))))
(max-value (or max-value
(max-value (coerce data 'list))))
(num-backets (max 1
(ceiling (/ (- max-value min-value)
step))))
(buckets (make-array num-backets :initial-element 0)))
(flet ((add-value-to-the-bucket (value)
"Finds a bucket for the value and increments it's counter."
(let ((index (floor (/ (- value min-value)
step))))
(incf (aref buckets index))))
(make-bar (number width label)
"Prints a line filled with = symbol with the label at the end."
(format t "~4f: ~a ~a~%"
number
(coerce (make-array width :initial-element #\=)
'string)
label)))
;; Now add all data points to their buckets
(mapc #'add-value-to-the-bucket
(coerce data 'list))
;; And print bucket values as a ASCII chart
(let ((max-bucket-size
(apply #'max (coerce buckets 'list))))
(loop for value across buckets
for number from min-value to max-value by step
do (make-bar number
(floor (* (/ value max-bucket-size)
width))
value))))))
@kqr
Copy link

kqr commented Jul 25, 2019

Suggestion:

(defun min-value (values)
  (apply #'min values))

(defun max-value (values)
  (apply #'max values))

You even use this elsewhere in the code!

@svetlyak40wt
Copy link
Author

svetlyak40wt commented Jul 27, 2019 via email

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