DEV Community

Discussion on: Daily Coding Puzzles - Nov 4th - Nov 9th

Collapse
 
aspittel profile image
Ali Spittel

Tuesday

Product of Array Items (7 KYU):

Calculate the product of all elements in an array.

CodeWars

Collapse
 
dance2die profile image
Sung M. Kim

A simple aggregation of data (using reduce) worked like a charm.

C# answer.

namespace Kata {
  using System;
  using System.Linq;
  public class ArrayMath
  {
    public static int Product(int[] values)
    {
      return values.Aggregate((product, current) => product * current);
    }
  }
}
Collapse
 
kspeakman profile image
Kasey Speakman

F#

let product arr =
    arr |> Array.reduce (*)

I probably wouldn't define a separate function for this in actual code.

Collapse
 
jreina profile image
Johnny Reina

Does F# require you to name the arr parameter explicitly or can you simply do the following:

let product = Array.reduce (*)

I've been curious about F# for some time but haven't really done a deep dive.

Thread Thread
 
kspeakman profile image
Kasey Speakman

Yes, you can do that in F#. (You probably know this, but for the sake of onlookers) it is called point-free notation. It can be handy for small functions like this. But I noticed when I use it too much, my code can become hard to understand.

Especially for code examples, I rarely use it because it can confuse readers.

Collapse
 
gypsydave5 profile image
David Wickes

JavaScript

const product = arr => arr.reduce((acc, x) => acc * x)
Collapse
 
sdicke profile image
Sebastian Martin Dicke

Haskell:

product' :: Num a => [a] -> a
product' = product
Collapse
 
gypsydave5 profile image
David Wickes

Common Lisp

as * in Common Lisp can take as many arguments as you like...

(apply #'* (list 1 2 3 4 5))
;; => 120
Collapse
 
aspittel profile image
Ali Spittel

Python!

def product(numbers):
    if not numbers: return None
    running_product = 1
    for number in numbers:
        running_product *= number
    return running_product
Collapse
 
marcellothearcane profile image
marcellothearcane
def product (numbers):
  return reduce(lambda total, number: total * number, numbers)
Collapse
 
thejessleigh profile image
jess unrein

Go

func Product(nums []int)(x int) {
    x = 1

    for _, num := range nums {
        x *= num
    }
    return
}

Collapse
 
clandau profile image
Courtney

I decided to not use reduce so that I could return early if I hit a zero.

function product(values) {
  if(!values || values.length === 0) return null;
  let prod = values[0];
  for(let i=1; i<values.length; i++) {
    if(values[i] === 0) return 0;
    prod *= values[i];
  }
  return result;
}
Collapse
 
susickypavel profile image
Pavel Susicky

Javascript

function arrayProduct(arr) {
    return arr.reduce((acc, val) => acc * val);
}
Collapse
 
jay profile image
Jay

Rust

fn product(list: &[i32]) -> i32 {
    list.iter().fold(1, |p, n| p * n)
}