3  If you can’t sleep, just count sheep!!

8kyu Tantangan #3/366 - 17 Feb 2024

https://www.codewars.com/kata/5b077ebdaf15be5c7f000077

3.1 Instruction

Given a non-negative integer, 3 for example, return a string with a murmur: “1 sheep…2 sheep…3 sheep…”. Input will always be valid, i.e. no negative integers.

3.2 YouTube Video

3.3 Solution Code

Solusi bar-bar

countSheep <- function(num){
  if(num == 0){
    return("")
  } else {
    result <- ""
    for(i in 1:num){
      result <- paste(result, i, " sheep...", sep = "")
    }
    return(result)
  }
}

Solusi simple

countSheep <- function(num){
  ifelse(num == 0, "", paste(1:num, "sheep...", collapse = ""))
}

3.4 Test

library(testthat)

test_that("Fixed tests", {
  expect_equal(countSheep(0), "")
  expect_equal(countSheep(1), "1 sheep...")
  expect_equal(countSheep(2), "1 sheep...2 sheep...")
  expect_equal(countSheep(3), "1 sheep...2 sheep...3 sheep...")
})
Test passed 😸

3.5 Supported by

StarCore Analytics