<- function(vec){
positive_sum <- c()
pos_vec for(i in vec){
if(i > 0){
<- c(pos_vec, i)
pos_vec else {
} <- c(pos_vec, 0)
pos_vec
}
}return(sum(pos_vec))
}
6 Sum of positive
8kyu Tantangan #6/366 - 20 Feb 2024
https://www.codewars.com/kata/5715eaedb436cf5606000381
6.1 Instruction
You get an array of numbers, return the sum of all of the positives ones.
Example [1,-4,7,12]
=> 1 + 7 + 12 = 20
Note: if there is nothing to sum, the sum is default to 0.
6.2 YouTube Video
6.3 Solution Code
Solusi bar-bar
Solusi simple
<- function(vec){
positive_sum < 0] <- 0
vec[vec sum(vec)
}
<- function(vec)sum(vec[vec>0]) positive_sum
6.4 Test
library(testthat)
test_that('Basic tests', {
expect_equal(positive_sum(c(1,2,3,4,5)),15)
expect_equal(positive_sum(c(1,-2,3,4,5)),13)
expect_equal(positive_sum(c(-1,2,3,4,-5)),9)
expect_equal(positive_sum(c()),0)
expect_equal(positive_sum(c(-1,-2,-3,-4,-5)),0)
})
Test passed 😀