Skip to content

Commit

Permalink
Merge pull request #120 from verdammelt/binary-update
Browse files Browse the repository at this point in the history
Adding more test cases to improve binary exercise.
  • Loading branch information
verdammelt authored Jul 29, 2016
2 parents 39e7d91 + 7eed904 commit eae5417
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 29 deletions.
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))))

0 comments on commit eae5417

Please sign in to comment.