Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding more test cases to improve binary exercise. #120

Merged
merged 1 commit into from
Jul 29, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions exercises/binary/binary-test.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@
(define-test invalid-binary-is-decimal-0
(assert-equal 0 (binary:to-decimal "carrot")))

(define-test invalid-characters-at-beginning
(assert-equal 2 (binary:to-decimal "a10")))

(define-test invalid-characters-at-end
(assert-equal 2 (binary:to-decimal "10a")))

(define-test invalid-characters-in-middle
(assert-equal 2 (binary:to-decimal "1a0")))

(define-test invalid-digits
(assert-equal 0 (binary:to-decimal "23")))

#-xlisp-test
(let ((*print-errors* t)
(*print-failures* t))
Expand Down
32 changes: 3 additions & 29 deletions exercises/binary/example.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,7 @@

(in-package #:binary)

;; (defun to-decimal (string)
;; (or (parse-integer string :radix 2 :junk-allowed t)
;; 0))

;; (defun to-decimal (string)
;; (flet ((parse-digit (digit) (if (and digit (char= digit #\1)) 1 0)))
;; (do* ((digits (reverse (coerce string 'list)) (rest digits))
;; (digit (parse-digit (car digits))
;; (parse-digit (car digits)))
;; (index 0 (incf index))
;; (value (* digit
;; (expt 2 index))
;; (+ value (* digit
;; (expt 2 index)))))
;; ((null digits) value))))

;; (defun to-decimal (string)
;; (flet ((parse-digit (digit) (or (digit-char-p digit 2) 0)))
;; (do* ((index 0 (incf index))
;; (revstr (reverse string))
;; (digit (parse-digit (char revstr index))
;; (parse-digit (char revstr index)))
;; (value digit (+ value (* digit (expt 2 index)))))
;; ((= (1+ index) (length string)) value))))

(defun to-decimal (string)
(loop with revstr = (reverse string)
for idx below (length string) and c across revstr
for digit = (or (digit-char-p c 2) 0)
summing (* digit (expt 2 idx))))
(loop with digits = (remove-if #'null (map 'list #'(lambda (c) (digit-char-p c 2)) string))
for idx below (length digits) and digit in (reverse digits)
summing (* digit (expt 2 idx))))