12  Square(n) Sum

8kyu Tantangan #12/366 - 26 Feb 2024

https://www.codewars.com/kata/515e271a311df0350d00000f

12.1 Instruction

Complete the square sum function so that it squares each number passed into it and then sums the results together.

For example, for [1, 2, 2] it should return 9 because 1^2+2^2+2^2=9.

12.2 YouTube Video

12.3 Solution Code

square_sum <- function(nums) {
  for (i in nums) {
    nums[i] <- nums[i]^2
  }
  sum(nums, na.rm = TRUE)
}
square_sum <- function(nums) {
  sum(nums^2)
}

12.4 Test

library(testthat)

test_that("basic tests", {
  expect_equal(square_sum(c(1, 2)), 5)
  expect_equal(square_sum(c(0, 3, 4, 5)), 50)
  expect_equal(square_sum(c()), 0)
  expect_equal(square_sum(c(-1, -2)), 5)
  expect_equal(square_sum(c(-1, 0, 1)), 2)
})
Test passed 🎊

12.5 Supported by

StarCore Analytics