How to resolve the algorithm Sum of squares step by step in the JavaScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sum of squares step by step in the JavaScript programming language

Table of Contents

Problem Statement

Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum of squares step by step in the JavaScript programming language

The provided source code contains multiple implementations of a function that calculates the sum of squares of elements in an array.

1. Initial Implementation:

function sumsq(array) {
 var sum = 0;
 var i, iLen;

 for (i = 0, iLen = array.length; i < iLen; i++) {
   sum += array[i] * array[i];
 }
 return sum;
}
  • This function iterates over the elements of the array using a traditional loop and calculates the sum of their squares.

2. Second Implementation:

function sumsq(array) {
 var sum = 0, 
     i = array.length;

 while (i--) sum += Math.pow(array[i], 2);

 return sum;
}
  • This function uses a while loop to iterate in reverse order and calculate the sum of squares.

3. Functional Implementation (Using Array.reduce):

Functional.reduce("x+y*y", 0, [1,2,3,4,5])
  • This implementation uses the reduce function from a functional programming library. It iteratively applies the given function ("x+y*y") to accumulate the sum of squares.

4. Map/Reduce Implementation:

[3,1,4,1,5,9].map(function (n) { return Math.pow(n,2); }).reduce(function (sum,n) { return sum+n; });
  • This implementation first maps the array elements to their squares using .map, and then applies .reduce to accumulate the sum of squares.

5. Functional Implementation Using ES6 Arrow Functions:

(() => {
   'use strict';

   // sumOfSquares :: Num a => [a] -> a
   const sumOfSquares = xs =>
       sum(xs.map(squared));

   // sumOfSquares2 :: Num a => [a] -> a
   const sumOfSquares2 = xs =>
       xs.reduce((a, x) => a + squared(x), 0);

   // ...
})();
  • This implementation uses ES6 arrow functions and the reduce and map methods of arrays to achieve the same result.

6. Generic Implementation:

// squared :: Num a => a -> a
const squared = x =>
   Math.pow(x, 2);

// sum :: [Num] -> Num
const sum = xs =>
   // The numeric sum of all values in xs.
   xs.reduce((a, x) => a + x, 0);
  • This part defines generic functions for calculating the square of a number (squared) and the sum of a list of numbers (sum). These functions are then used in the implementations above.

Usage: The code includes a simple test case where the functions are applied to an array [3, 1, 4, 1, 5, 9] and the results are printed. It demonstrates that all implementations produce the same result (55).

Source code in the javascript programming language

function sumsq(array) {
  var sum = 0;
  var i, iLen;

  for (i = 0, iLen = array.length; i < iLen; i++) {
    sum += array[i] * array[i];
  }
  return sum;
}

alert(sumsq([1,2,3,4,5]));  // 55


function sumsq(array) {
  var sum = 0, 
      i = array.length;

  while (i--) sum += Math.pow(array[i], 2);

  return sum;
}

alert(sumsq([1,2,3,4,5])); // 55


Functional.reduce("x+y*y", 0, [1,2,3,4,5])


[3,1,4,1,5,9].map(function (n) { return Math.pow(n,2); }).reduce(function (sum,n) { return sum+n; });


(() => {
    'use strict';

    // sumOfSquares :: Num a => [a] -> a
    const sumOfSquares = xs =>
        sum(xs.map(squared));

    // sumOfSquares2 :: Num a => [a] -> a
    const sumOfSquares2 = xs =>
        xs.reduce((a, x) => a + squared(x), 0);


    // ---------------------- TEST -----------------------
    const main = () => [
        sumOfSquares,
        sumOfSquares2
    ].map(
        f => f([3, 1, 4, 1, 5, 9])
    ).join('\n');


    // --------------------- GENERIC ---------------------

    // squared :: Num a => a -> a
    const squared = x =>
        Math.pow(x, 2);

    // sum :: [Num] -> Num
    const sum = xs =>
        // The numeric sum of all values in xs.
        xs.reduce((a, x) => a + x, 0);

    // MAIN ---
    return main();
})();


  

You may also check:How to resolve the algorithm Amb step by step in the Julia programming language
You may also check:How to resolve the algorithm Minimum multiple of m where digital sum equals m step by step in the BASIC programming language
You may also check:How to resolve the algorithm Split a character string based on change of character step by step in the Ring programming language
You may also check:How to resolve the algorithm Sorting algorithms/Sleep sort step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Time a function step by step in the 8051 Assembly programming language