Skip to content

Commit 27021c1

Browse files
xarxziuxjonmcalder
authored andcommitted
Fix unit tests and example for Collatz Conjecture (#111)
As a demonstration of the point I raised in issue #109, here is an update for the non-core Collatz Conjecture exercise. The current version of this does not test for vector parameters and the example would fail this test. The following changes have been made: - An extra test has been added to the unit tests that send a four-element vector to the function. - In the example, he original function `collatz_step_counter` has been renamed to `collatz_scalar`. - Also in the example, the line `collatz_step_counter <- Vectorize(collatz_scalar)` has been added. This is a very minor change to the example, but makes the function a lot more powerful by taking full advantage of R's vectorisation capabilities. R developers really shouldn't be thinking in single values the way most mainstream programming languages do.
1 parent 600aac9 commit 27021c1

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed
+6-4
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1-
collatz_step_counter <- function(num) {
2-
1+
collatz_scalar <- function(num) {
2+
33
if (num <= 0) {
44
stop("Only positive numbers are allowed")
55
} else if (num == 1) {
6-
return(0)
6+
return(0)
77
} else if (num %% 2 == 0) {
88
return(1 + collatz_step_counter(num / 2))
99
} else {
1010
return(1 + collatz_step_counter(3 * num + 1))
1111
}
12-
12+
1313
}
14+
15+
collatz_step_counter <- Vectorize(collatz_scalar)

exercises/collatz-conjecture/test_collatz-conjecture.R

+5
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,9 @@ test_that("Negative input results in an error", {
2727
expect_error(collatz_step_counter(-15))
2828
})
2929

30+
test_that("Answer can accept vector parameter", {
31+
expect_equal(collatz_step_counter(
32+
c(1, 16, 12, 1000000)), (c(0, 4, 9, 152)))
33+
})
34+
3035
message("All tests passed for exercise: collatz-conjecture")

0 commit comments

Comments
 (0)