4  Beginner - Reduce but Grow

8kyu Tantangan #4/366 - 18 Feb 2024

https://www.codewars.com/kata/57f780909f7e8e3183000078

4.1 Instruction

Given a non-empty array of integers, return the result of multiplying the values together in order. Example:

[1, 2, 3, 4] => 1 * 2 * 3 * 4 = 24

4.2 YouTube Video

4.3 Solution Code

Solusi bar-bar

grow <- function(arr) {
  result <- 1
  for(i in arr){
    result <- result * i
  }
  return(result)
}

Solusi simple

# grow <- function(arr) prod(arr)
grow <- prod

4.4 Test

library(testthat)
test_that("basic tests", {
  expect_equal(grow(c(1, 2, 3)), 6)
  expect_equal(grow(c(4, 1, 1, 1, 4)), 16)
  expect_equal(grow(c(2, 2, 2, 2, 2, 2)), 64)
})
Test passed 🌈

4.5 Supported by

StarCore Analytics