Jump to content

Water collected between towers: Difference between revisions

m
Line 1,762:
{{Trans|Haskell}}
<lang JavaScript>(() => {
'"use strict'";
 
// ---------- WATER COLLECTED BETWEEN TOWERS -----------
 
// waterCollected :: [Int] -> Int
Line 1,779:
 
 
// ----------------------- TEST ------------------------
const main = () => [
[1, 5, 3, 7, 2],
Line 1,791:
 
 
// ---------------------- GENERIC ----------------------
 
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: '"Tuple'",
'"0'": a,
'"1'": b,
length: 2
});
Line 1,808:
// the predicate p.
xs => [...xs].filter(p);
 
 
// gt :: Ord a => a -> a -> Bool
const gt = x => y =>
'Tuple' === x.type ? (
x[0] > y[0]
) : (x > y);
 
 
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
'GeneratorFunction' !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
 
 
Line 1,850 ⟶ 1,831:
xs.reduce((a, x) => {
const v = f(a[0])(x);
 
return Tuple(v)(a[1].concat(v));
}, Tuple(startValue)([startValue]))[1];
Line 1,856 ⟶ 1,838:
// scanl1 :: (a -> a -> a) -> [a] -> [a]
const scanl1 = f =>
// scanl1 is a variant of scanl that has no
// has no starting value argument.
xs => xs.length > 0 ? (
scanl(f)(
Line 1,865 ⟶ 1,847:
 
 
// scanr :: (ba -> ab -> b) -> b -> [a] -> [b]
const scanr = f =>
startValue => xs => xs.reduceRight((a, x) => {
const(a, vx) => f(x)(a[0]);{
return Tuple( const v = f(x)([v].concat(a[10]));
 
}, Tuple(startValue)([startValue]))[1];
return Tuple(v)([v].concat(a[1]));
}, Tuple(startValue)([startValue]))[1];
x)[0] > y[01];
 
 
// scanr1 :: (a -> a -> a) -> [a] -> [a]
const scanr1 = f =>
// scanr1 is a variant of scanr that has no
// seed-value argument, and assumes that
// xs is not empty.
Line 1,894 ⟶ 1,879:
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
 
 
// take :: Int -> [a] -> [a]
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => xs.slice(0, n);
 
 
Line 1,908 ⟶ 1,886:
// custom function, rather than with the
// default tuple constructor.
xs => ys => xs.map((xs_, ys_) => {
const(x, lngi) => Math.minf(length(xs_x), length(ys_)ys[i]);
return take(lng)(xs_).mapslice(
0, Math.min(xxs.length, i) => f(x)(ys_[i]ys.length)
);
})(xs, ys);
 
// MAIN ---
9,655

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.