Comma quibbling

Solution:
(() => {
    'use strict';

    // ----------------- COMMA QUIBBLING -----------------

    // quibble :: [String] -> String
    const quibble = xs =>
        1 < xs.length ? (
            intercalate(' and ')(
                ap([
                    compose(
                        intercalate(', '),
                        reverse,
                        tail
                    ),
                    head
                ])([reverse(xs)])
            )
        ) : concat(xs);

    // ---------------------- TEST -----------------------
    const main = () =>
        unlines(
            map(compose(x => '{' + x + '}', quibble))(
                append([
                    [],
                    ["ABC"],
                    ["ABC", "DEF"],
                    ["ABC", "DEF", "G", "H"]
                ])(
                    map(words)([
                        "One two three four",
                        "Me myself I",
                        "Jack Jill",
                        "Loner"
                    ])
                )
            ));

    // ---------------- GENERIC FUNCTIONS ----------------

    // ap (<*>) :: [(a -> b)] -> [a] -> [b]
    const ap = fs =>
        // The sequential application of each of a list
        // of functions to each of a list of values.
        // apList([x => 2 * x, x => 20 + x])([1, 2, 3])
        //     -> [2, 4, 6, 21, 22, 23]
        xs => fs.flatMap(f => xs.map(f));

    // append (++) :: [a] -> [a] -> [a]
    const append = xs =>
        // A list defined by the
        // concatenation of two others.
        ys => xs.concat(ys);

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        // A function defined by the right-to-left
        // composition of all the functions in fs.
        fs.reduce(
            (f, g) => x => f(g(x)),
            x => x
        );

    // concat :: [[a]] -> [a]
    // concat :: [String] -> String
    const concat = xs => (
        ys => 0 < ys.length ? (
            ys.every(Array.isArray) ? (
                []
            ) : ''
        ).concat(...ys) : ys
    )(xs);

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

    // intercalate :: String -> [String] -> String
    const intercalate = s =>
        // The concatenation of xs
        // interspersed with copies of s.
        xs => xs.join(s);

    // list :: StringOrArrayLike b => b -> [a]
    const list = xs =>
        // xs itself, if it is an Array,
        // or an Array derived from xs.
        Array.isArray(xs) ? (
            xs
        ) : Array.from(xs || []);

    // map :: (a -> b) -> [a] -> [b]
    const map = f =>
        // The list obtained by applying f
        // to each element of xs.
        // (The image of xs under f).
        xs => [...xs].map(f);

    // reverse :: [a] -> [a]
    const reverse = xs =>
        'string' !== typeof xs ? (
            xs.slice(0).reverse()
        ) : xs.split('').reverse().join('');

    // tail :: [a] -> [a]
    const tail = xs =>
        // A new list consisting of all
        // items of xs except the first.
        xs.slice(1);

    // unlines :: [String] -> String
    const unlines = xs =>
        // A single string formed by the intercalation
        // of a list of strings with the newline character.
        xs.join('\n');

    // words :: String -> [String]
    const words = s =>
        // List of space-delimited sub-strings.
        s.split(/\s+/);

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


Compare a list of strings

Given a   list   of arbitrarily many strings, show how to:

*   test if they are all lexically '''equal'''
*   test if every string is lexically '''less than''' the one after it  ''(i.e. whether the list is in strict ascending order)''

Each of those two tests should result in a single true or false value, which could be used as the condition of an    if    statement or similar.

If the input list has less than two elements, the tests should always return true.

There is ''no'' need to provide a complete program and output.

Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible.

Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers.

If you need further guidance/clarification,   see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops,   and [[#Raku]] for a solution that gets away with simply using a built-in language feature.

Solution:
(() => {
    'use strict';

    // allEqual :: [String] -> Bool
    let allEqual = xs => and(zipWith(equal, xs, xs.slice(1))),

        // azSorted :: [String] -> Bool
        azSorted = xs => and(zipWith(azBefore, xs, xs.slice(1))),

        // equal :: a -> a -> Bool
        equal = (a, b) => a === b,

        // azBefore :: String -> String -> Bool
        azBefore = (a, b) => a.toLowerCase() <= b.toLowerCase();

    // GENERIC

    // and :: [Bool] -> Bool
    let and = xs => xs.reduceRight((a, x) => a && x, true),

        // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
        zipWith = (f, xs, ys) => {
            let ny = ys.length;
            return (xs.length <= ny ? xs : xs.slice(0, ny))
                .map((x, i) => f(x, ys[i]));
        };

    // TEST

    let lists = [
        ['isiZulu', 'isiXhosa', 'isiNdebele', 'Xitsonga',
            'Tshivenda', 'Setswana', 'Sesotho sa Leboa', 'Sesotho',
            'English', 'Afrikaans'
        ],
        ['Afrikaans', 'English', 'isiNdebele', 'isiXhosa',
            'isiZulu', 'Sesotho', 'Sesotho sa Leboa', 'Setswana',
            'Tshivenda', 'Xitsonga',
        ],
        ['alpha', 'alpha', 'alpha', 'alpha', 'alpha', 'alpha',
            'alpha', 'alpha', 'alpha', 'alpha', 'alpha', 'alpha'
        ]
    ];

    return {
        allEqual: lists.map(allEqual),
        azSorted: lists.map(azSorted)
    };

})();


Convert decimal number to rational

The task is to write a program to transform a decimal number into a fraction in lowest terms.

It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...

Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:
* 67 / 74 = 0.9(054) = 0.9054054...
* 14 / 27 = 0.(518)  = 0.518518...

Acceptable output:

* 0.9054054 - 4527027 / 5000000
* 0.518518  - 259259 / 500000

Finite decimals are of course no problem:

* 0.75      - 3 / 4

Solution:
(() => {
    'use strict';

    const main = () =>
        showJSON(
            map( // Using a tolerance epsilon of 1/10000
                n => showRatio(approxRatio(0.0001)(n)),
                [0.9054054, 0.518518, 0.75]
            )
        );

    // Epsilon -> Real -> Ratio

    // approxRatio :: Real -> Real -> Ratio
    const approxRatio = eps => n => {
        const
            gcde = (e, x, y) => {
                const _gcd = (a, b) => (b < e ? a : _gcd(b, a % b));
                return _gcd(Math.abs(x), Math.abs(y));
            },
            c = gcde(Boolean(eps) ? eps : (1 / 10000), 1, n);
        return Ratio(
            Math.floor(n / c), // numerator
            Math.floor(1 / c) // denominator
        );
    };

    // GENERIC FUNCTIONS ----------------------------------

    // Ratio :: Int -> Int -> Ratio
    const Ratio = (n, d) => ({
        type: 'Ratio',
        'n': n, // numerator
        'd': d // denominator
    });

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) => xs.map(f);

    // showJSON :: a -> String
    const showJSON = x => JSON.stringify(x, null, 2);

    // showRatio :: Ratio -> String
    const showRatio = nd =>
        nd.n.toString() + '/' + nd.d.toString();

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


Convert seconds to compound duration

Write a function or program which:
*   takes a positive integer representing a duration in seconds as input (e.g., 100), and
*   returns a string which shows the same duration decomposed into:
:::*   weeks,
:::*   days,
:::*   hours,
:::*   minutes,   and
:::*   seconds.

This is detailed below (e.g., "2 hr, 59 sec").

Demonstrate that it passes the following three test-cases:

'''''Test Cases'''''

:::::{| class="wikitable"
|-
! input number
! output string
|-
| 7259
| 2 hr, 59 sec
|-
| 86400
| 1 d
|-
| 6000000
| 9 wk, 6 d, 10 hr, 40 min
|}

'''''Details'''''

The following five units should be used:
:::::{| class="wikitable"
|-
! unit
! suffix used in output
! conversion
|-
| week
| wk
| 1 week = 7 days
|-
| day
| d
| 1 day = 24 hours
|-
| hour
| hr
| 1 hour = 60 minutes
|-
| minute
| min
| 1 minute = 60 seconds
|-
| second
| sec
|
|}

However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").

Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)

Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).

Solution:
(function () {
    'use strict';

    // angloDuration :: Int -> String
    function angloDuration(intSeconds) {
        return zip(
                weekParts(intSeconds),
                ['wk', 'd', 'hr', 'min','sec']
            )
            .reduce(function (a, x) {
                return a.concat(x[0] ? (
                    [(x[0].toString() + ' ' + x[1])]
                ) : []);
            }, [])
            .join(', ');
    }

    // weekParts :: Int -> [Int]
    function weekParts(intSeconds) {

        return [undefined, 7, 24, 60, 60]
            .reduceRight(function (a, x) {
                var intRest = a.remaining,
                    intMod = isNaN(x) ? intRest : intRest % x;

                return {
                    remaining:(intRest - intMod) / (x || 1),
                    parts: [intMod].concat(a.parts)
                };
            }, {
                remaining: intSeconds,
                parts: []
            })
            .parts
    }

    // GENERIC ZIP

    // zip :: [a] -> [b] -> [(a,b)]
    function zip(xs, ys) {
        return xs.length === ys.length ? (
            xs.map(function (x, i) {
                return [x, ys[i]];
            })
        ) : undefined;
    }

    // TEST

    return [7259, 86400, 6000000]
        .map(function (intSeconds) {
            return intSeconds.toString() +
                '    ->    ' + angloDuration(intSeconds);
        })
        .join('\n');

})();


Count the coins

There are four types of common coins in   US   currency:
:::#   quarters   (25 cents)
:::#   dimes   (10 cents)
:::#   nickels   (5 cents),   and
:::#   pennies   (1 cent)

There are six ways to make change for 15 cents:
:::#   A dime and a nickel
:::#   A dime and 5 pennies
:::#   3 nickels
:::#   2 nickels and 5 pennies
:::#   A nickel and 10 pennies
:::#   15 pennies

;Task:
How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents).

;Optional:
Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000?

(Note:   the answer is larger than   232).

;References:
* an algorithm from the book ''Structure and Interpretation of Computer Programs''.
* an article in the algorithmist.
* Change-making problem on Wikipedia.

Solution:
function countcoins(t, o) {
    'use strict';
    var targetsLength = t + 1;
    var operandsLength = o.length;
    t = [1];

    for (var a = 0; a < operandsLength; a++) {
        for (var b = 1; b < targetsLength; b++) {

            // initialise undefined target
            t[b] = t[b] ? t[b] : 0;

            // accumulate target + operand ways
            t[b] += (b < o[a]) ? 0 : t[b - o[a]];
        }
    }

    return t[targetsLength - 1];
}


Count the coins

Solution:
var amount = 100,
    coin = [1, 5, 10, 25]
var t = [1];
for (t[amount] = 0, a = 1; a < amount; a++) t[a] = 0 // initialise t[0..amount]=[1,0,...,0]
for (var i = 0, e = coin.length; i < e; i++)
    for (var ci = coin[i], a = ci; a <= amount; a++)
        t[a] += t[a - ci]
document.write(t[amount])


Create an HTML table

Create an HTML table.
* The table body should have at least three rows of three columns.
* Each of these three columns should be labelled "X", "Y", and "Z".
* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
* The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
* The numbers should be aligned in the same fashion for all columns.

Solution:
(() => {
    'use strict';

    // HTML ---------------------------------------------

    // treeHTML :: tree
    //      {tag :: String, text :: String, kvs :: Dict}
    //      -> String
    const treeHTML = tree =>
        foldTree(
            (x, xs) => `<${x.tag + attribString(x.kvs)}>` + (
                'text' in x ? (
                    x.text
                ) : '\n'
            ) + concat(xs) + `</${x.tag}>\n`)(
            tree
        );

    // attribString :: Dict -> String
    const attribString = dct =>
        dct ? (
            ' ' + Object.keys(dct)
            .reduce(
                (a, k) => a + k + '="' + dct[k] + '" ', ''
            ).trim()
        ) : '';

    // TEST ---------------------------------------------
    const main = () => {
        const
            tableStyle = {
                style: "width:25%; border:2px solid silver;"
            },
            trStyle = {
                style: "border:1px solid silver;text-align:right;"
            },
            strCaption = 'Table generated by JS';

        const
            n = 3,
            colNames = take(n)(enumFrom('A')),
            dataRows = map(
                x => Tuple(x)(map(randomRInt(100)(9999))(
                    colNames
                )))(take(n)(enumFrom(1)));

        const
            // TABLE AS TREE STRUCTURE  -----------------
            tableTree = Node({
                    tag: 'table',
                    kvs: tableStyle
                },
                append([
                    Node({
                        tag: 'caption',
                        text: 'Table source generated by JS'
                    }),
                    // HEADER ROW -----------------------
                    Node({
                            tag: 'tr',
                        },
                        map(k => Node({
                            tag: 'th',
                            kvs: {
                                style: "text-align:right;"
                            },
                            text: k
                        }))(cons('')(colNames))
                    )
                    // DATA ROWS ------------------------
                ])(map(tpl => Node({
                    tag: 'tr',
                    kvs: trStyle
                }, cons(
                    Node({
                        tag: 'th',
                        text: fst(tpl)
                    }))(
                    map(v => Node({
                        tag: 'td',
                        text: v.toString()
                    }))(snd(tpl))
                )))(dataRows))
            );

        // Return a value and/or apply console.log to it.
        // (JS embeddings vary in their IO channels)
        const strHTML = treeHTML(tableTree);
        return (
            console.log(strHTML)
            //strHTML
        );
    };

    // GENERIC FUNCTIONS --------------------------------

    // Node :: a -> [Tree a] -> Tree a
    const Node = (v, xs) => ({
        type: 'Node',
        root: v,
        nest: xs || []
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a => b => ({
        type: 'Tuple',
        '0': a,
        '1': b,
        length: 2
    });

    // append (++) :: [a] -> [a] -> [a]
    // append (++) :: String -> String -> String
    const append = xs => ys => xs.concat(ys);

    // chr :: Int -> Char
    const chr = String.fromCodePoint;

    // concat :: [[a]] -> [a]
    // concat :: [String] -> String
    const concat = xs =>
        0 < xs.length ? (() => {
            const unit = 'string' !== typeof xs[0] ? (
                []
            ) : '';
            return unit.concat.apply(unit, xs);
        })() : [];

    // cons :: a -> [a] -> [a]
    const cons = x => xs => [x].concat(xs);

    // enumFrom :: a -> [a]
    function* enumFrom(x) {
        let v = x;
        while (true) {
            yield v;
            v = succ(v);
        }
    }

    // enumFromToChar :: Char -> Char -> [Char]
    const enumFromToChar = m => n => {
        const [intM, intN] = [m, n].map(
            x => x.charCodeAt(0)
        );
        return Array.from({
            length: Math.floor(intN - intM) + 1
        }, (_, i) => String.fromCodePoint(intM + i));
    };

    // foldTree :: (a -> [b] -> b) -> Tree a -> b
    const foldTree = f => tree => {
        const go = node =>
            f(node.root, node.nest.map(go));
        return go(tree);
    };

    // fst :: (a, b) -> a
    const fst = tpl => tpl[0];

    // isChar :: a -> Bool
    const isChar = x =>
        ('string' === typeof x) && (1 === x.length);

    // map :: (a -> b) -> [a] -> [b]
    const map = f => xs =>
        (Array.isArray(xs) ? (
            xs
        ) : xs.split('')).map(f);

    // ord :: Char -> Int
    const ord = c => c.codePointAt(0);

    // randomRInt :: Int -> Int -> () -> Int
    const randomRInt = low => high => () =>
        low + Math.floor(
            (Math.random() * ((high - low) + 1))
        );

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

    // succ :: Enum a => a -> a
    const succ = x =>
        isChar(x) ? (
            chr(1 + ord(x))
        ) : isNaN(x) ? (
            undefined
        ) : 1 + x;

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n => xs =>
        'GeneratorFunction' !== xs.constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

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


Currency

Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.

;Note:
The '''IEEE 754''' binary floating point representations of numbers like   '''2.86'''   and   '''.0765'''   are not exact.

For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.

Use the values:
::* 4000000000000000 hamburgers at $5.50 each       (four quadrillion burgers)
::* 2 milkshakes at $2.86 each, and
::* a tax rate of 7.65%.

(That number of hamburgers is a 4 with 15 zeros after it.    The number is contrived to exclude naive task solutions using 64 bit floating point types.)

Compute and output (show results on this page):
::* the total price before tax
::* the tax
::* the total with tax

The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.

The output must show dollars and cents with a decimal point.

The three results displayed should be:
::* 22000000000000005.72
::* 1683000000000000.44
::* 23683000000000006.16

Dollar signs and thousands separators are optional.

Solution:
const money = require('money-math')

let hamburgers = 4000000000000000
let hamburgerPrice = 5.50

let shakes = 2
let shakePrice = 2.86

let tax = 7.65

let hamburgerTotal = money.mul(hamburgers.toFixed(0), money.floatToAmount(hamburgerPrice))
let shakeTotal = money.mul(shakes.toFixed(0), money.floatToAmount(shakePrice))

let subTotal = money.add(hamburgerTotal, shakeTotal)

let taxTotal = money.percent(subTotal, tax)

let total = money.add(subTotal, taxTotal)

console.log('Hamburger Total:', hamburgerTotal)
console.log('Shake Total:', shakeTotal)
console.log('Sub Total:', subTotal)
console.log('Tax:', taxTotal)
console.log('Total:', total)


Currying

{{Wikipedia|Currying}}

;Task:
Create a simple demonstrative example of Currying in a specific language.

Add any historic details as to how the feature made its way into the language.

Solution:
(function () {

    // curry :: ((a, b) -> c) -> a -> b -> c
    function curry(f) {
        return function (a) {
            return function (b) {
                return f(a, b);
            };
        };
    }

    // TESTS

    // product :: Num -> Num -> Num
    function product(a, b) {
        return a * b;
    }

    // return typeof curry(product);
    // --> function

    // return typeof curry(product)(7)
    // --> function

    //return typeof curry(product)(7)(9)
    // --> number

    return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        .map(curry(product)(7))

    // [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]

})();


Damm algorithm

The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.

The algorithm is named after H. Michael Damm.

;Task:
Verify the checksum, stored as last digit of an input.

Solution:
const table = [
    [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
    [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
    [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
    [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
    [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
    [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
    [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
    [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
    [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
    [2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
 ];

const lookup = (p, c) => table[p][parseInt(c, 10)]
const damm = input => [...input].reduce(lookup, 0) === 0;

// ----------------------------------------------------------[ Tests ]----
const test = () => ["5724", "5727", "112946", "112949"].forEach(e =>
    console.log(`${e} => ${damm(e) ? 'Pass' : 'Fail'}`)
);
test();


Deepcopy

Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.

This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.

If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.

The task should show:

* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.

* Any limitations of the method.

* That the structure and its copy are different.

* Suitable links to external documentation for common libraries.

Solution:
var deepcopy = function(o){
  return JSON.parse(JSON.stringify(src));
};

var src = {foo:0,bar:[0,1]};
print(JSON.stringify(src));
var dst = deepcopy(src);
print(JSON.stringify(src));


Department numbers

There is a highly organized city that has decided to assign a number to each of their departments:
::*   police department
::*   sanitation department
::*   fire department

Each department can have a number between   '''1'''   and   '''7'''   (inclusive).

The three department numbers are to be unique (different from each other) and must add up to   '''12'''.

The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.

;Task:
Write a computer program which outputs all valid combinations.

Possible output   (for the 1st and 14th solutions):

  --police--  --sanitation--  --fire--
      2             3            7
      6             5            1

Solution:
(function () {
    'use strict';

    // concatMap :: (a -> [b]) -> [a] -> [b]
    function concatMap(f, xs) {
        return [].concat.apply([], xs.map(f));
    };

    return '(Police, Sanitation, Fire)\n' +
        concatMap(function (x) {
            return concatMap(function (y) {
                return concatMap(function (z) {
                    return z !== y && 1 <= z && z <= 7 ? [
                        [x, y, z]
                    ] : [];
                }, [12 - (x + y)]);
            }, [1, 2, 3, 4, 5, 6, 7]);
        }, [2, 4, 6])
        .map(JSON.stringify)
        .join('\n');
})();


Department numbers

Solution:
(() => {
    "use strict";

    // -------------- NUMBERING CONSTRAINTS --------------

    // options :: Int -> Int -> Int -> [(Int, Int, Int)]
    const options = lo => hi => total => {
        const
            bind = xs => f => xs.flatMap(f),
            ds = enumFromTo(lo)(hi);

        return bind(ds.filter(even))(
            x => bind(ds.filter(d => d !== x))(
                y => bind([total - (x + y)])(
                    z => (z !== y && lo <= z && z <= hi) ? [
                        [x, y, z]
                    ] : []
                )
            )
        );
    };

    // ---------------------- TEST -----------------------
    const main = () => {
        const
            label = "(Police, Sanitation, Fire)",
            solutions = options(1)(7)(12),
            n = solutions.length,
            list = solutions
            .map(JSON.stringify)
            .join("\n");

        return (
            `${label}\n\n${list}\n\nNumber of options: ${n}`
        );
    };

    // ---------------- GENERIC FUNCTIONS ----------------

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = m =>
        n => Array.from({
            length: 1 + n - m
        }, (_, i) => m + i);

    // even :: Integral a => a -> Bool
    const even = n => n % 2 === 0;

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


Detect division by zero

Write a function to detect a   ''divide by zero error''   without checking if the denominator is zero.

Solution:
function divByZero(dividend,divisor)
{
	var quotient=dividend/divisor;
        if(isNaN(quotient)) return 0; //Can be changed to whatever is desired by the programmer to be 0, false, or Infinity
        return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively
}
alert(divByZero(0,0));


Determinant and permanent

permanent of the matrix.

The determinant is given by
:: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i}
while the permanent is given by
::  \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i}
In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)

More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.

;Related task:
* [[Permutations by swapping]]

Solution:
const determinant = arr =>
    arr.length === 1 ? (
        arr[0][0]
    ) : arr[0].reduce(
        (sum, v, i) => sum + v * (-1) ** i * determinant(
            arr.slice(1)
            .map(x => x.filter((_, j) => i !== j))
        ), 0
    );

const permanent = arr =>
    arr.length === 1 ? (
        arr[0][0]
    ) : arr[0].reduce(
        (sum, v, i) => sum + v * permanent(
            arr.slice(1)
            .map(x => x.filter((_, j) => i !== j))
        ), 0
    );

const M = [
    [0, 1, 2, 3, 4],
    [5, 6, 7, 8, 9],
    [10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19],
    [20, 21, 22, 23, 24]
];
console.log(determinant(M));
console.log(permanent(M));


Determine if a string has all the same characters

Given a character string   (which may be empty, or have a length of zero characters):
::*   create a function/procedure/routine to:
::::*    determine if all the characters in the string are the same
::::*    indicate if or which character is different from the previous character
::*   display each string and its length   (as the strings are being examined)
::*   a zero-length (empty) string shall be considered as all the same character(s)
::*   process the strings from left-to-right
::*   if       all the same character,   display a message saying such
::*   if                  not all the same character,   then:
::::*    display a message saying such
::::*    display what character is different
::::*    only the 1st different character need be displayed
::::*    display where the different character is in the string
::::*    the above messages can be part of a single message
::::*    display the hexadecimal value of the different character

Use (at least) these seven test values   (strings):
:::*   a string of length   0   (an empty string)
:::*   a string of length   3   which contains three blanks
:::*   a string of length   1   which contains:   '''2'''
:::*   a string of length   3   which contains:   '''333'''
:::*   a string of length   3   which contains:   '''.55'''
:::*   a string of length   6   which contains:   '''tttTTT'''
:::*   a string of length   9   with a blank in the middle:   '''4444   444k'''

Show all output here on this page.

Solution:
const check = s => {
  const arr = [...s];
  const at = arr.findIndex(
      (v, i) => i === 0 ? false : v !== arr[i - 1]
  )
  const l = arr.length;
  const ok = at === -1;
  const p = ok ? "" : at + 1;
  const v = ok ? "" : arr[at];
  const vs = v === "" ? v : `"${v}"`
  const h = ok ? "" : `0x${v.codePointAt(0).toString(16)}`;
  console.log(`"${s}" => Length:${l}\tSame:${ok}\tPos:${p}\tChar:${vs}\tHex:${h}`)
}

['', '   ', '2', '333', '.55', 'tttTTT', '4444 444k', '🐶🐶🐺🐶', '🎄🎄🎄🎄'].forEach(check)


Determine if a string has all unique characters

Given a character string   (which may be empty, or have a length of zero characters):
::*   create a function/procedure/routine to:
::::*    determine if all the characters in the string are unique
::::*    indicate if or which character is duplicated and where
::*   display each string and its length   (as the strings are being examined)
::*   a zero-length (empty) string shall be considered as unique
::*   process the strings from left-to-right
::*   if       unique,   display a message saying such
::*   if                  not unique,   then:
::::*    display a message saying such
::::*    display what character is duplicated
::::*    only the 1st non-unique character need be displayed
::::*    display where "both" duplicated characters are in the string
::::*    the above messages can be part of a single message
::::*    display the hexadecimal value of the duplicated character

Use (at least) these five test values   (strings):
:::*   a string of length     0   (an empty string)
:::*   a string of length     1   which is a single period   ('''.''')
:::*   a string of length     6   which contains:   '''abcABC'''
:::*   a string of length     7   which contains a blank in the middle:   '''XYZ  ZYX'''
:::*   a string of length         36   which   ''doesn't''   contain the letter "oh":
::::::::  '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''

Show all output here on this page.

Solution:
(() => {
    'use strict';

    // duplicatedCharIndices :: String -> Maybe (Char, [Int])
    const duplicatedCharIndices = s => {
        const
            duplicates = filter(g => 1 < g.length)(
                groupBy(on(eq)(snd))(
                    sortOn(snd)(
                        zip(enumFrom(0))(chars(s))
                    )
                )
            );
        return 0 < duplicates.length ? Just(
            fanArrow(compose(snd, fst))(map(fst))(
                sortOn(compose(fst, fst))(
                    duplicates
                )[0]
            )
        ) : Nothing();
    };

    // ------------------------TEST------------------------
    const main = () =>
        console.log(
            fTable('First duplicated character, if any:')(
                s => `'${s}' (${s.length})`
            )(maybe('None')(tpl => {
                const [c, ixs] = Array.from(tpl);
                return `'${c}' (0x${showHex(ord(c))}) at ${ixs.join(', ')}`
            }))(duplicatedCharIndices)([
                "", ".", "abcABC", "XYZ ZYX",
                "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"
            ])
        );

    // -----------------GENERIC FUNCTIONS------------------

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a => b => ({
        type: 'Tuple',
        '0': a,
        '1': b,
        length: 2
    });

    // chars :: String -> [Char]
    const chars = s => s.split('');

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        x => fs.reduceRight((a, f) => f(a), x);

    // enumFrom :: Enum a => a -> [a]
    function* enumFrom(x) {
        let v = x;
        while (true) {
            yield v;
            v = 1 + v;
        }
    }

    // eq (==) :: Eq a => a -> a -> Bool
    const eq = a => b => a === b;

    // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c))
    const fanArrow = f =>
        // Compose a function from a simple value to a tuple of
        // the separate outputs of two different functions.
        g => x => Tuple(f(x))(g(x));

    // filter :: (a -> Bool) -> [a] -> [a]
    const filter = f => xs => xs.filter(f);

    // fst :: (a, b) -> a
    const fst = tpl => tpl[0];

    // fTable :: String -> (a -> String) -> (b -> String)
    //                      -> (a -> b) -> [a] -> String
    const fTable = s => xShow => fxShow => f => xs => {
        // Heading -> x display function ->
        //           fx display function ->
        //    f -> values -> tabular string
        const
            ys = xs.map(xShow),
            w = Math.max(...ys.map(length));
        return s + '\n' + zipWith(
            a => b => a.padStart(w, ' ') + ' -> ' + b
        )(ys)(
            xs.map(x => fxShow(f(x)))
        ).join('\n');
    };

    // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
    const groupBy = fEq =>
        // Typical usage: groupBy(on(eq)(f), xs)
        xs => 0 < xs.length ? (() => {
            const
                tpl = xs.slice(1).reduce(
                    (gw, x) => {
                        const
                            gps = gw[0],
                            wkg = gw[1];
                        return fEq(wkg[0])(x) ? (
                            Tuple(gps)(wkg.concat([x]))
                        ) : Tuple(gps.concat([wkg]))([x]);
                    },
                    Tuple([])([xs[0]])
                );
            return tpl[0].concat([tpl[1]])
        })() : [];

    // 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
        (Array.isArray(xs) || 'string' === typeof xs) ? (
            xs.length
        ) : Infinity;

    // map :: (a -> b) -> [a] -> [b]
    const map = f => xs =>
        (Array.isArray(xs) ? (
            xs
        ) : xs.split('')).map(f);

    // maybe :: b -> (a -> b) -> Maybe a -> b
    const maybe = v =>
        // Default value (v) if m is Nothing, or f(m.Just)
        f => m => m.Nothing ? v : f(m.Just);

    // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
    const on = f =>
        g => a => b => f(g(a))(g(b));

    // ord :: Char -> Int
    const ord = c => c.codePointAt(0);

    // showHex :: Int -> String
    const showHex = n =>
        n.toString(16);

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

    // sortOn :: Ord b => (a -> b) -> [a] -> [a]
    const sortOn = f =>
        // Equivalent to sortBy(comparing(f)), but with f(x)
        // evaluated only once for each x in xs.
        // ('Schwartzian' decorate-sort-undecorate).
        xs => xs.map(
            x => [f(x), x]
        ).sort(
            (a, b) => a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0)
        ).map(x => x[1]);

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n => xs =>
        'GeneratorFunction' !== xs.constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    // uncurry :: (a -> b -> c) -> ((a, b) -> c)
    const uncurry = f =>
        (x, y) => f(x)(y)

    // zip :: [a] -> [b] -> [(a, b)]
    const zip = xs => ys => {
        const
            lng = Math.min(length(xs), length(ys)),
            vs = take(lng)(ys);
        return take(lng)(xs)
            .map((x, i) => Tuple(x)(vs[i]));
    };

    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    const zipWith = f =>
        xs => ys => {
            const
                lng = Math.min(length(xs), length(ys)),
                vs = take(lng)(ys);
            return take(lng)(xs)
                .map((x, i) => f(x)(vs[i]));
        };

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


Determine if a string is collapsible

Determine if a character string is   ''collapsible''.

And if so,   collapse the string   (by removing   ''immediately repeated''   characters).

If a character string has   ''immediately repeated''   character(s),   the repeated characters are to be
deleted (removed),   but not the primary (1st) character(s).

An   ''immediately repeated''   character is any character that is   immediately   followed by an
identical character (or characters).   Another word choice could've been   ''duplicated character'',   but that
might have ruled out   (to some readers)   triplicated characters   ***   or more.

{This Rosetta Code task was inspired by a newly introduced   (as of around November 2019)   '''PL/I'''   BIF:   '''collapse'''.}

;Examples:
In the following character string:

  The better the 4-wheel drive, the further you'll be from help when ya get stuck!

Only the 2nd   '''t''',   '''e''', and   '''l'''   are repeated characters,   indicated
by underscores (above),   even though they (those characters) appear elsewhere in the character string.

So, after ''collapsing'' the string, the result would be:

  The beter the 4-whel drive, the further you'l be from help when ya get stuck!

Another example:
In the following character string:

  headmistressship

The "collapsed" string would be:

  headmistreship

;Task:
Write a subroutine/function/procedure/routine***   to
locate   ''repeated''   characters and   ''collapse''   (delete)   them from the character
string.   The character string can be processed from either direction.

Show all output here, on this page:
:*   the   original string and its length
:*   the       resultant string and its length
:*   the above strings should be "bracketed" with   '''<<<'''   and   '''>>>'''   (to delineate blanks)
;*   <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers,   shown used here>>>>>>

Use (at least) the following five strings,   all strings are length seventy-two (characters, including blanks),   except
the 1st string:

  string
  number
         ++
    1    |+-----------------------------------------------------------------------+   <######  a null string  (length zero)
    2    |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln |
    3    |..1111111111111111111111111111111111111111111111111111111111111117777888|
    4    |I never give 'em hell, I just tell the truth, and they think it's hell. |
    5    |                                                    --- Harry S Truman  |   <######  has many repeated blanks
         +------------------------------------------------------------------------+

Solution:
String.prototype.collapse = function() {
  let str = this;
  for (let i = 0; i < str.length; i++) {
    while (str[i] == str[i+1]) str = str.substr(0,i) + str.substr(i+1);
  }
  return str;
}

// testing
let strings = [
  '',
  '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
  '..1111111111111111111111111111111111111111111111111111111111111117777888',
  `I never give 'em hell, I just tell the truth, and they think it's hell. `,
  '                                                    --- Harry S Truman  '
];
for (let i = 0; i < strings.length; i++) {
  let str = strings[i], col = str.collapse();
  console.log(`«««${str}»»» (${str.length})`);
  console.log(`«««${col}»»» (${col.length})`);
}


Dice game probabilities

Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.

They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?

Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?

This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205

Solution:
let Player = function(dice, faces) {
  this.dice = dice;
  this.faces = faces;
  this.roll = function() {
    let results = [];
    for (let x = 0; x < dice; x++)
      results.push(Math.floor(Math.random() * faces +1));
    return eval(results.join('+'));
  }
}

function contest(player1, player2, rounds) {
  let res = [0, 0, 0];
  for (let x = 1; x <= rounds; x++) {
    let a = player1.roll(),
        b = player2.roll();
    switch (true) {
      case (a > b): res[0]++; break;
      case (a < b): res[1]++; break;
      case (a == b): res[2]++; break;
    }
  }
  document.write(`

        Player 1 (${player1.dice} × d${player1.faces}): ${res[0]} wins

        Player 2 (${player2.dice} × d${player2.faces}): ${res[1]} wins

        Draws: ${res[2]}

        Chances for Player 1 to win:
        ~${Math.round(res[0] / eval(res.join('+')) * 100)} %

  `);
}

let p1, p2;

p1 = new Player(9, 4),
p2 = new Player(6, 6);
contest(p1, p2, 1e6);

p1 = new Player(5, 10);
p2 = new Player(6, 7);
contest(p1, p2, 1e6);


Digital root

The digital root, X, of a number, n, is calculated:
: find X as the sum of the digits of n
: find a new X by summing the digits of X, repeating until X has only one digit.

The additive persistence is the number of summations required to obtain the single digit.

The task is to calculate the additive persistence and the digital root of a number, e.g.:
:627615 has additive persistence 2 and digital root of 9;
:39390 has additive persistence 2 and digital root of 6;
:588225 has additive persistence 2 and digital root of 3;
:393900588225 has additive persistence 2 and digital root of 9;

The digital root may be calculated in bases other than 10.

;See:
* [[Casting out nines]] for this wiki's use of this procedure.
* [[Digital root/Multiplicative digital root]]
* [[Sum digits of an integer]]
* Digital root sequence on OEIS
* Additive persistence sequence on OEIS
* [[Iterated digits squaring]]

Solution:
/// Digital root of 'x' in base 'b'.
/// @return {addpers, digrt}
function digitalRootBase(x,b) {
   if (x < b)
      return {addpers:0, digrt:x};

   var fauxroot = 0;
   while (b <= x) {
      x = (x / b) | 0;
      fauxroot += x % b;
   }

   var rootobj = digitalRootBase(fauxroot,b);
   rootobj.addpers += 1;
   return rootobj;
}


Disarium numbers

A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.

;E.G.

'''135''' is a '''Disarium number''':

 11 + 32 + 53 == 1 + 9 + 125 == 135

There are a finite number of '''Disarium numbers'''.

;Task

* Find and display the first 18 '''Disarium numbers'''.

;Stretch

* Find and display all 20 '''Disarium numbers'''.

;See also

;* Geeks for Geeks - Disarium numbers
;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
;* Related task: Narcissistic decimal number
;* Related task: Own digits power sum  ''Which seems to be the same task as Narcissistic decimal number...''

Solution:
function is_disarium (num) {
    let n = num
    let len = n.toString().length
    let sum = 0
    while (n > 0) {
        sum += (n % 10) ** len
        n = parseInt(n / 10, 10)
        len--
    }
    return num == sum
}
let count = 0
let i = 1
while (count < 18) {
    if (is_disarium(i)) {
        process.stdout.write(i + " ")
        count++
    }
    i++
}


Display an outline as a nested table

{| class="wikitable" style="text-align: center;"
|-
| style="background: #ffffe6; " colspan=7 | Display an outline as a nested table.
|-
| style="background: #ffebd2; " colspan=3 | Parse the outline to a tree,
| style="background: #f0fff0; " colspan=2 | count the leaves descending from each node,
| style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values
|-
| style="background: #ffebd2; " | measuring the indent of each line,
| style="background: #ffebd2; " | translating the indentation to a nested structure,
| style="background: #ffebd2; " | and padding the tree to even depth.
| style="background: #f0fff0; " | defining the width of a leaf as 1,
| style="background: #f0fff0; " | and the width of a parent node as a sum.
| style="background: #e6ffff; " | either as a wiki table,
| style="background: #e6ffff; " | or as HTML.
|-
|  |
|  |
|  |
|  |
| style="background: #f0fff0; " | (The sum of the widths of its children)
|  |
|  |
|}

The graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.

;Task:
Given a outline with at least 3 levels of indentation, for example:

Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.

write a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.

The WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:

{| class="wikitable" style="text-align: center;"
|-
| style="background: #ffffe6; " colspan=7 | Display an outline as a nested table.
|-
| style="background: #ffebd2; " colspan=3 | Parse the outline to a tree,
| style="background: #f0fff0; " colspan=2 | count the leaves descending from each node,
| style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values
|-
| style="background: #ffebd2; " | measuring the indent of each line,
| style="background: #ffebd2; " | translating the indentation to a nested structure,
| style="background: #ffebd2; " | and padding the tree to even depth.
| style="background: #f0fff0; " | defining the width of a leaf as 1,
| style="background: #f0fff0; " | and the width of a parent node as a sum.
| style="background: #e6ffff; " | either as a wiki table,
| style="background: #e6ffff; " | or as HTML.
|-
|  |
|  |
|  |
|  |
| style="background: #f0fff0; " | (The sum of the widths of its children)
|  |
|  |
|}

;Extra credit:
Use background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.

;Output:
Display your nested table on this page.

Solution:
(() => {
    "use strict";

    // ----------- NESTED TABLES FROM OUTLINE ------------

    // wikiTablesFromOutline :: [String] -> String -> String
    const wikiTablesFromOutline = colorSwatch =>
        outline => forestFromIndentedLines(
            indentLevelsFromLines(lines(outline))
        )
        .map(wikiTableFromTree(colorSwatch))
        .join("\n\n");

    // wikiTableFromTree :: [String] -> Tree String -> String
    const wikiTableFromTree = colorSwatch =>
        compose(
            wikiTableFromRows,
            levels,
            paintedTree(colorSwatch),
            widthLabelledTree,
            ap(paddedTree(""))(treeDepth)
        );

    // ---------------------- TEST -----------------------
    // main :: IO ()
    const main = () => {
        const outline = `Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.`;

        return wikiTablesFromOutline([
            "#ffffe6",
            "#ffebd2",
            "#f0fff0",
            "#e6ffff",
            "#ffeeff"
        ])(outline);
    };

    // --------- TREE STRUCTURE FROM NESTED TEXT ---------

    // forestFromIndentedLines :: [(Int, String)] ->
    // [Tree String]
    const forestFromIndentedLines = tuples => {
        const go = xs =>
            0 < xs.length ? (() => {
                // First line and its sub-tree,
                const [indented, body] = Array.from(
                        xs[0]
                    ),
                    [tree, rest] = Array.from(
                        span(compose(lt(indented), fst))(
                            tail(xs)
                        )
                    );

                // followed by the rest.
                return [
                    Node(body)(go(tree))
                ].concat(go(rest));
            })() : [];

        return go(tuples);
    };

    // indentLevelsFromLines :: [String] -> [(Int, String)]
    const indentLevelsFromLines = xs => {
        const
            pairs = xs.map(
                x => bimap(length)(cs => cs.join(""))(
                    span(isSpace)(list(x))
                )
            ),
            indentUnit = pairs.reduce(
                (a, tpl) => {
                    const i = tpl[0];

                    return 0 < i ? (
                        i < a ? i : a
                    ) : a;
                },
                Infinity
            );

        return [Infinity, 0].includes(indentUnit) ? (
            pairs
        ) : pairs.map(first(n => n / indentUnit));
    };

    // ------------ TREE PADDED TO EVEN DEPTH ------------

    // paddedTree :: a -> Tree a -> Int -> Tree a
    const paddedTree = padValue =>
        // All descendants expanded to same depth
        // with empty nodes where needed.
        node => depth => {
            const go = n => tree =>
                1 < n ? (() => {
                    const children = nest(tree);

                    return Node(root(tree))(
                        (
                            0 < children.length ? (
                                children
                            ) : [Node(padValue)([])]
                        ).map(go(n - 1))
                    );
                })() : tree;

            return go(depth)(node);
        };

    // treeDepth :: Tree a -> Int
    const treeDepth = tree =>
        foldTree(
            () => xs => 0 < xs.length ? (
                1 + maximum(xs)
            ) : 1
        )(tree);

    // ------------- SUBTREE WIDTHS MEASURED -------------

    // widthLabelledTree :: Tree a -> Tree (a, Int)
    const widthLabelledTree = tree =>
        // A tree in which each node is labelled with
        // the width of its own subtree.
        foldTree(x => xs =>
            0 < xs.length ? (
                Node(Tuple(x)(
                    xs.reduce(
                        (a, node) => a + snd(root(node)),
                        0
                    )
                ))(xs)
            ) : Node(Tuple(x)(1))([])
        )(tree);

    // -------------- COLOR SWATCH APPLIED ---------------

    // paintedTree :: [String] -> Tree a -> Tree (String, a)
    const paintedTree = colorSwatch =>
        tree => 0 < colorSwatch.length ? (
            Node(
                Tuple(colorSwatch[0])(root(tree))
            )(
                zipWith(compose(fmapTree, Tuple))(
                    cycle(colorSwatch.slice(1))
                )(
                    nest(tree)
                )
            )
        ) : fmapTree(Tuple(""))(tree);

    // --------------- WIKITABLE RENDERED ----------------

    // wikiTableFromRows ::
    // [[(String, (String, Int))]] -> String
    const wikiTableFromRows = rows => {
        const
            cw = color => width => {
                const go = w =>
                    1 < w ? (
                        `colspan=${w} `
                    ) : "";

                return `style="background:${color}; "` + (
                    ` ${go(width)}`
                );
            },
            cellText = ctw => {
                const [color, tw] = Array.from(ctw);
                const [txt, width] = Array.from(tw);

                return 0 < txt.length ? (
                    `| ${cw(color)(width)}| ${txt}`
                ) : "| |";
            },
            classText = "class=\"wikitable\"",
            styleText = "style=\"text-align:center;\"",
            header = `{| ${classText} ${styleText}\n|-`,
            tableBody = rows.map(
                cells => cells.map(cellText).join("\n")
            ).join("\n|-\n");

        return `${header}\n${tableBody}\n|}`;
    };

    // ------------------ GENERIC TREES ------------------

    // Node :: a -> [Tree a] -> Tree a
    const Node = v =>
        // Constructor for a Tree node which connects a
        // value of some kind to a list of zero or
        // more child trees.
        xs => ({
            type: "Node",
            root: v,
            nest: xs || []
        });

    // fmapTree :: (a -> b) -> Tree a -> Tree b
    const fmapTree = f => {
        // A new tree. The result of a
        // structure-preserving application of f
        // to each root in the existing tree.
        const go = t => Node(
            f(t.root)
        )(
            t.nest.map(go)
        );

        return go;
    };

    // foldTree :: (a -> [b] -> b) -> Tree a -> b
    const foldTree = f => {
        // The catamorphism on trees. A summary
        // value obtained by a depth-first fold.
        const go = tree => f(
            root(tree)
        )(
            nest(tree).map(go)
        );

        return go;
    };

    // levels :: Tree a -> [[a]]
    const levels = tree => {
        // A list of lists, grouping the root
        // values of each level of the tree.
        const go = (a, node) => {
            const [h, ...t] = 0 < a.length ? (
                a
            ) : [
                [],
                []
            ];

            return [
                [node.root, ...h],
                ...node.nest.slice(0)
                .reverse()
                .reduce(go, t)
            ];
        };

        return go([], tree);
    };

    // nest :: Tree a -> [a]
    const nest = tree => {
        // Allowing for lazy (on-demand) evaluation.
        // If the nest turns out to be a function –
        // rather than a list – that function is applied
        // here to the root, and returns a list.
        const xs = tree.nest;

        return "function" !== typeof xs ? (
            xs
        ) : xs(root(tree));
    };

    // root :: Tree a -> a
    const root = tree =>
        // The value attached to a tree node.
        tree.root;

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

    // Just :: a -> Maybe a
    const Just = x => ({
        type: "Maybe",
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: "Maybe",
        Nothing: true
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a =>
        b => ({
            type: "Tuple",
            "0": a,
            "1": b,
            length: 2
        });

    // apFn :: (a -> b -> c) -> (a -> b) -> (a -> c)
    const ap = f =>
        // Applicative instance for functions.
        // f(x) applied to g(x).
        g => x => f(x)(
            g(x)
        );

    // bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)
    const bimap = f =>
        // Tuple instance of bimap.
        // A tuple of the application of f and g to the
        // first and second values respectively.
        g => tpl => Tuple(f(tpl[0]))(
            g(tpl[1])
        );

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        // A function defined by the right-to-left
        // composition of all the functions in fs.
        fs.reduce(
            (f, g) => x => f(g(x)),
            x => x
        );

    // cycle :: [a] -> Generator [a]
    const cycle = function* (xs) {
        // An infinite repetition of xs,
        // from which an arbitrary prefix
        // may be taken.
        const lng = xs.length;
        let i = 0;

        while (true) {
            yield xs[i];
            i = (1 + i) % lng;
        }
    };

    // first :: (a -> b) -> ((a, c) -> (b, c))
    const first = f =>
        // A simple function lifted to one which applies
        // to a tuple, transforming only its first item.
        xy => {
            const tpl = Tuple(f(xy[0]))(xy[1]);

            return Array.isArray(xy) ? (
                Array.from(tpl)
            ) : tpl;
        };

    // fst :: (a, b) -> a
    const fst = tpl =>
        // First member of a pair.
        tpl[0];

    // isSpace :: Char -> Bool
    const isSpace = c =>
        // True if c is a white space character.
        (/\s/u).test(c);

    // 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;

    // lines :: String -> [String]
    const lines = s =>
        // A list of strings derived from a single
        // string delimited by newline and or CR.
        0 < s.length ? (
            s.split(/[\r\n]+/u)
        ) : [];

    // list :: StringOrArrayLike b => b -> [a]
    const list = xs =>
        // xs itself, if it is an Array,
        // or an Array derived from xs.
        Array.isArray(xs) ? (
            xs
        ) : Array.from(xs || []);

    // lt (<) :: Ord a => a -> a -> Bool
    const lt = a =>
        b => a < b;

    // maximum :: Ord a => [a] -> a
    const maximum = xs => (
        // The largest value in a non-empty list.
        ys => 0 < ys.length ? (
            ys.slice(1).reduce(
                (a, y) => y > a ? (
                    y
                ) : a, ys[0]
            )
        ) : undefined
    )(list(xs));

    // snd :: (a, b) -> b
    const snd = tpl =>
        // Second member of a pair.
        tpl[1];

    // span :: (a -> Bool) -> [a] -> ([a], [a])
    const span = p =>
        // Longest prefix of xs consisting of elements which
        // all satisfy p, tupled with the remainder of xs.
        xs => {
            const i = xs.findIndex(x => !p(x));

            return -1 !== i ? (
                Tuple(xs.slice(0, i))(
                    xs.slice(i)
                )
            ) : Tuple(xs)([]);
        };

    // tail :: [a] -> [a]
    const tail = xs =>
        // A new list consisting of all
        // items of xs except the first.
        "GeneratorFunction" !== xs.constructor
        .constructor.name ? (
            (ys => 0 < ys.length ? ys.slice(1) : [])(
                xs
            )
        ) : (take(1)(xs), xs);

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n =>
        // The first n elements of a list,
        // string of characters, or stream.
        xs => "GeneratorFunction" !== xs
        .constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat(...Array.from({
            length: n
        }, () => {
            const x = xs.next();

            return x.done ? [] : [x.value];
        }));

    // uncons :: [a] -> Maybe (a, [a])
    const uncons = xs => {
        // Just a tuple of the head of xs and its tail,
        // Or Nothing if xs is an empty list.
        const lng = length(xs);

        return (0 < lng) ? (
            Infinity > lng ? (
                // Finite list
                Just(Tuple(xs[0])(xs.slice(1)))
            ) : (() => {
                // Lazy generator
                const nxt = take(1)(xs);

                return 0 < nxt.length ? (
                    Just(Tuple(nxt[0])(xs))
                ) : Nothing();
            })()
        ) : Nothing();
    };

    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    const zipWith = f =>
        // A list with the length of the shorter of
        // xs and ys, defined by zipping with a
        // custom function, rather than with the
        // default tuple constructor.
        xs => ys => {
            const n = Math.min(length(xs), length(ys));

            return Infinity > n ? (
                (([as, bs]) => Array.from({
                    length: n
                }, (_, i) => f(as[i])(
                    bs[i]
                )))([xs, ys].map(
                    take(n)
                ))
            ) : zipWithGen(f)(xs)(ys);
        };

    // zipWithGen :: (a -> b -> c) ->
    // Gen [a] -> Gen [b] -> Gen [c]
    const zipWithGen = f => ga => gb => {
        const go = function* (ma, mb) {
            let
                a = ma,
                b = mb;

            while (!a.Nothing && !b.Nothing) {
                const
                    ta = a.Just,
                    tb = b.Just;

                yield f(fst(ta))(fst(tb));
                a = uncons(snd(ta));
                b = uncons(snd(tb));
            }
        };

        return go(uncons(ga), uncons(gb));
    };

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


Diversity prediction theorem

The   ''wisdom of the crowd''   is the collective opinion of a group of individuals rather than that of a single expert.

Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that assumes independence of the individual judgments from each other.

Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.

Scott E. Page introduced the diversity prediction theorem:
: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''.

Therefore,   when the diversity in a group is large,   the error of the crowd is small.

;Definitions:
::*   Average Individual Error:   Average of the individual squared errors
::*   Collective Error:           Squared error of the collective prediction
::*   Prediction Diversity:       Average squared distance from the individual predictions to the collective prediction
::*   Diversity Prediction Theorem:   ''Given a crowd of predictive models'',     then
::::::   Collective Error   =   Average Individual Error   -   Prediction Diversity

;Task:
For a given   true   value and a number of number of estimates (from a crowd),   show   (here on this page):
:::*   the true value   and   the crowd estimates
:::*   the average error
:::*   the crowd error
:::*   the prediction diversity

Use   (at least)   these two examples:
:::*   a true value of   '''49'''   with crowd estimates of:   ''' 48   47   51'''
:::*   a true value of   '''49'''   with crowd estimates of:   ''' 48   47   51   42'''

;Also see:
:*   Wikipedia entry:   Wisdom of the crowd
:*   University of Michigan: PDF paper         (exists on a web archive,   the ''Wayback Machine'').

Solution:
'use strict';

function sum(array) {
    return array.reduce(function (a, b) {
        return a + b;
    });
}

function square(x) {
    return x * x;
}

function mean(array) {
    return sum(array) / array.length;
}

function averageSquareDiff(a, predictions) {
    return mean(predictions.map(function (x) {
        return square(x - a);
    }));
}

function diversityTheorem(truth, predictions) {
    var average = mean(predictions);
    return {
        'average-error': averageSquareDiff(truth, predictions),
        'crowd-error': square(truth - average),
        'diversity': averageSquareDiff(average, predictions)
    };
}

console.log(diversityTheorem(49, [48,47,51]))
console.log(diversityTheorem(49, [48,47,51,42]))


Dot product

Create a function/use an in-built function, to compute the   '''dot product''',   also known as the   '''scalar product'''   of two vectors.

If possible, make the vectors of arbitrary length.

As an example, compute the dot product of the vectors:
::::     [1,  3, -5]       and
::::     [4,      -2, -1]

If implementing the dot product of two vectors directly:
:::*   each vector must be the same length
:::*   multiply corresponding terms from each vector
:::*   sum the products   (to produce the answer)

;Related task:
*   [[Vector products]]

Solution:
(() => {
    "use strict";

    // ------------------- DOT PRODUCT -------------------

    // dotProduct :: [Num] -> [Num] -> Either Null Num
    const dotProduct = xs =>
        ys => xs.length === ys.length
            ? sum(zipWith(mul)(xs)(ys))
            : null;

    // ---------------------- TEST -----------------------

    // main :: IO ()
    const main = () =>
        dotProduct([1, 3, -5])([4, -2, -1]);

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

    // mul :: Num -> Num -> Num
    const mul = x =>
        y => x * y;

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

    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    const zipWith = f =>
    // A list constructed by zipping with a
    // custom function, rather than with the
    // default tuple constructor.
        xs => ys => xs.map(
            (x, i) => f(x)(ys[i])
        ).slice(
            0, Math.min(xs.length, ys.length)
        );

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


Draw a clock

Draw a clock.

More specific:
# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.

;Key points
* animate simple object
* timed event
* polling system resources
* code clarity

Solution:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        canvas {
            background-color: black;
        }
    </style>
</head>
<body>
    <canvas></canvas>
    <script>
        var canvas = document.querySelector("canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var g = canvas.getContext("2d");

        // which leds are on or off for each digit
        var masks = ["1110111", "0010010", "1011101", "1011011", "0111010",
            "1101011", "1101111", "1010010", "1111111", "1111011"];

        // horizontal and vertical layouts in scalable units
        var vertices = [
            [
                [0, 0], [1, 1], [7, 1], [8, 0], [7, -1], [1, -1]
            ],
            [
                [0, 0], [-1, 1], [-1, 7], [0, 8], [1, 7], [1, 1]
            ]
        ];

        function Led(x, y, idx, ox, oy) {
            // starting points in scalable units
            this.x = x;
            this.y = y;

            // horizontal or vertical layout
            this.idx = idx;

            // pixel values to create small gaps between the leds
            this.offset_x = ox;
            this.offset_y = oy;
        }

        var leds = [];
        leds.push(new Led(0, 0, 0, 0, -1));
        leds.push(new Led(0, 0, 1, -1, 0));
        leds.push(new Led(8, 0, 1, 1, 0));
        leds.push(new Led(0, 8, 0, 0, 1));
        leds.push(new Led(0, 8, 1, -1, 2));
        leds.push(new Led(8, 8, 1, 1, 2));
        leds.push(new Led(0, 16, 0, 0, 3));

        var onColor, offColor;

        function drawDigitalClock(color1, color2, size) {

            var clockWidth = (6 * 15 + 2 * 10) * size;
            var clockHeight = 20 * size;
            var x = (canvas.width - clockWidth) / 2;
            var y = (canvas.height - clockHeight) / 2;

            onColor = color1;
            offColor = color2;

            g.clearRect(0, 0, canvas.width, canvas.height);

            var date = new Date();
            var segments = [date.getHours(), date.getMinutes(), date.getSeconds()];

            segments.forEach(function (value, index) {
                x = drawDigits(x, y, size, value);
                if (index < 2) {
                    x = drawSeparator(x, y, size);
                }
            });
        }

        function drawDigits(x, y, size, timeUnit) {

            var digit1 = Math.floor(timeUnit / 10);
            var digit2 = timeUnit % 10;

            x = drawLeds(x, y, size, masks[digit1]);
            x = drawLeds(x, y, size, masks[digit2]);

            return x;
        }

        function drawSeparator(x, y, size) {

            g.fillStyle = onColor;
            g.fillRect(x + 0.5 * size, y + 3 * size, 2 * size, 2 * size);
            g.fillRect(x + 0.5 * size, y + 10 * size, 2 * size, 2 * size);

            return x + size * 10;
        }

        function drawLeds(x, y, size, mask) {

            leds.forEach(function (led, i) {

                g.fillStyle = mask[i] == '1' ? onColor : offColor;

                var xx = x + led.x * size + led.offset_x;
                var yy = y + led.y * size + led.offset_y;

                drawLed(xx, yy, size, vertices[led.idx]);
            });

            return x + size * 15;
        }

        function drawLed(x, y, size, vertices) {

            g.beginPath();
            g.moveTo(x, y);

            vertices.forEach(function (vertex) {
                g.lineTo(x + vertex[0] * size, y + vertex[1] * size);
            });

            g.closePath();
            g.fill();
        }

        setInterval(drawDigitalClock, 1000, "#00FF00", "#002200", 12);
    </script>

</body>
</html>


Draw a rotating cube

Task
Draw a rotating cube.

It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.

;Related tasks
* Draw a cuboid
* write language name in 3D ASCII

Solution:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        canvas {
            background-color: black;
        }
    </style>
</head>
<body>
    <canvas></canvas>
    <script>
        var canvas = document.querySelector("canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var g = canvas.getContext("2d");

        var nodes = [[-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1],
        [1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1]];

        var edges = [[0, 1], [1, 3], [3, 2], [2, 0], [4, 5], [5, 7], [7, 6],
        [6, 4], [0, 4], [1, 5], [2, 6], [3, 7]];

        function scale(factor0, factor1, factor2) {
            nodes.forEach(function (node) {
                node[0] *= factor0;
                node[1] *= factor1;
                node[2] *= factor2;
            });
        }

        function rotateCuboid(angleX, angleY) {

            var sinX = Math.sin(angleX);
            var cosX = Math.cos(angleX);

            var sinY = Math.sin(angleY);
            var cosY = Math.cos(angleY);

            nodes.forEach(function (node) {
                var x = node[0];
                var y = node[1];
                var z = node[2];

                node[0] = x * cosX - z * sinX;
                node[2] = z * cosX + x * sinX;

                z = node[2];

                node[1] = y * cosY - z * sinY;
                node[2] = z * cosY + y * sinY;
            });
        }

        function drawCuboid() {
            g.save();

            g.clearRect(0, 0, canvas.width, canvas.height);
            g.translate(canvas.width / 2, canvas.height / 2);
            g.strokeStyle = "#FFFFFF";
            g.beginPath();

            edges.forEach(function (edge) {
                var p1 = nodes[edge[0]];
                var p2 = nodes[edge[1]];
                g.moveTo(p1[0], p1[1]);
                g.lineTo(p2[0], p2[1]);
            });

            g.closePath();
            g.stroke();

            g.restore();
        }

        scale(200, 200, 200);
        rotateCuboid(Math.PI / 4, Math.atan(Math.sqrt(2)));

        setInterval(function() {
            rotateCuboid(Math.PI / 180, 0);
            drawCuboid();
        }, 17);

    </script>

</body>
</html>


Draw a sphere

{{requires|Graphics}}

;Task:
Draw a sphere.

The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.

Either static or rotational projection is acceptable for this task.

;Related tasks:
* draw a cuboid
* draw a rotating cube
* write language name in 3D ASCII
* draw a Deathstar

Solution:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Draw a sphere</title>

R=<input type="range" id="R" name="R" min="5" max="500" value="200" step="5" onchange="document.getElementById('lR').innerHTML=gR=parseFloat(this.value);draw_sphere(gR,gk,gambient)">
200

k=<input type="range" id="k" name="k" min="0" max="10" value="4" step=".25" onchange="document.getElementById('lk').innerHTML=gk=parseFloat(this.value);draw_sphere(gR,gk,gambient)">
4

ambient=<input type="range" id="ambient" name="ambient" min="0" max="1" value=".2" step=".05" onchange="document.getElementById('lambient').innerHTML=gambient=parseFloat(this.value);draw_sphere(gR,gk,gambient)">
0.2

<canvas id="c">Unsupportive browser...</canvas>


Dutch national flag problem

The Dutch national flag is composed of three coloured bands in the order:
::*   red     (top)
::*   then white,   and
::*   lastly blue   (at the bottom).

The problem posed by Edsger Dijkstra is:
:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...

;Task
# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.
# Sort the balls in a way idiomatic to your language.
# Check the sorted balls ''are'' in the order of the Dutch national flag.

;C.f.:
* Dutch national flag problem
* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)

Solution:
const dutchNationalFlag = () => {

  /**
   * Return the name of the given number in this way:
   * 0 = Red
   * 1 = White
   * 2 = Blue
   * @param {!number} e
   */
  const name = e => e > 1 ? 'Blue' : e > 0 ? 'White' : 'Red';

  /**
   * Given an array of numbers return true if each number is bigger than
   * or the same as the previous
   * @param {!Array<!number>} arr
   */
  const isSorted = arr => arr.every((e,i) => e >= arr[Math.max(i-1, 0)]);

  /**
   * Generator that keeps yielding a random int between 0(inclusive) and
   * max(exclusive), up till n times, and then is done.
   * @param max
   * @param n
   */
  function* randomGen (max, n) {
    let i = 0;
    while (i < n) {
      i += 1;
      yield Math.floor(Math.random() * max);
    }
  }

  /**
   * An array of random integers between 0 and 3
   * @type {[!number]}
   */
  const mixedBalls = [...(randomGen(3, 22))];

  /**
   * Sort the given array into 3 sub-arrays and then concatenate those.
   */
  const sortedBalls = mixedBalls
    .reduce((p,c) => p[c].push(c) && p, [[],[],[]])
    .reduce((p,c) => p.concat(c), []);

  /**
   * A verbatim implementation of the Wikipedia pseudo-code
   * @param {!Array<!number>} A
   * @param {!number} mid The value of the 'mid' number. In our case 1 as
   * low is 0 and high is 2
   */
  const dutchSort = (A, mid) => {
    let i = 0;
    let j = 0;
    let n = A.length - 1;
    while(j <= n) {
      if (A[j] < mid) {
        [A[i], A[j]] = [A[j], A[i]];
        i += 1;
        j += 1;
      } else if (A[j] > mid) {
        [A[j], A[n]] = [A[n], A[j]];
        n -= 1
      } else {
        j += 1;
      }
    }
  };

  console.log(`Mixed balls       : ${mixedBalls.map(name).join()}`);
  console.log(`Is sorted: ${isSorted(mixedBalls)}`);

  console.log(`Sorted balls      : ${sortedBalls.map(name).join()}`);
  console.log(`Is sorted: ${isSorted(sortedBalls)}`);

  // Only do the dutch sort now as it mutates the mixedBalls array in place.
  dutchSort(mixedBalls, 1);
  console.log(`Dutch Sorted balls: ${mixedBalls.map(name).join()}`);
  console.log(`Is sorted: ${isSorted(mixedBalls)}`);
};
dutchNationalFlag();


Egyptian division

Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of [[Ethiopian multiplication]]

'''Algorithm:'''

Given two numbers where the '''dividend''' is to be divided by the '''divisor''':

# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
# Continue with successive i'th rows of 2^i and 2^i * divisor.
# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''
# Consider each row of the table, in the ''reverse'' order of its construction.
# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).

'''Example: 580 / 34'''

''' Table creation: '''

::: {| class="wikitable"
! powers_of_2
! doublings
|-
| 1
| 34
|-
| 2
| 68
|-
| 4
| 136
|-
| 8
| 272
|-
| 16
| 544
|}

''' Initialization of sums: '''

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| 16
| 544
|

|

|-
|
|
| 0
| 0
|}

''' Considering table rows, bottom-up: '''

When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
| 16
| 544
|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
| 16
| 544
|-
| '''16'''
| '''544'''
|

|

|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
| 16
| 544
|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
|

|

|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
| 16
| 544
|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
|

|

|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| '''1'''
| '''34'''
| 17
| 578
|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
|

|

|}

;Answer:
So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.

;Task:
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.

* Functions should be clear interpretations of the algorithm.
* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.

;Related tasks:
:*   Egyptian fractions

;References:
:*   Egyptian Number System

Solution:
(() => {
    'use strict';

    // EGYPTIAN DIVISION --------------------------------

    // eqyptianQuotRem :: Int -> Int -> (Int, Int)
    const eqyptianQuotRem = (m, n) => {
        const expansion = ([i, x]) =>
            x > m ? (
                Nothing()
            ) : Just([
                [i, x],
                [i + i, x + x]
            ]);
        const collapse = ([i, x], [q, r]) =>
            x < r ? (
                [q + i, r - x]
            ) : [q, r];
        return foldr(
            collapse,
            [0, m],
            unfoldr(expansion, [1, n])
        );
    };

    // TEST ---------------------------------------------

    // main :: IO ()
    const main = () =>
        showLog(
            eqyptianQuotRem(580, 34)
        );
        // -> [17, 2]

    // GENERIC FUNCTIONS --------------------------------

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

    // flip :: (a -> b -> c) -> b -> a -> c
    const flip = f =>
        1 < f.length ? (
            (a, b) => f(b, a)
        ) : (x => y => f(y)(x));

    // foldr :: (a -> b -> b) -> b -> [a] -> b
    const foldr = (f, a, xs) => xs.reduceRight(flip(f), a);

    // unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
    const unfoldr = (f, v) => {
        let
            xr = [v, v],
            xs = [];
        while (true) {
            const mb = f(xr[1]);
            if (mb.Nothing) {
                return xs
            } else {
                xr = mb.Just;
                xs.push(xr[0])
            }
        }
    };

    // showLog :: a -> IO ()
    const showLog = (...args) =>
        console.log(
            args
            .map(JSON.stringify)
            .join(' -> ')
        );

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


Elementary cellular automaton

An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors.  Those three values can be encoded with three bits.

The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order.  Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.

;Task:
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state.  You can demonstrate your solution with any automaton of your choice.

The space state should ''wrap'':  this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.

This task is basically a generalization of [[one-dimensional cellular automata]].

;See also
* Cellular automata (natureofcode.com)

Solution:
const alive = '#';
const dead = '.';

// ------------------------------------------------------------[ Bit banging ]--
const setBitAt = (val, idx) => BigInt(val) | (1n << BigInt(idx));
const clearBitAt = (val, idx) => BigInt(val) & ~(1n << BigInt(idx));
const getBitAt = val => idx => (BigInt(val) >> BigInt(idx)) & 1n;
const hasBitAt = val => idx => ((BigInt(val) >> BigInt(idx)) & 1n) === 1n;

// ----------------------------------------------------------------[ Utility ]--
const makeArr = n => Array(n).fill(0);
const reverse = x => Array.from(x).reduce((p, c) => [c, ...p], []);
const numToLine = width => int => {
  const test = hasBitAt(int);
  const looper = makeArr(width);
  return reverse(looper.map((_, i) => test(i) ? alive : dead)).join('');
}

// -------------------------------------------------------------------[ Main ]--
const displayCA = (rule, width, lines, startIndex) => {
  const result = [];
  result.push(`Rule:${rule} Width:${width} Gen:${lines}\n`)
  const ruleTest = hasBitAt(rule);
  const lineLoop = makeArr(lines);
  const looper = makeArr(width);
  const pLine = numToLine(width);

  let nTarget = setBitAt(0n, startIndex);
  result.push(pLine(nTarget));
  lineLoop.forEach(() => {
    const bitTest = getBitAt(nTarget);
    looper.forEach((e, i) => {
      const l = bitTest(i === 0 ? width - 1 : i - 1);
      const m = bitTest(i);
      const r = bitTest(i === width - 1 ? 0 : i + 1);
      nTarget = ruleTest(
          parseInt([l, m, r].join(''), 2))
          ? setBitAt(nTarget, i)
          : clearBitAt(nTarget, i);
    });
    result.push(pLine(nTarget));
  });
  return result.join('\n');
}

displayCA(90, 57, 31, 28);


Empty directory

Starting with a path to some directory, determine whether the directory is empty.

An empty directory contains no files nor subdirectories.
With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.

Solution: The ECMAScript standard itself defines no IO interface – the following example makes use of the Node.js file IO library.


Equilibrium index

An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.

For example, in a sequence   A:

:::::   A_0 = -7
:::::   A_1 =  1
:::::   A_2 =  5
:::::   A_3 =  2
:::::   A_4 = -4
:::::   A_5 =  3
:::::   A_6 =  0

3   is an equilibrium index, because:

:::::   A_0 + A_1 + A_2 = A_4 + A_5 + A_6

6   is also an equilibrium index, because:

:::::   A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0

(sum of zero elements is zero)

7   is not an equilibrium index, because it is not a valid index of sequence A.

;Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).

Assume that the sequence may be very long.

Solution:
function equilibrium(a) {
  var N = a.length, i, l = [], r = [], e = []
  for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i<N; i++)
    l[i] = l[i - 1] + a[i], r[N - i - 1] = r[N - i] + a[N - i - 1]
  for (i = 0; i < N; i++)
    if (l[i] === r[i]) e.push(i)
  return e
}

// test & output
[ [-7, 1, 5, 2, -4, 3, 0], // 3, 6
  [2, 4, 6], // empty
  [2, 9, 2], // 1
  [1, -1, 1, -1, 1, -1, 1], // 0,1,2,3,4,5,6
  [1], // 0
  [] // empty
].forEach(function(x) {
  console.log(equilibrium(x))
});


Esthetic numbers

An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.

;E.G.

:* '''12''' is an esthetic number. One and two differ by 1.

:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.

:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.

These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.

Esthetic numbers are also sometimes referred to as stepping numbers.

;Task

:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.

:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)

:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.

:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.

;Related task:
*   numbers with equal rises and falls

;See also:
:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
:;*Numbers Aplenty - Esthetic numbers
:;*Geeks for Geeks - Stepping numbers

Solution:
function isEsthetic(inp, base = 10) {
  let arr = inp.toString(base).split('');
  if (arr.length == 1) return false;
  for (let i = 0; i < arr.length; i++)
    arr[i] = parseInt(arr[i], base);
  for (i = 0; i < arr.length-1; i++)
    if (Math.abs(arr[i]-arr[i+1]) !== 1) return false;
  return true;
}

function collectEsthetics(base, range) {
  let out = [], x;
  if (range) {
    for (x = range[0]; x < range[1]; x++)
      if (isEsthetic(x)) out.push(x);
    return out;
  } else {
    x = 1;
    while (out.length < base*6) {
      s = x.toString(base);
      if (isEsthetic(s, base)) out.push(s.toUpperCase());
      x++;
    }
    return out.slice(base*4);
  }
}

// main
let d = new Date();
for (let x = 2; x <= 36; x++) { // we put b17 .. b36 on top, because we can
  console.log(`${x}:`);
  console.log( collectEsthetics(x),
    (new Date() - d) / 1000 + ' s');
}
console.log( collectEsthetics(10, [1000, 9999]),
  (new Date() - d) / 1000 + ' s' );

console.log( collectEsthetics(10, [1e8, 1.3e8]),
  (new Date() - d) / 1000 + ' s' );


Esthetic numbers

Solution:
(() => {
    "use strict";

    // -------- ESTHETIC NUMBERS IN A GIVEN BASE ---------

    // estheticNumbersInBase :: Int -> [Int]
    const estheticNumbersInBase = b =>
        // An infinite sequence of numbers which
        // are esthetic in the given base.

        tail(fmapGen(x => x[0])(
            iterate(([, queue]) => {
                const [num, lsd] = queue[0];
                const
                    newDigits = [lsd - 1, lsd + 1]
                    .flatMap(
                        d => (d < b && d >= 0) ? (
                            [d]
                        ) : []
                    );

                return Tuple(num)(
                    queue.slice(1).concat(
                        newDigits.flatMap(d => [
                            Tuple((num * b) + d)(d)
                        ])
                    )
                );
            })(
                Tuple()(
                    enumFromTo(1)(b - 1).flatMap(
                        d => [Tuple(d)(d)]
                    )
                )
            )
        ));

    // ---------------------- TESTS ----------------------
    const main = () => {

        const samples = b => {
            const
                i = b * 4,
                j = b * 6;

            return unlines([
                `Esthetics [${i}..${j}] for base ${b}:`,
                ...chunksOf(10)(
                    compose(drop(i - 1), take(j))(
                        estheticNumbersInBase(b)
                    ).map(n => n.toString(b))
                )
                .map(unwords)
            ]);
        };

        const takeInRange = ([a, b]) =>
            compose(
                dropWhile(x => x < a),
                takeWhileGen(x => x <= b)
            );

        return [
            enumFromTo(2)(16)
            .map(samples)
            .join("\n\n"),
            [
                Tuple(1000)(9999),
                Tuple(100000000)(130000000)
            ]
            .map(
                ([lo, hi]) => unlines([
                    `Base 10 Esthetics in range [${lo}..${hi}]:`,
                    unlines(
                        chunksOf(6)(
                            takeInRange([lo, hi])(
                                estheticNumbersInBase(10)
                            )
                        )
                        .map(unwords)
                    )
                ])
            ).join("\n\n")
        ].join("\n\n");
    };

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

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a =>
        b => ({
            type: "Tuple",
            "0": a,
            "1": b,
            length: 2,
            *[Symbol.iterator]() {
                for (const k in this) {
                    if (!isNaN(k)) {
                        yield this[k];
                    }
                }
            }
        });

    // chunksOf :: Int -> [a] -> [[a]]
    const chunksOf = n => {
        // xs split into sublists of length n.
        // The last sublist will be short if n
        // does not evenly divide the length of xs .
        const go = xs => {
            const chunk = xs.slice(0, n);

            return 0 < chunk.length ? (
                [chunk].concat(
                    go(xs.slice(n))
                )
            ) : [];
        };

        return go;
    };

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        // A function defined by the right-to-left
        // composition of all the functions in fs.
        fs.reduce(
            (f, g) => x => f(g(x)),
            x => x
        );

    // drop :: Int -> [a] -> [a]
    // drop :: Int -> Generator [a] -> Generator [a]
    // drop :: Int -> String -> String
    const drop = n =>
        xs => Infinity > length(xs) ? (
            xs.slice(n)
        ) : (take(n)(xs), xs);

    // dropWhile :: (a -> Bool) -> [a] -> [a]
    // dropWhile :: (Char -> Bool) -> String -> String
    const dropWhile = p =>
        // The suffix remaining after takeWhile p xs.
        xs => {
            const n = xs.length;

            return xs.slice(
                0 < n ? until(
                    i => n === i || !p(xs[i])
                )(i => 1 + i)(0) : 0
            );
        };

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = m =>
        n => Array.from({
            length: 1 + n - m
        }, (_, i) => m + i);

    // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
    const fmapGen = f =>
        // The map of f over a stream of generator values.
        function* (gen) {
            let v = gen.next();

            while (!v.done) {
                yield f(v.value);
                v = gen.next();
            }
        };

    // iterate :: (a -> a) -> a -> Gen [a]
    const iterate = f =>
        // An infinite list of repeated
        // applications of f to x.
        function* (x) {
            let v = x;

            while (true) {
                yield v;
                v = f(v);
            }
        };

    // 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;

    // tail :: [a] -> [a]
    const tail = xs =>
        // A new list consisting of all
        // items of xs except the first.
        "GeneratorFunction" !== xs.constructor
        .constructor.name ? (
            (ys => 0 < ys.length ? ys.slice(1) : [])(
                xs
            )
        ) : (take(1)(xs), xs);

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n =>
        // The first n elements of a list,
        // string of characters, or stream.
        xs => "GeneratorFunction" !== xs
        .constructor.constructor.name ? (
            xs.slice(0, n)
        ) : Array.from({
            length: n
        }, () => {
            const x = xs.next();

            return x.done ? [] : [x.value];
        }).flat();

    // takeWhileGen :: (a -> Bool) -> Gen [a] -> [a]
    const takeWhileGen = p => xs => {
        const ys = [];
        let
            nxt = xs.next(),
            v = nxt.value;

        while (!nxt.done && p(v)) {
            ys.push(v);
            nxt = xs.next();
            v = nxt.value;
        }

        return ys;
    };

    // unlines :: [String] -> String
    const unlines = xs =>
        // A single string formed by the intercalation
        // of a list of strings with the newline character.
        xs.join("\n");

    // until :: (a -> Bool) -> (a -> a) -> a -> a
    const until = p =>
        // The value resulting from repeated applications
        // of f to the seed value x, terminating when
        // that result returns true for the predicate p.
        f => x => {
            let v = x;

            while (!p(v)) {
                v = f(v);
            }

            return v;
        };

    // unwords :: [String] -> String
    const unwords = xs =>
        // A space-separated string derived
        // from a list of words.
        xs.join(" ");

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