Skip to content

Commit

Permalink
Cleanup binary
Browse files Browse the repository at this point in the history
  • Loading branch information
BNAndras committed Jun 24, 2024
1 parent bc91986 commit 94bb25f
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 17 deletions.
6 changes: 1 addition & 5 deletions exercises/practice/binary/.meta/example.lfe
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,5 @@
(export (to-decimal 1)))

(defun to-decimal (string)
(try (element 2 (lists:foldr #'to-decimal/2 #(0 0) string))
(catch (_ 0))))
(list_to_integer string 2))

(defun to-decimal
([#\0 `#(,n ,acc)] `#(,(+ n 1) ,acc))
([#\1 `#(,n ,acc)] `#(,(+ n 1) ,(+ acc (trunc (math:pow 2 n))))))
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
%% -*- erlang -*-
{application, 'binary',
{application, 'binary-string',
[{description, ""},
{vsn, "0.0.1"},
{modules,
['binary']},
['binary-string']},
{registered, []},
{applications,
[kernel, stdlib]},
Expand Down
5 changes: 5 additions & 0 deletions exercises/practice/binary/src/binary-string.lfe
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
(defmodule binary-string
(export (to-decimal 1)))

; please implement the to-decimal function

26 changes: 16 additions & 10 deletions exercises/practice/binary/test/binary-string-tests.lfe
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,27 @@

(include-lib "ltest/include/ltest-macros.lfe")

(deftest one (check "1"))
(deftest binary-0-is-decimal-0
(is-equal 0 (binary-string:to-decimal "0")))

(deftest two (check "10"))
(deftest binary-1-is-decimal-1
(is-equal 1 (binary-string:to-decimal "1")))

(deftest three (check "11"))
(deftest binary-10-is-decimal-2
(is-equal 2 (binary-string:to-decimal "10")))

(deftest four (check "100"))
(deftest binary-11-is-decimal-3
(is-equal 3 (binary-string:to-decimal "11")))

(deftest nine (check "1001"))
(deftest binary-100-is-decimal-4
(is-equal 4 (binary-string:to-decimal "100")))

(deftest twenty-six (check "11010"))
(deftest binary-1001-is-decimal-9
(is-equal 9 (binary-string:to-decimal "1001")))

(deftest large (check "10001101000"))
(deftest binary-11010-is-decimal-26
(is-equal 26 (binary-string:to-decimal "11010")))

(deftest carrot (is-equal 0 (binary-string:to-decimal "carrot")))
(deftest binary-10001101000-is-decimal-1128
(is-equal 1128 (binary-string:to-decimal "10001101000")))

(defun check (string)
(is-equal (list_to_integer string 2) (binary-string:to-decimal string)))

0 comments on commit 94bb25f

Please sign in to comment.