grow <- function(arr) {
result <- 1
for(i in arr){
result <- result * i
}
return(result)
}
4 Beginner - Reduce but Grow!
8Kyu Tantangan #4/366 - 04 Feb 2025
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
Solusi simple
# grow <- function(arr) prod(arr)
grow <- prod
Function prod()
adalah function untuk mengalikan nilai dari satu vector numeric, cara kerjanya sama persis dengan yang diinginkan. Oleh karena itu cukup meng-copy function prod()
sebagai grow()
.
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 🎉
Supported by