Maximum triangle path sum: Difference between revisions
Content added Content deleted
m (→{{header|Javascript}}: lang -> pre) |
m (→JavaScript :: Functional: Tidied) |
||
Line 1,698: | Line 1,698: | ||
{{Trans|Haskell}} |
{{Trans|Haskell}} |
||
<lang JavaScript>(() => { |
<lang JavaScript>(() => { |
||
"use strict"; |
|||
// |
// ------------------ 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. |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
// Plus greater of two below |
|||
(a, b, c) => a + Math.max(b, c) |
|||
)(xs)(ys)(ys.slice(1)) |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
// foldr1 :: (a -> a -> a) -> [a] -> a |
|||
⚫ | |||
(a, b, c) => a + max(b, c), |
|||
xs => 0 < xs.length ? ( |
|||
xs.slice(0, -1).reduceRight( |
|||
f, xs.slice(-1)[0] |
|||
) |
) |
||
); |
) : []; |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
// Right fold using final element as initial accumulator |
|||
xs => ys => zs => Array.from({ |
|||
length: Math.min( |
|||
⚫ | |||
...[xs, ys, zs].map(x => x.length) |
|||
) |
|||
// head :: [a] -> a |
|||
const head = xs => xs.length ? xs[0] : undefined; |
|||
⚫ | |||
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 |
|||
⚫ | |||
⚫ | |||
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 ----------------------- |
||
return maxPathSum([ |
return maxPathSum([ |
||
[55], |
[55], |