Skip to content

Commit

Permalink
math: add simple fib function (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
gliga authored Jun 3, 2024
1 parent 091a80e commit b3805f3
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/lang/bool.sh
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,20 @@ function is_int() {
[ "${val}" = "${res}" ]
}

function is_uint() {
# True if the given value is an unsigned int (bc).
local ctx; is_ctx "${1}" && ctx="${1}" && shift
[ $# -ne 1 ] && { ctx_wn $ctx; return $EC; }
local -r val="${1}"
shift 1 || { ctx_wn $ctx; return $EC; }

! is_int "${val}" && return $FALSE

[[ "${val:0:1}" == "-" ]] && return $FALSE

return $TRUE
}

function is_float() {
# True if the given value can be a float (bc).
local ctx; is_ctx "${1}" && ctx="${1}" && shift
Expand Down
17 changes: 17 additions & 0 deletions src/lang/bool_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,23 @@ function test_is_int() {
}
readonly -f test_is_int

function test_is_uint() {
is_uint 10 || \
return $EC

is_uint abc && \
return $EC

is_uint 10.2 && \
return $EC

is_uint -10 && \
return $EC

return 0
}
readonly -f test_is_uint

function test_is_float() {
is_float 1.2 || \
return $EC
Expand Down
23 changes: 23 additions & 0 deletions src/util/math.sh
Original file line number Diff line number Diff line change
Expand Up @@ -289,3 +289,26 @@ function math_ceil() {
res=$(bc -l <<< "scale=0; ( ${val} + 1 ) / 1")
echo "${res}"
}

function math_fib() {
# Return fibonacci for the given `n`.
local ctx; is_ctx "${1}" && ctx="${1}" && shift
[ $# -ne 1 ] && { ctx_wn $ctx; return $EC; }
local n="${1}"
shift 1 || { ctx_wn $ctx; return $EC; }

[ -z "${n}" ] && { ctx_w $ctx "no n"; return $EC; }
! is_uint "${n}" && { ctx_w $ctx "not an int"; return $EC; }

local f0=0
local f1=1

local res=0
for (( i=1; i<${n}; i++ )); do
res=$(( ${f0} + ${f1} ))
f0=${f1}
f1=${res}
done

echo "${res}"
}
21 changes: 21 additions & 0 deletions src/util/math_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,24 @@ function test_math_ceil() {
assert_eq 0 $(math_ceil "-0.8")
}
readonly -f test_math_ceil

function test_math_fib() {
local res

res=$(math_fib 13)
[ "${res}" -ne 233 ] && \
assert_fail "13 incorrect"

res=$(math_fib 23)
[ "${res}" -ne 28657 ] && \
assert_fail "23 incorrect"

math_fib -10 && \
assert_fail "negative is not allowed"

math_fib "abc" && \
assert_fail "has to fail with non int"

return 0
}
readonly -f test_math_fib

0 comments on commit b3805f3

Please sign in to comment.