Skip to content

Commit

Permalink
Fix unit tests and example for Collatz Conjecture (#111)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
xarxziux authored and jonmcalder committed Jan 17, 2019
1 parent 600aac9 commit 27021c1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
10 changes: 6 additions & 4 deletions exercises/collatz-conjecture/example.R
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
collatz_step_counter <- function(num) {
collatz_scalar <- function(num) {

if (num <= 0) {
stop("Only positive numbers are allowed")
} else if (num == 1) {
return(0)
return(0)
} else if (num %% 2 == 0) {
return(1 + collatz_step_counter(num / 2))
} else {
return(1 + collatz_step_counter(3 * num + 1))
}

}

collatz_step_counter <- Vectorize(collatz_scalar)
5 changes: 5 additions & 0 deletions exercises/collatz-conjecture/test_collatz-conjecture.R
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,9 @@ test_that("Negative input results in an error", {
expect_error(collatz_step_counter(-15))
})

test_that("Answer can accept vector parameter", {
expect_equal(collatz_step_counter(
c(1, 16, 12, 1000000)), (c(0, 4, 9, 152)))
})

message("All tests passed for exercise: collatz-conjecture")

0 comments on commit 27021c1

Please sign in to comment.