Skip to content

Commit

Permalink
Simpler error return value for collatz-conjecture
Browse files Browse the repository at this point in the history
  • Loading branch information
gvrooyen committed Sep 4, 2024
1 parent 03c05ff commit 47bc81e
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 22 deletions.
Original file line number Diff line number Diff line change
@@ -1,20 +1,15 @@
package collatz_conjecture

Error :: enum {
None,
IllegalArgument,
}

steps :: proc(start: int) -> (int, Error) {
if (start <= 0) do return 0, .IllegalArgument
steps :: proc(start: int) -> (result: int, ok: bool) {
if (start <= 0) do return 0, false

n := start
result := 0
result = 0

for n > 1 {
n = n / 2 if n % 2 == 0 else 3 * n + 1
result += 1
}

return result, .None
return result, true
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package collatz_conjecture

Error :: enum {} // Please inspect the tests to see which error states to enumerate here.

// Returns the number of steps to get to a value of 1.
steps :: proc(start: int) -> (int, Error) {
steps :: proc(start: int) -> (result: int, ok: bool) {
#panic("Please implement the `steps` procedure.")
}
20 changes: 10 additions & 10 deletions exercises/practice/collatz-conjecture/collatz_conjecture_test.odin
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,35 @@ import "core:testing"

@(test)
test_zero_steps_for_one :: proc(t: ^testing.T) {
s, e := steps(1)
s, ok := steps(1)
testing.expect_value(t, s, 0)
testing.expect_value(t, e, Error.None)
testing.expect(t, ok)
}

@(test)
test_divide_if_even :: proc(t: ^testing.T) {
s, e := steps(16)
s, ok := steps(16)
testing.expect_value(t, s, 4)
testing.expect_value(t, e, Error.None)
testing.expect(t, ok)
}

@(test)
test_even_and_odd_steps :: proc(t: ^testing.T) {
s, e := steps(12)
s, ok := steps(12)
testing.expect_value(t, s, 9)
testing.expect_value(t, e, Error.None)
testing.expect(t, ok)
}

@(test)
test_large_number_of_even_and_odd_steps :: proc(t: ^testing.T) {
s, e := steps(1_000_000)
s, ok := steps(1_000_000)
testing.expect_value(t, s, 152)
testing.expect_value(t, e, Error.None)
testing.expect(t, ok)
}

@(test)
test_zero_is_an_error :: proc(t: ^testing.T) {
s, e := steps(0)
s, ok := steps(0)
testing.expect_value(t, s, 0)
testing.expect_value(t, e, Error.IllegalArgument)
testing.expect(t, !ok)
}

0 comments on commit 47bc81e

Please sign in to comment.