Maximum triangle path sum: Difference between revisions

Content added Content deleted
Line 1,698: Line 1,698:
{{Trans|Haskell}}
{{Trans|Haskell}}
<lang JavaScript>(() => {
<lang JavaScript>(() => {
'use strict';
"use strict";


// MAX PATH SUM -----------------------------------------------------------
// ------------------ MAX PATH SUM -------------------


// Working from the bottom of the triangle upwards,
// Working from the bottom of the triangle upwards,
Line 1,708: Line 1,708:
// maxPathSum ::[[Int]] -> Int
// maxPathSum ::[[Int]] -> Int
const maxPathSum = xss =>
const maxPathSum = xss =>
// A list of lists folded down to a list of just one
// remaining integer.
foldr1(
// The accumulator, zipped with the tail of the
// accumulator, yields pairs of adjacent sums.
(ys, xs) => zipWith3(


// A list of lists folded down to a list of just one remaining integer.
// Plus greater of two below
// The head function returns that integer from the list.
(a, b, c) => a + Math.max(b, c)
)(xs)(ys)(ys.slice(1))
)(xss)[0];


head(
foldr1(


// ---------------- GENERIC FUNCTIONS ----------------
// The accumulator, zipped with the tail of the
// accumulator, yields pairs of adjacent sums so far.
(ys, xs) => zipWith3(


// Plus greater of two below
// foldr1 :: (a -> a -> a) -> [a] -> a
const foldr1 = f =>
(a, b, c) => a + max(b, c),
xs, ys, tail(ys)
xs => 0 < xs.length ? (
),
xs.slice(0, -1).reduceRight(
xss
f, xs.slice(-1)[0]
)
)
);
) : [];




// zipWith3 :: (a -> b -> c -> d) ->
// GENERIC FUNCTIONS ------------------------------------------------------
// [a] -> [b] -> [c] -> [d]

const zipWith3 = f =>
// Right fold using final element as initial accumulator
// foldr1 :: (a -> a -> a) -> [a] -> a
xs => ys => zs => Array.from({
length: Math.min(
const foldr1 = (f, xs) =>
xs.length > 0 ? init(xs)
...[xs, ys, zs].map(x => x.length)
.reduceRight(f, last(xs)) : [];
)

// head :: [a] -> a
const head = xs => xs.length ? xs[0] : undefined;

// init :: [a] -> [a]
const init = xs => xs.length ? xs.slice(0, -1) : undefined;

// last :: [a] -> a
const last = xs => xs.length ? xs.slice(-1)[0] : undefined;

// max :: Ord a => a -> a -> a
const max = (a, b) => b > a ? b : a;

// minimum :: [a] -> a
const minimum = xs =>
xs.reduce((a, x) => (x < a || a === undefined ? x : a), undefined);

// tail :: [a] -> [a]
const tail = xs => xs.length ? xs.slice(1) : undefined;

// Function of arity 3 mapped over nth items of each of 3 lists
// zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
const zipWith3 = (f, xs, ys, zs) =>
Array.from({
length: minimum([xs.length, ys.length, zs.length])
}, (_, i) => f(xs[i], ys[i], zs[i]));
}, (_, i) => f(xs[i], ys[i], zs[i]));




// TEST -------------------------------------------------------------------
// ---------------------- TEST -----------------------
return maxPathSum([
return maxPathSum([
[55],
[55],