loading...

Daily Challenge #225 - Square'n'Sum

thepracticaldev profile image dev.to staff ・1 min read

Implement a function squareSum so that it squares any number(s) passed into it and then adds the squares together.

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

Tests
[1, 2, 3, 4]
[0, 3, 5, 7]
[2, 2, 20]

Good luck!


This challenge comes from jhoffner on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Discussion

pic
Editor guide
 

Javascript:

const squareSum = numbers => numbers.map(num => num ** 2).reduce((a, b) => a + b, 0)
 

Trying to find a more... unconventional javascript answer :D

function squareSum(numbers)
{
  if(numbers.length > 0)
  {
    let n = numbers.pop();
    return square(n) + squareSum(numbers);
  }

  return 0;
}

let squares = [0, 1];
function square(n)
{
  let absn = Math.abs(n);
  if(typeof(squares[n]) !== 'undefined')
  {
    return squares[n];
  }

  let sqr = square(absn-1) + (absn-1) + absn;

  squares[n] = sqr;

  return sqr;
}
 

you can actually get rid of the map

const squareSum = arrayOfNumbers => arrayOfNumbers.reduce( (acc, val) => val ** 2 + acc, 0 )
 

I am in love with Python.

square_sum = lambda lst: sum(map(int.__mul__ , *[lst]*2))

print(square_sum([1, 2, 2])) # output -> 9
print(square_sum([1, 2, 3, 4])) # output -> 30
print(square_sum([0, 3, 5, 7])) # output -> 83
print(square_sum([2, 2, 20])) # output -> 408
print(square_sum([])) # output -> 0
 

Sum of squares is the default example of the Rayon crate:

use rayon::prelude::*;
fn sum_of_squares(input: &[i32]) -> i32 {
    input.par_iter() // <-- just change that!
         .map(|&i| i * i)
         .sum()
}

(this runs in parallel)

Apparently people here are really into onelinerization.

let sum_of_squares = |nums| nums.iter().map(|&i| i * i).sum();

No parallelism, but at least it's shorter than Python.

 
squareSum = let square x = x * x in getSum . foldMap (Sum . square)

Btw, you gave "tests" but the tests don't have the supposed results. I know I can hand calculate but still they are not complete test cases.

 

Point free baby!

import Data.Monoid (Sum(..))

squareSum :: (Num c, Foldable t) => t c -> c
squareSum = getSum . foldMap (Sum . (^2))

(Obviously this is probably too polymorphic, you could just limit it to [Int] -> Int)

 

How about this?

squareSum :: [Int] -> Int
squareSum = sum . fmap (^2)

Also point free and a bit easier on the eye. If we want to keep it single traversal, maybe

squareSum = foldr ((+) . (^2)) 0
 

My swift solution :

func squareSum(_ array: [Int]) -> Int {
    Int(array.reduce(into: 0.0) { $0 += pow(Double($1), 2) })
}

squareSum([1, 2, 2]) // 9
squareSum([1, 2, 3, 4]) // 30
squareSum([0, 3, 5, 7]) // 83
squareSum([2, 2, 20]) // 408
squareSum([]) // 0
 

Raku

With nothing else to do in lockdown, I made a Raku version too:

sub sum-squared(@a) { [+] (@a >>*<< @a) }

Or single-pass with reduce:

sub sum-squared(@a) { reduce { $^a + $^b ** 2}, 0, |@a }
 

Elm

I really wish flip is part of the core library...

flip : (a -> b -> c) -> (b -> a -> c)
flip f a b = f b a

squareSum : List Int -> Int
squareSum integers =
    List.foldl (flip (^) 2 >> (+)) 0 integers
 

Ruby:

def square_sum(arr)
  arr.sum { |n| n * n }
end
 

A GolfScript solution:

{{. *}%{+}*}:ssq;

[1 2 2]ssq
#=> 14

Explanation: map (%) the block {. *} over the input. . duplicates the element, * multiplies the top 2 stack elements. Then fold (*) a block performing addition {+} over the result.

 

Python

squareSum = lambda arr: sum([n ** 2 for n in arr])
 

Kotlin

val squareSum = { arr: List<Int> -> arr.map { it * it }.sum() }
 

Elixir

def square_sum(n), do: n |> Enum.map(&(&1 * &1)) |> Enum.sum
 

JS:

function squareSum(numbers){
  return numbers.map(a=>Math.pow(a,2)).reduce((a,b)=>a+b,0);
};