Euler's sum of powers conjecture

There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.

This conjecture is called Euler's sum of powers conjecture and can be stated as such:

:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.

In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.

The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.

Related tasks are:
* [[Pythagorean quadruples]].
* [[Pythagorean triples]].

Solution:
var eulers_sum_of_powers = function (iMaxN) {

    var aPow5 = [];
    var oPow5ToN = {};

    for (var iP = 0; iP <= iMaxN; iP++) {
        var iPow5 = Math.pow(iP, 5);
        aPow5.push(iPow5);
        oPow5ToN[iPow5] = iP;
    }

    for (var i0 = 1; i0 <= iMaxN; i0++) {
        for (var i1 = 1; i1 <= i0; i1++) {
            for (var i2 = 1; i2 <= i1; i2++) {
                for (var i3 = 1; i3 <= i2; i3++) {
                    var iPow5Sum = aPow5[i0] + aPow5[i1] + aPow5[i2] + aPow5[i3];
                    if (typeof oPow5ToN[iPow5Sum] != 'undefined') {
                        return {
                            i0: i0,
                            i1: i1,l
                            i2: i2,
                            i3: i3,
                            iSum: oPow5ToN[iPow5Sum]
                        };
                    }
                }
            }
        }
    }

};

var oResult = eulers_sum_of_powers(250);

console.log(oResult.i0 + '^5 + ' + oResult.i1 + '^5 + ' + oResult.i2 +
    '^5 + ' + oResult.i3 + '^5 = ' + oResult.iSum + '^5');


Euler's sum of powers conjecture

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

    const main = () => {

        const
            iFrom = 1,
            iTo = 249,
            xs = enumFromTo(1, 249),
            p5 = x => Math.pow(x, 5);

        const
            // powerMap :: Dict Int Int
            powerMap = mapFromList(
                zip(map(p5, xs), xs)
            ),
            // sumMap :: Dict Int (Int, Int)
            sumMap = mapFromList(
                bind(
                    xs,
                    x => bind(
                        tail(xs),
                        y => Tuple(
                            p5(x) + p5(y),
                            Tuple(x, y)
                        )
                    )
                )
            );

        // mbExample :: Maybe (Int, Int)
        const mbExample = find(
            tpl => member(fst(tpl) - snd(tpl), sumMap),
            bind(
                map(x => parseInt(x, 10),
                    keys(powerMap)
                ),
                p => bind(
                    takeWhile(
                        x => x < p,
                        map(x => parseInt(x, 10),
                            keys(sumMap)
                        )
                    ),
                    s => [Tuple(p, s)]
                )
            )
        );

        // showExample :: (Int, Int) -> String
        const showExample = tpl => {
            const [p, s] = Array.from(tpl);
            const [a, b] = Array.from(sumMap[p - s]);
            const [c, d] = Array.from(sumMap[s]);
            return 'Counter-example found:\n' + intercalate(
                '^5 + ',
                map(str, [a, b, c, d])
            ) + '^5 = ' + str(powerMap[p]) + '^5';
        };

        return maybe(
            'No counter-example found',
            showExample,
            mbExample
        );
    };

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

    // bind (>>=) :: [a] -> (a -> [b]) -> [b]
    const bind = (xs, mf) => [].concat.apply([], xs.map(mf));

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

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

    // find :: (a -> Bool) -> [a] -> Maybe a
    const find = (p, xs) => {
        for (let i = 0, lng = xs.length; i < lng; i++) {
            if (p(xs[i])) return Just(xs[i]);
        }
        return Nothing();
    };

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

    // intercalate :: [a] -> [[a]] -> [a]
    // intercalate :: String -> [String] -> String
    const intercalate = (sep, xs) =>
        0 < xs.length && 'string' === typeof sep &&
        'string' === typeof xs[0] ? (
            xs.join(sep)
        ) : concat(intersperse(sep, xs));

    // intersperse(0, [1,2,3]) -> [1, 0, 2, 0, 3]

    // intersperse :: a -> [a] -> [a]
    // intersperse :: Char -> String -> String
    const intersperse = (sep, xs) => {
        const bln = 'string' === typeof xs;
        return xs.length > 1 ? (
            (bln ? concat : x => x)(
                (bln ? (
                    xs.split('')
                ) : xs)
                .slice(1)
                .reduce((a, x) => a.concat([sep, x]), [xs[0]])
            )) : xs;
    };

    // keys :: Dict -> [String]
    const keys = Object.keys;

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

    // length :: [a] -> Int
    const length = xs =>
        (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);

    // mapFromList :: [(k, v)] -> Dict
    const mapFromList = kvs =>
        kvs.reduce(
            (a, kv) => {
                const k = kv[0];
                return Object.assign(a, {
                    [
                        (('string' === typeof k) && k) || JSON.stringify(k)
                    ]: kv[1]
                });
            }, {}
        );

    // Default value (v) if m.Nothing, or f(m.Just)

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

    // member :: Key -> Dict -> Bool
    const member = (k, dct) => k in dct;

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

    // str :: a -> String
    const str = x => x.toString();

    // tail :: [a] -> [a]
    const tail = xs => 0 < xs.length ? xs.slice(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];
        }));

    // takeWhile :: (a -> Bool) -> [a] -> [a]
    // takeWhile :: (Char -> Bool) -> String -> String
    const takeWhile = (p, xs) =>
        xs.constructor.constructor.name !==
        'GeneratorFunction' ? (() => {
            const lng = xs.length;
            return 0 < lng ? xs.slice(
                0,
                until(
                    i => lng === i || !p(xs[i]),
                    i => 1 + i,
                    0
                )
            ) : [];
        })() : takeWhileGen(p, xs);

    // until :: (a -> Bool) -> (a -> a) -> a -> a
    const until = (p, f, x) => {
        let v = x;
        while (!p(v)) v = f(v);
        return v;
    };

    // Use of `take` and `length` here allows for zipping with non-finite
    // lists - i.e. generators like cycle, repeat, iterate.

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

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


Even or odd

Test whether an integer is even or odd.

There is more than one way to solve this task:

* Use the even and odd predicates, if the language provides them.
* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.
* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.
* Use modular congruences:
** ''i''  0 (mod 2) iff ''i'' is even.
** ''i''  1 (mod 2) iff ''i'' is odd.

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

    // even : Integral a => a -> Bool
    const even = x => (x % 2) === 0;

    // odd : Integral a => a -> Bool
    const odd = x => !even(x);

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

    // show :: a -> String
    const show = JSON.stringify;

    // xs :: [Int]
    const xs = range(-6, 6);

    return show([xs.filter(even), xs.filter(odd)]);
})();


Evolutionary algorithm

Starting with:
* The target string: "METHINKS IT IS LIKE A WEASEL".
* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
* A fitness function that computes the 'closeness' of its argument to the target string.
* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
:* repeat until the parent converges, (hopefully), to the target.

;See also:
*   Wikipedia entry:   Weasel algorithm.
*   Wikipedia entry:   Evolutionary algorithm.

Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions

A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.

Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"

 (:* repeat until the parent converges, (hopefully), to the target.

Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!

As illustration of this error, the code for 8th has the following remark.

 Create a new string based on the TOS, '''changing randomly any characters which
 don't already match the target''':

''NOTE:'' this has been changed, the 8th version is completely random now

Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!

To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.

Solution:
// ------------------------------------- Cross-browser Compatibility -------------------------------------

/* Compatibility code to reduce an array
 * Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce
 */
if (!Array.prototype.reduce) {
    Array.prototype.reduce = function (fun /*, initialValue */ ) {
        "use strict";

        if (this === void 0 || this === null) throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== "function") throw new TypeError();

        // no value to return if no initial value and an empty array
        if (len == 0 && arguments.length == 1) throw new TypeError();

        var k = 0;
        var accumulator;
        if (arguments.length >= 2) {
            accumulator = arguments[1];
        } else {
            do {
                if (k in t) {
                    accumulator = t[k++];
                    break;
                }

                // if array contains no values, no initial value to return
                if (++k >= len) throw new TypeError();
            }
            while (true);
        }

        while (k < len) {
            if (k in t) accumulator = fun.call(undefined, accumulator, t[k], k, t);
            k++;
        }

        return accumulator;
    };
}

/* Compatibility code to map an array
 * Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Map
 */
if (!Array.prototype.map) {
    Array.prototype.map = function (fun /*, thisp */ ) {
        "use strict";

        if (this === void 0 || this === null) throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== "function") throw new TypeError();

        var res = new Array(len);
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in t) res[i] = fun.call(thisp, t[i], i, t);
        }

        return res;
    };
}

/* ------------------------------------- Generator -------------------------------------
 * Generates a fixed length gene sequence via a gene strategy object.
 * The gene strategy object must have two functions:
 *	- "create": returns create a new gene
 *	- "mutate(existingGene)": returns mutation of an existing gene
 */
function Generator(length, mutationRate, geneStrategy) {
    this.size = length;
    this.mutationRate = mutationRate;
    this.geneStrategy = geneStrategy;
}

Generator.prototype.spawn = function () {
    var genes = [],
        x;
    for (x = 0; x < this.size; x += 1) {
        genes.push(this.geneStrategy.create());
    }
    return genes;
};

Generator.prototype.mutate = function (parent) {
    return parent.map(function (char) {
        if (Math.random() > this.mutationRate) {
            return char;
        }
        return this.geneStrategy.mutate(char);
    }, this);
};

/* ------------------------------------- Population -------------------------------------
 * Helper class that holds and spawns a new population.
 */
function Population(size, generator) {
    this.size = size;
    this.generator = generator;

    this.population = [];
    // Build initial popuation;
    for (var x = 0; x < this.size; x += 1) {
        this.population.push(this.generator.spawn());
    }
}

Population.prototype.spawn = function (parent) {
    this.population = [];
    for (var x = 0; x < this.size; x += 1) {
        this.population.push(this.generator.mutate(parent));
    }
};

/* ------------------------------------- Evolver -------------------------------------
 * Attempts to converge a population based a fitness strategy object.
 * The fitness strategy object must have three function
 *	- "score(individual)": returns a score for an individual.
 *	- "compare(scoreA, scoreB)": return true if scoreA is better (ie more fit) then scoreB
 *	- "done( score )": return true if score is acceptable (ie we have successfully converged).
 */
function Evolver(size, generator, fitness) {
    this.done = false;
    this.fitness = fitness;
    this.population = new Population(size, generator);
}

Evolver.prototype.getFittest = function () {
    return this.population.population.reduce(function (best, individual) {
        var currentScore = this.fitness.score(individual);
        if (best === null || this.fitness.compare(currentScore, best.score)) {
            return {
                score: currentScore,
                individual: individual
            };
        } else {
            return best;
        }
    }, null);
};

Evolver.prototype.doGeneration = function () {
    this.fittest = this.getFittest();
    this.done = this.fitness.done(this.fittest.score);
    if (!this.done) {
        this.population.spawn(this.fittest.individual);
    }
};

Evolver.prototype.run = function (onCheckpoint, checkPointFrequency) {
    checkPointFrequency = checkPointFrequency || 10; // Default to Checkpoints every 10 generations
    var generation = 0;
    while (!this.done) {
        this.doGeneration();
        if (generation % checkPointFrequency === 0) {
            onCheckpoint(generation, this.fittest);
        }
        generation += 1;
    }
    onCheckpoint(generation, this.fittest);
    return this.fittest;
};

// ------------------------------------- Exports -------------------------------------
window.Generator = Generator;
window.Evolver = Evolver;

// helper utitlity to combine elements of two arrays.
Array.prototype.zip = function (b, func) {
    var result = [],
        max = Math.max(this.length, b.length),
        x;
    for (x = 0; x < max; x += 1) {
        result.push(func(this[x], b[x]));
    }
    return result;
};

var target = "METHINKS IT IS LIKE A WEASEL", geneStrategy, fitness, target, generator, evolver, result;

geneStrategy = {
    // The allowed character set (as an array)
    characterSet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".split(""),

    /*
        Pick a random character from the characterSet
    */
    create: function getRandomGene() {
        var randomNumber = Math.floor(Math.random() * this.characterSet.length);
        return this.characterSet[randomNumber];
    }
};
geneStrategy.mutate = geneStrategy.create; // Our mutation stragtegy is to simply get a random gene
fitness = {
    // The target (as an array of characters)
    target: target.split(""),
    equal: function (geneA, geneB) {
        return (geneA === geneB ? 0 : 1);
    },
    sum: function (runningTotal, value) {
        return runningTotal + value;
    },

    /*
        We give one point to for each corect letter
    */
    score: function (genes) {
        var diff = genes.zip(this.target, this.equal); // create an array of ones and zeros
        return diff.reduce(this.sum, 0); // Sum the array values together.
    },
    compare: function (scoreA, scoreB) {
        return scoreA <= scoreB; // Lower scores are better
    },
    done: function (score) {
        return score === 0; // We have matched the target string.
    }
};

generator = new Generator(target.length, 0.05, geneStrategy);
evolver = new Evolver(100, generator, fitness);

function showProgress(generation, fittest) {
    document.write("Generation: " + generation + ", Best: " + fittest.individual.join("") + ", fitness:" + fittest.score + "<br>");
}
result = evolver.run(showProgress);


Execute HQ9+

Implement a   ''' [[HQ9+]] '''   interpreter or compiler.

Solution:
function hq9plus(code) {
  var out = '';
  var acc = 0;

  for (var i=0; i<code.length; i++) {
    switch (code.charAt(i)) {
      case 'H': out += "hello, world\n"; break;
      case 'Q': out += code + "\n"; break;
      case '9':
        for (var j=99; j>1; j--) {
          out += j + " bottles of beer on the wall, " + j + " bottles of beer.\n";
          out += "Take one down and pass it around, " + (j-1) + " bottles of beer.\n\n";
        }
        out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
            "Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
            "No more bottles of beer on the wall, no more bottles of beer.\n" +
            "Go to the store and buy some more, 99 bottles of beer on the wall.\n";
        break;
      case '+': acc++; break;
    }
  }
  return out;
}


FASTA format

In FASTA.

A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.

;Task:
Write a program that reads a FASTA file such as:

>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED

Solution:
const fs = require("fs");
const readline = require("readline");

const args = process.argv.slice(2);
if (!args.length) {
    console.error("must supply file name");
    process.exit(1);
}

const fname = args[0];

const readInterface = readline.createInterface({
    input: fs.createReadStream(fname),
    console: false,
});

let sep = "";
readInterface.on("line", (line) => {
    if (line.startsWith(">")) {
        process.stdout.write(sep);
        sep = "\n";
        process.stdout.write(line.substring(1) + ": ");
    } else {
        process.stdout.write(line);
    }
});

readInterface.on("close", () => process.stdout.write("\n"));


Fairshare between two and more

The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)

The Thue-Morse sequence of ones-and-zeroes can be generated by:
:''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"''

;Sharing fairly between two or more:
Use this method:
:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''

;Task
Counting from zero;   using a function/method/routine to express an integer count in base '''b''',
sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.

Show the first 25 terms of the fairshare sequence:
:*   For two people:
:*   For three people
:*   For five people
:*   For eleven people

;Related tasks:
:*   [[Non-decimal radices/Convert]]
:*   [[Thue-Morse]]

;See also:
:*   A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))

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

    // thueMorse :: Int -> [Int]
    const thueMorse = base =>
        // Thue-Morse sequence for a given base
        fmapGen(baseDigitsSumModBase(base))(
            enumFrom(0)
        )

    // baseDigitsSumModBase :: Int -> Int -> Int
    const baseDigitsSumModBase = base =>
        // For any integer n, the sum of its digits
        // in a given base, modulo that base.
        n => sum(unfoldl(
            x => 0 < x ? (
                Just(quotRem(x)(base))
            ) : Nothing()
        )(n)) % base

    // ------------------------TEST------------------------
    const main = () =>
        console.log(
            fTable(
                'First 25 fairshare terms for a given number of players:'
            )(str)(
                xs => '[' + map(
                    compose(justifyRight(2)(' '), str)
                )(xs) + ' ]'
            )(
                compose(take(25), thueMorse)
            )([2, 3, 5, 11])
        );

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

    // 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) {
        // A non-finite succession of enumerable
        // values, starting with the value x.
        let v = x;
        while (true) {
            yield v;
            v = 1 + v;
        }
    }

    // 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');
    };

    // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
    const fmapGen = f =>
        function*(gen) {
            let v = take(1)(gen);
            while (0 < v.length) {
                yield(f(v[0]))
                v = take(1)(gen)
            }
        };

    // justifyRight :: Int -> Char -> String -> String
    const justifyRight = n =>
        // The string s, preceded by enough padding (with
        // the character c) to reach the string length n.
        c => s => n > s.length ? (
            s.padStart(n, c)
        ) : s;

    // 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 =>
        // The list obtained by applying f to each element of xs.
        // (The image of xs under f).
        xs => (Array.isArray(xs) ? (
            xs
        ) : xs.split('')).map(f);

    // quotRem :: Int -> Int -> (Int, Int)
    const quotRem = m => n =>
        Tuple(Math.floor(m / n))(
            m % n
        );

    // str :: a -> String
    const str = x => x.toString();

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

    // 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.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    // unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
    const unfoldl = f => v => {
        // Dual to reduce or foldl.
        // Where these reduce a list to a summary value, unfoldl
        // builds a list from a seed value.
        // Where f returns Just(a, b), a is appended to the list,
        // and the residual b is used as the argument for the next
        // application of f.
        // Where f returns Nothing, the completed list is returned.
        let
            xr = [v, v],
            xs = [];
        while (true) {
            const mb = f(xr[0]);
            if (mb.Nothing) {
                return xs
            } else {
                xr = mb.Just;
                xs = [xr[1]].concat(xs);
            }
        }
    };

    // 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();
})();


Fast Fourier transform

Calculate the   FFT   (Fast Fourier Transform)   of an input sequence.

The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude   (i.e.:   sqrt(re2 + im2))   of the complex result.

The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.

Solution:
/*
complex fast fourier transform and inverse from
http://rosettacode.org/wiki/Fast_Fourier_transform#C.2B.2B
*/
function icfft(amplitudes)
{
	var N = amplitudes.length;
	var iN = 1 / N;

	//conjugate if imaginary part is not 0
	for(var i = 0 ; i < N; ++i)
		if(amplitudes[i] instanceof Complex)
			amplitudes[i].im = -amplitudes[i].im;

	//apply fourier transform
	amplitudes = cfft(amplitudes)

	for(var i = 0 ; i < N; ++i)
	{
		//conjugate again
		amplitudes[i].im = -amplitudes[i].im;
		//scale
		amplitudes[i].re *= iN;
		amplitudes[i].im *= iN;
	}
	return amplitudes;
}

function cfft(amplitudes)
{
	var N = amplitudes.length;
	if( N <= 1 )
		return amplitudes;

	var hN = N / 2;
	var even = [];
	var odd = [];
	even.length = hN;
	odd.length = hN;
	for(var i = 0; i < hN; ++i)
	{
		even[i] = amplitudes[i*2];
		odd[i] = amplitudes[i*2+1];
	}
	even = cfft(even);
	odd = cfft(odd);

	var a = -2*Math.PI;
	for(var k = 0; k < hN; ++k)
	{
		if(!(even[k] instanceof Complex))
			even[k] = new Complex(even[k], 0);
		if(!(odd[k] instanceof Complex))
			odd[k] = new Complex(odd[k], 0);
		var p = k/N;
		var t = new Complex(0, a * p);
		t.cexp(t).mul(odd[k], t);
		amplitudes[k] = even[k].add(t, odd[k]);
		amplitudes[k + hN] = even[k].sub(t, even[k]);
	}
	return amplitudes;
}

//test code
//console.log( cfft([1,1,1,1,0,0,0,0]) );
//console.log( icfft(cfft([1,1,1,1,0,0,0,0])) );


Fibonacci n-step number sequences

These number series are an expansion of the ordinary [[Fibonacci sequence]] where:
# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2
# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3
# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...
# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}

For small values of n, Greek numeric prefixes are sometimes used to individually name each series.

:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Fibonacci n-step sequences
|- style="background-color: rgb(255, 204, 255);"
! n !! Series name !! Values
|-
|  2 ||  fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
|-
|  3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
|-
|  4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
|-
|  5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
|-
|  6 ||  hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
|-
|  7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
|-
|  8 ||  octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
|-
|  9 ||  nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
|-
| 10 ||  decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
|}

Allied sequences can be generated where the initial values are changed:
: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.

;Task:
# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.

;Related tasks:
*   [[Fibonacci sequence]]
*   Wolfram Mathworld
*   [[Hofstadter Q sequence]]
*   [[Leonardo numbers]]

;Also see:
*   Lucas Numbers - Numberphile (Video)
*   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
*   Wikipedia, Lucas number
*   MathWorld, Fibonacci Number
*   Some identities for r-Fibonacci numbers
*   OEIS Fibonacci numbers
*   OEIS Lucas numbers

Solution:
function fib(arity, len) {
    return nacci(nacci([1,1], arity, arity), arity, len);
}

function lucas(arity, len) {
    return nacci(nacci([2,1], arity, arity), arity, len);
}

function nacci(a, arity, len) {
    while (a.length < len) {
        var sum = 0;
        for (var i = Math.max(0, a.length - arity); i < a.length; i++)
            sum += a[i];
        a.push(sum);
    }
    return a;
}

function main() {
    for (var arity = 2; arity <= 10; arity++)
        console.log("fib(" + arity + "): " + fib(arity, 15));
    for (var arity = 2; arity <= 10; arity++)
        console.log("lucas(" + arity + "): " + lucas(arity, 15));
}

main();


Fibonacci word

The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence    as described here:

     Define   F_Word1   as   '''1'''
     Define   F_Word2   as   '''0'''
     Form     F_Word3   as   F_Word2     concatenated with   F_Word1    i.e.:   '''01'''
     Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2

;Task:
Perform the above steps for     n = 37.

You may display the first few but not the larger values of   n.
{Doing so will get the task's author into trouble with them what be (again!).}

Instead, create a table for   F_Words   '''1'''   to   '''37'''   which shows:
::*   The number of characters in the word
::*   The word's [[Entropy]]

;Related tasks:
*   Fibonacci word/fractal
*   [[Entropy]]
*   [[Entropy/Narcissist]]

Solution:
//makes outputting a table possible in environments
//that don't support console.table()
function console_table(xs) {
    function pad(n,s) {
        var res = s;
        for (var i = s.length; i < n; i++)
            res += " ";
        return res;
    }

    if (xs.length === 0)
        console.log("No data");
    else {
        var widths = [];
        var cells = [];
        for (var i = 0; i <= xs.length; i++)
            cells.push([]);

        for (var s in xs[0]) {
            var len = s.length;
            cells[0].push(s);

            for (var i = 0; i < xs.length; i++) {
                var ss = "" + xs[i][s];
                len = Math.max(len, ss.length);
                cells[i+1].push(ss);
            }
            widths.push(len);
        }
        var s = "";
        for (var x = 0; x < cells.length; x++) {
            for (var y = 0; y < widths.length; y++)
                s += "|" + pad(widths[y], cells[x][y]);
            s += "|\n";
        }
        console.log(s);
    }
}

//returns the entropy of a string as a number
function entropy(s) {
     //create an object containing each individual char
	//and the amount of iterations per char
    function prob(s) {
        var h = Object.create(null);
        s.split('').forEach(function(c) {
           h[c] && h[c]++ || (h[c] = 1);
        });
        return h;
    }

    s = s.toString(); //just in case
    var e = 0, l = s.length, h = prob(s);

    for (var i in h ) {
        var p = h[i]/l;
        e -= p * Math.log(p) / Math.log(2);
    }
    return e;
}

//creates Fibonacci Word to n as described on Rosetta Code
//see rosettacode.org/wiki/Fibonacci_word
function fibWord(n) {
    var wOne = "1", wTwo = "0", wNth = [wOne, wTwo], w = "", o = [];

    for (var i = 0; i < n; i++) {
        if (i === 0 || i === 1) {
            w = wNth[i];
        } else {
            w = wNth[i - 1] + wNth[i - 2];
            wNth.push(w);
        }
        var l = w.length;
        var e = entropy(w);

        if (l <= 21) {
        	o.push({
            	N: i + 1,
            	Length: l,
            	Entropy: e,
            	Word: w
        	});
        } else {
        	o.push({
            	N: i + 1,
            	Length: l,
            	Entropy: e,
            	Word: "..."
        	});
        }
    }

    try {
    	console.table(o);
    } catch (err) {
    	console_table(o);
    }
}

fibWord(37);


File extension is in extensions list

Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.

It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.

For these reasons, this task exists in addition to the [[Extract file extension]] task.

;Related tasks:
* [[Extract file extension]]
* [[String matching]]

Solution:
function fileExtensionInExtensionsList(filename) {
	let foundIt = false;
	let filenameLC = filename.toLowerCase();
	let extensions = ["zip", "rar", "7z", "gz", "archive", "A##" ,"tar.bz2"];
	extensions.forEach(extension =>  {
		if (filenameLC.endsWith("." + extension.toLowerCase())) { foundIt = true; }
	} );
	return foundIt;
}

// perform tests below

var fileNamesToTest = [
	"MyData.a##"
	,"MyData.tar.Gz"
	,"MyData.gzip"
	,"MyData.7z.backup"
	,"MyData..."
	,"MyData"
	,"MyData_v1.0.tar.bz2"
	,"MyData_v1.0.bz2"
];

fileNamesToTest.forEach(filename => {
	console.log(filename + " -> " + fileExtensionInExtensionsList(filename));
});


Find limit of recursion

{{selection|Short Circuit|Console Program Basics}}

;Task:
Find the limit of recursion.

Solution:
function recurse(depth)
{
 try
 {
  return recurse(depth + 1);
 }
 catch(ex)
 {
  return depth;
 }
}

var maxRecursion = recurse(1);
document.write("Recursion depth on this system is " + maxRecursion);


Find palindromic numbers in both binary and ternary bases

*   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   ''both'':
:::*   base 2
:::*   base 3
*   Display   '''0'''   (zero) as the first number found, even though some other definitions ignore it.
*   Optionally, show the decimal number found in its binary and ternary form.
*   Show all output here.

It's permissible to assume the first two numbers and simply list them.

;See also
*   Sequence A60792,   numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.

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

    // GENERIC FUNCTIONS

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

    // compose :: (b -> c) -> (a -> b) -> (a -> c)
    const compose = (f, g) => x => f(g(x));

    // listApply :: [(a -> b)] -> [a] -> [b]
    const listApply = (fs, xs) =>
        [].concat.apply([], fs.map(f =>
        [].concat.apply([], xs.map(x => [f(x)]))));

    // pure :: a -> [a]
    const pure = x => [x];

    // curry :: Function -> Function
    const curry = (f, ...args) => {
        const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :
            function () {
                return go(xs.concat([].slice.apply(arguments)));
            };
        return go([].slice.call(args, 1));
    };

    // transpose :: [[a]] -> [[a]]
    const transpose = xs =>
        xs[0].map((_, iCol) => xs.map(row => row[iCol]));

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

    // take :: Int -> [a] -> [a]
    const take = (n, xs) => xs.slice(0, n);

    // drop :: Int -> [a] -> [a]
    const drop = (n, xs) => xs.slice(n);

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

    // quotRem :: Integral a => a -> a -> (a, a)
    const quotRem = (m, n) => [Math.floor(m / n), m % n];

    // length :: [a] -> Int
    const length = xs => xs.length;

    // justifyLeft :: Int -> Char -> Text -> Text
    const justifyLeft = (n, cFiller, strText) =>
        n > strText.length ? (
            (strText + cFiller.repeat(n))
            .substr(0, n)
        ) : strText;

    // unwords :: [String] -> String
    const unwords = xs => xs.join(' ');

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // BASES AND PALINDROMES

    // show, showBinary, showTernary :: Int -> String
    const show = n => n.toString(10);
    const showBinary = n => n.toString(2);
    const showTernary = n => n.toString(3);

    // readBase3 :: String -> Int
    const readBase3 = s => parseInt(s, 3);

    // base3Palindrome :: Int -> String
    const base3Palindrome = n => {
        const s = showTernary(n);
        return s + '1' + reverse(s);
    };

    // isBinPal :: Int -> Bool
    const isBinPal = n => {
        const
            s = showBinary(n),
            [q, r] = quotRem(s.length, 2);
        return (r !== 0) && drop(q + 1, s) === reverse(take(q, s));
    };

    // solutions :: [Int]
    const solutions = [0, 1].concat(range(1, 10E5)
        .map(compose(readBase3, base3Palindrome))
        .filter(isBinPal));

    // TABULATION

    // cols :: [[Int]]
    const cols = transpose(
        [
            ['Decimal', 'Ternary', 'Binary']
        ].concat(
            solutions.map(
                compose(
                    xs => listApply([show, showTernary, showBinary], xs),
                    pure
                )
            )
        )
    );

    return unlines(
        transpose(cols.map(col => col.map(
            curry(justifyLeft)(maximum(col.map(length)) + 1, ' ')
        )))
        .map(unwords));
})();


Find the intersection of two lines

Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]

;Task:
Find the point of intersection of two lines in 2D.

The 1st     line passes though    (4,0)    and    (6,10) .
The 2nd line passes though    (0,3)    and    (10,7) .

Solution:
(() => {
    'use strict';
    // INTERSECTION OF TWO LINES ----------------------------------------------

    // intersection :: Line -> Line -> Either String (Float, Float)
    const intersection = (ab, pq) => {
        const
            delta = f => x => f(fst(x)) - f(snd(x)),
            [abDX, pqDX, abDY, pqDY] = apList(
                [delta(fst), delta(snd)], [ab, pq]
            ),
            determinant = abDX * pqDY - abDY * pqDX;

        return determinant !== 0 ? Right((() => {
            const [abD, pqD] = map(
                ([a, b]) => fst(a) * snd(b) - fst(b) * snd(a),
                [ab, pq]
            );
            return apList(
                [([pq, ab]) =>
                    (abD * pq - ab * pqD) / determinant
                ], [
                    [pqDX, abDX],
                    [pqDY, abDY]
                ]
            );
        })()) : Left('(Parallel lines – no intersection)');
    };

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

    // Left :: a -> Either a b
    const Left = x => ({
        type: 'Either',
        Left: x
    });

    // Right :: b -> Either a b
    const Right = x => ({
        type: 'Either',
        Right: x
    });

    // A list of functions applied to a list of arguments
    // <*> :: [(a -> b)] -> [a] -> [b]
    const apList = (fs, xs) => //
        [].concat.apply([], fs.map(f => //
            [].concat.apply([], xs.map(x => [f(x)]))));

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

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

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

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

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

    // lrIntersection ::Either String Point
    const lrIntersection = intersection([
        [4.0, 0.0],
        [6.0, 10.0]
    ], [
        [0.0, 3.0],
        [10.0, 7.0]
    ]);
    return show(lrIntersection.Left || lrIntersection.Right);
})();


Find the last Sunday of each month

Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).

Example of an expected output:

./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29

;Related tasks
* [[Day of the week]]
* [[Five weekends]]
* [[Last Friday of each month]]

Solution:
function lastSundayOfEachMonths(year) {
	var lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	var sundays = [];
	var date, month;
	if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
		lastDay[2] = 29;
	}
	for (date = new Date(), month = 0; month < 12; month += 1) {
		date.setFullYear(year, month, lastDay[month]);
		date.setDate(date.getDate() - date.getDay());
		sundays.push(date.toISOString().substring(0, 10));
	}
	return sundays;
}

console.log(lastSundayOfEachMonths(2013).join('\n'));


Find the missing permutation

ABCD
                    CABD
                    ACDB
                    DACB
                    BCDA
                    ACBD
                    ADCB
                    CDAB
                    DABC
                    BCAD
                    CADB
                    CDBA
                    CBAD
                    ABDC
                    ADBC
                    BDCA
                    DCBA
                    BACD
                    BADC
                    BDAC
                    CBDA
                    DBCA
                    DCAB

Listed above are   all-but-one   of the permutations of the symbols   '''A''',   '''B''',   '''C''',   and   '''D''',   ''except''   for one permutation that's   ''not''   listed.

;Task:
Find that missing permutation.

;Methods:
* Obvious method:
         enumerate all permutations of   '''A''',  '''B''',  '''C''',  and  '''D''',
         and then look for the missing permutation.

* alternate method:
         Hint:  if all permutations were shown above,  how many
         times would  '''A'''  appear in each position?
         What is the  ''parity''  of this number?

* another alternate method:
         Hint:  if you add up the letter values of each column,
         does a missing letter   '''A''',  '''B''',  '''C''',  and  '''D'''   from each
         column cause the total value for each column to be unique?

;Related task:
*   [[Permutations]])

Solution:
(function (strList) {

    // [a] -> [[a]]
    function permutations(xs) {
        return xs.length ? (
            chain(xs, function (x) {
                return chain(permutations(deleted(x, xs)), function (ys) {
                    return [[x].concat(ys).join('')];
                })
            })) : [[]];
    }

    // Monadic bind/chain for lists
    // [a] -> (a -> b) -> [b]
    function chain(xs, f) {
        return [].concat.apply([], xs.map(f));
    }

    // a -> [a] -> [a]
    function deleted(x, xs) {
        return xs.length ? (
            x === xs[0] ? xs.slice(1) : [xs[0]].concat(
                deleted(x, xs.slice(1))
            )
        ) : [];
    }

    // Provided subset
    var lstSubSet = strList.split('\n');

    // Any missing permutations
    // (we can use fold/reduce, filter, or chain (concat map) here)
    return chain(permutations('ABCD'.split('')), function (x) {
        return lstSubSet.indexOf(x) === -1 ? [x] : [];
    });

})(
    'ABCD\nCABD\nACDB\nDACB\nBCDA\nACBD\nADCB\nCDAB\nDABC\nBCAD\nCADB\n\
CDBA\nCBAD\nABDC\nADBC\nBDCA\nDCBA\nBACD\nBADC\nBDAC\nCBDA\nDBCA\nDCAB'
);


Find the missing permutation

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

    // MISSING PERMUTATION ---------------------------------------------------

    // missingPermutation :: [String] -> String
    const missingPermutation = xs =>
        map(
            // Rarest letter,
            compose([
                sort,
                group,
                curry(minimumBy)(comparing(length)),
                head
            ]),

            // in each column.
            transpose(map(stringChars, xs))
        )
        .join('');

    // GENERIC FUNCTIONAL PRIMITIVES -----------------------------------------

    // transpose :: [[a]] -> [[a]]
    const transpose = xs =>
        xs[0].map((_, iCol) => xs.map(row => row[iCol]));

    // sort :: Ord a => [a] -> [a]
    const sort = xs => xs.sort();

    // group :: Eq a => [a] -> [[a]]
    const group = xs => groupBy((a, b) => a === b, xs);

    // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
    const groupBy = (f, xs) => {
        const dct = xs.slice(1)
            .reduce((a, x) => {
                const
                    h = a.active.length > 0 ? a.active[0] : undefined,
                    blnGroup = h !== undefined && f(h, x);

                return {
                    active: blnGroup ? a.active.concat(x) : [x],
                    sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])
                };
            }, {
                active: xs.length > 0 ? [xs[0]] : [],
                sofar: []
            });
        return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);
    };

    // length :: [a] -> Int
    const length = xs => xs.length;

    // comparing :: (a -> b) -> (a -> a -> Ordering)
    const comparing = f =>
        (x, y) => {
            const
                a = f(x),
                b = f(y);
            return a < b ? -1 : a > b ? 1 : 0
        };

    // minimumBy :: (a -> a -> Ordering) -> [a] -> a
    const minimumBy = (f, xs) =>
        xs.reduce((a, x) => a === undefined ? x : (
            f(x, a) < 0 ? x : a
        ), undefined);

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

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

    // compose :: [(a -> a)] -> (a -> a)
    const compose = fs => x => fs.reduce((a, f) => f(a), x);

    // curry :: ((a, b) -> c) -> a -> b -> c
    const curry = f => a => b => f(a, b);

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

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

    return missingPermutation(["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",
        "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC",
        "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
    ]);

    // -> "DBAC"
})();


First-class functions/Use numbers analogously

In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.

This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.

Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
   x  = 2.0
   xi = 0.5
   y  = 4.0
   yi = 0.25
   z  = x + y
   zi = 1.0 / ( x + y )

Create a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
  new_function = multiplier(n1,n2)
  # where new_function(m) returns the result of n1 * n2 * m

Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.

To paraphrase the task description: Do what was done before, but with numbers rather than functions

Solution:
const x = 2.0;
const xi = 0.5;
const y = 4.0;
const yi = 0.25;
const z = x + y;
const zi = 1.0 / (x + y);
const pairs = [[x, xi], [y, yi], [z, zi]];
const testVal = 0.5;

const multiplier = (a, b) => m => a * b * m;

const test = () => {
  return pairs.map(([a, b]) => {
    const f = multiplier(a, b);
    const result = f(testVal);
    return `${a} * ${b} * ${testVal} = ${result}`;
  });
}

test().join('\n');


First perfect square in base n with n unique digits

Find the first perfect square in a given base '''N''' that has at least '''N''' digits and
exactly '''N''' ''significant unique'' digits when expressed in base '''N'''.

E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').

You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.

;Task

* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.

* (optional) Do the same for bases '''13''' through '''16'''.

* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)

;See also:

;* OEIS A260182: smallest square that is pandigital in base n.

;Related task

;* [[Casting out nines]]

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

    // allDigitSquare :: Int -> Int
    const allDigitSquare = base => {
        const bools = replicate(base, false);
        return untilSucc(
            allDigitsUsedAtBase(base, bools),
            ceil(sqrt(parseInt(
                '10' + '0123456789abcdef'.slice(2, base),
                base
            )))
        );
    };

    // allDigitsUsedAtBase :: Int -> [Bool] -> Int -> Bool
    const allDigitsUsedAtBase = (base, bools) => n => {
        // Fusion of representing the square of integer N at a given base
        // with checking whether all digits of that base contribute to N^2.
        // Sets the bool at a digit position to True when used.
        // True if all digit positions have been used.
        const ds = bools.slice(0);
        let x = n * n;
        while (x) {
            ds[x % base] = true;
            x = floor(x / base);
        }
        return ds.every(x => x)
    };

    // showBaseSquare :: Int -> String
    const showBaseSquare = b => {
        const q = allDigitSquare(b);
        return justifyRight(2, ' ', str(b)) + ' -> ' +
            justifyRight(8, ' ', showIntAtBase(b, digit, q, '')) +
            ' -> ' + showIntAtBase(b, digit, q * q, '');
    };

    // TEST -----------------------------------------------
    const main = () => {
        // 1-12 only - by 15 the squares are truncated by
        // JS integer limits.

        // Returning values through console.log –
        // in separate events to avoid asynchronous disorder.
        print('Smallest perfect squares using all digits in bases 2-12:\n')
      (id > 0 ? chars.substr(id, 1) : " ")    print('Base      Root    Square')

        print(showBaseSquare(2));
        print(showBaseSquare(3));
        print(showBaseSquare(4));
        print(showBaseSquare(5));
        print(showBaseSquare(6));
        print(showBaseSquare(7));
        print(showBaseSquare(8));
        print(showBaseSquare(9));
        print(showBaseSquare(10));
        print(showBaseSquare(11));
        print(showBaseSquare(12));
    };

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

    const
        ceil = Math.ceil,
        floor = Math.floor,
        sqrt = Math.sqrt;

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

    // digit :: Int -> Char
    const digit = n =>
        // Digit character for given integer.
        '0123456789abcdef' [n];

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

    // justifyRight :: Int -> Char -> String -> String
    const justifyRight = (n, cFiller, s) =>
        n > s.length ? (
            s.padStart(n, cFiller)
        ) : s;

    // print :: a -> IO ()
    const print = x => console.log(x)

    // quotRem :: Int -> Int -> (Int, Int)
    const quotRem = (m, n) =>
        Tuple(Math.floor(m / n), m % n);

    // replicate :: Int -> a -> [a]
    const replicate = (n, x) =>
        Array.from({
            length: n
        }, () => x);

    // showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String
    const showIntAtBase = (base, toChr, n, rs) => {
        const go = ([n, d], r) => {
            const r_ = toChr(d) + r;
            return 0 !== n ? (
                go(Array.from(quotRem(n, base)), r_)
            ) : r_;
        };
        return 1 >= base ? (
            'error: showIntAtBase applied to unsupported base'
        ) : 0 > n ? (
            'error: showIntAtBase applied to negative number'
        ) : go(Array.from(quotRem(n, base)), rs);
    };

    // Abbreviation for quick testing - any 2nd arg interpreted as indent size

    // sj :: a -> String
    function sj() {
        const args = Array.from(arguments);
        return JSON.stringify.apply(
            null,
            1 < args.length && !isNaN(args[0]) ? [
                args[1], null, args[0]
            ] : [args[0], null, 2]
        );
    }

    // str :: a -> String
    const str = x => x.toString();

    // untilSucc :: (Int -> Bool) -> Int -> Int
    const untilSucc = (p, x) => {
        // The first in a chain of successive integers
        // for which p(x) returns true.
        let v = x;
        while (!p(v)) v = 1 + v;
        return v;
    };

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


Fivenum

Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory.

For example, the   '''R'''   programming language implements Tukey's five-number summary as the '''fivenum''' function.

;Task:
Given an array of numbers, compute the five-number summary.

;Note:
While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data.

Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.

Solution:
function median(arr) {
  let mid = Math.floor(arr.length / 2);
  return (arr.length % 2 == 0) ? (arr[mid-1] + arr[mid]) / 2 : arr[mid];
}

Array.prototype.fiveNums = function() {
  this.sort(function(a, b) { return a - b} );
  let mid = Math.floor(this.length / 2),
      loQ = (this.length % 2 == 0) ? this.slice(0, mid) : this.slice(0, mid+1),
      hiQ = this.slice(mid);
  return [ this[0],
           median(loQ),
           median(this),
           median(hiQ),
           this[this.length-1] ];
}

// testing
let test = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43];
console.log( test.fiveNums() );

test = [0, 0, 1, 2, 63, 61, 27, 13];
console.log( test.fiveNums() );

test = [ 0.14082834,  0.09748790,  1.73131507,  0.87636009, -1.95059594,
         0.73438555, -0.03035726,  1.46675970, -0.74621349, -0.72588772,
         0.63905160,  0.61501527, -0.98983780, -1.00447874, -0.62759469,
         0.66206163,  1.04312009, -0.10305385,  0.75775634,  0.32566578];
console.log( test.fiveNums() );


Flatten a list

Write a function to flatten the nesting in an arbitrary list of values.

Your program should work on the equivalent of this list:
   [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
    [1, 2, 3, 4, 5, 6, 7, 8]

;Related task:
*   [[Tree traversal]]

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

    // flatten :: Tree a -> [a]
    function flatten(t) {
        return (t instanceof Array ? concatMap(flatten, t) : t);
    }

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

    return flatten(
        [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
    );

})();


Flipping bits game

The game:
Given an   '''NxN'''   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones.

The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once   (as one move).

In an inversion.   any  '''1'''  becomes  '''0''',   and any  '''0'''  becomes  '''1'''  for that whole row or column.

;Task:
Create a program to score for the Flipping bits game.
# The game should create an original random target configuration and a starting configuration.
# Ensure that the starting position is ''never'' the target position.
# The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position).
# The number of moves taken so far should be shown.

Show an example of a short game here, on this page, for a   '''3x3'''   array of bits.

Solution:
function numOfRows(board) { return board.length; }
function numOfCols(board) { return board[0].length; }
function boardToString(board) {
    // First the top-header
    var header = '   ';
    for (var c = 0; c < numOfCols(board); c++)
        header += c + ' ';

    // Then the side-header + board
    var sideboard = [];
    for (var r = 0; r < numOfRows(board); r++) {
        sideboard.push(r + ' [' + board[r].join(' ') + ']');
    }

    return header + '\n' + sideboard.join('\n');
}
function flipRow(board, row) {
    for (var c = 0; c < numOfCols(board); c++) {
        board[row][c] = 1 - board[row][c];
    }
}
function flipCol(board, col) {
    for (var r = 0; r < numOfRows(board); r++) {
        board[r][col] = 1 - board[r][col];
    }
}

function playFlippingBitsGame(rows, cols) {
    rows = rows | 3;
    cols = cols | 3;
    var targetBoard = [];
    var manipulatedBoard = [];
    // Randomly generate two identical boards.
    for (var r = 0; r < rows; r++) {
        targetBoard.push([]);
        manipulatedBoard.push([]);
        for (var c = 0; c < cols; c++) {
            targetBoard[r].push(Math.floor(Math.random() * 2));
            manipulatedBoard[r].push(targetBoard[r][c]);
        }
    }
    // Naive-scramble one of the boards.
    while (boardToString(targetBoard) == boardToString(manipulatedBoard)) {
        var scrambles = rows * cols;
        while (scrambles-- > 0) {
            if (0 == Math.floor(Math.random() * 2)) {
                flipRow(manipulatedBoard, Math.floor(Math.random() * rows));
            }
            else {
                flipCol(manipulatedBoard, Math.floor(Math.random() * cols));
            }
        }
    }
    // Get the user to solve.
    alert(
        'Try to match both boards.\n' +
        'Enter `r<num>` or `c<num>` to manipulate a row or col or enter `q` to quit.'
        );
    var input = '', letter, num, moves = 0;
    while (boardToString(targetBoard) != boardToString(manipulatedBoard) && input != 'q') {
        input = prompt(
            'Target:\n' + boardToString(targetBoard) +
            '\n\n\n' +
            'Board:\n' + boardToString(manipulatedBoard)
            );
        try {
            letter = input.charAt(0);
            num = parseInt(input.slice(1));
            if (letter == 'q')
				break;
            if (isNaN(num)
                || (letter != 'r' && letter != 'c')
                || (letter == 'r' && num >= rows)
                || (letter == 'c' && num >= cols)
                ) {
                throw new Error('');
            }
            if (letter == 'r') {
                flipRow(manipulatedBoard, num);
            }
            else {
                flipCol(manipulatedBoard, num);
            }
            moves++;
        }
        catch(e) {
            alert('Uh-oh, there seems to have been an input error');
        }
    }
    if (input == 'q') {
        alert('~~ Thanks for playing ~~');
    }
    else {
        alert('Completed in ' + moves + ' moves.');
    }
}


Floyd's triangle

Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where
* the first row is   '''1'''     (unity)
* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.

The first few lines of a Floyd triangle looks like this:

 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15

;Task:
:# Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows).
:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.

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

    // FLOYD's TRIANGLE -------------------------------------------------------

    // floyd :: Int -> [[Int]]
    function floyd(n) {
        return snd(mapAccumL(function (start, row) {
            return [start + row + 1, enumFromTo(start, start + row)];
        }, 1, enumFromTo(0, n - 1)));
    };

    // showFloyd :: [[Int]] -> String
    function showFloyd(xss) {
        var ws = map(compose([succ, length, show]), last(xss));
        return unlines(map(function (xs) {
            return concat(zipWith(function (w, x) {
                return justifyRight(w, ' ', show(x));
            }, ws, xs));
        }, xss));
    };

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

    // compose :: [(a -> a)] -> (a -> a)
    function compose(fs) {
        return function (x) {
            return fs.reduceRight(function (a, f) {
                return f(a);
            }, x);
        };
    };

    // concat :: [[a]] -> [a] | [String] -> String
    function concat(xs) {
        if (xs.length > 0) {
            var unit = typeof xs[0] === 'string' ? '' : [];
            return unit.concat.apply(unit, xs);
        } else return [];
    };

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

    // justifyRight :: Int -> Char -> Text -> Text
    function justifyRight(n, cFiller, strText) {
        return n > strText.length ? (cFiller.repeat(n) + strText)
            .slice(-n) : strText;
    };

    // last :: [a] -> a
    function last(xs) {
        return xs.length ? xs.slice(-1)[0] : undefined;
    };

    // length :: [a] -> Int
    function length(xs) {
        return xs.length;
    };

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

    // 'The mapAccumL function behaves like a combination of map and foldl;
    // it applies a function to each element of a list, passing an accumulating
    // parameter from left to right, and returning a final value of this
    // accumulator together with the new list.' (See hoogle )

    // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
    function mapAccumL(f, acc, xs) {
        return xs.reduce(function (a, x) {
            var pair = f(a[0], x);

            return [pair[0], a[1].concat([pair[1]])];
        }, [acc, []]);
    };

    // show ::
    // (a -> String) f,  Num n =>
    // a -> maybe f -> maybe n -> String
    var show = JSON.stringify;

    // snd :: (a, b) -> b
    function snd(tpl) {
        return Array.isArray(tpl) ? tpl[1] : undefined;
    };

    // succ :: Int -> Int
    function succ(x) {
        return x + 1;
    };

    // unlines :: [String] -> String
    function unlines(xs) {
        return xs.join('\n');
    };

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

    // TEST ( n=5 and n=14 rows ) ---------------------------------------------

    return unlines(map(function (n) {
        return showFloyd(floyd(n)) + '\n';
    }, [5, 14]));
})();


Floyd's triangle

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

    // FLOYD's TRIANGLE -------------------------------------------------------

    // floyd :: Int -> [[Int]]
    const floyd = n => snd(mapAccumL(
        (start, row) => [start + row + 1, enumFromTo(start, start + row)],
        1, enumFromTo(0, n - 1)
    ));

    // showFloyd :: [[Int]] -> String
    const showFloyd = xss => {
        const ws = map(compose([succ, length, show]), last(xss));
        return unlines(
            map(xs => concat(zipWith(
                    (w, x) => justifyRight(w, ' ', show(x)), ws, xs
                )),
                xss
            )
        );
    };

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

    // compose :: [(a -> a)] -> (a -> a)
    const compose = fs => x => fs.reduceRight((a, f) => f(a), x);

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

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

    // justifyRight :: Int -> Char -> Text -> Text
    const justifyRight = (n, cFiller, strText) =>
        n > strText.length ? (
            (cFiller.repeat(n) + strText)
            .slice(-n)
        ) : strText;

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

    // length :: [a] -> Int
    const length = xs => xs.length;

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

    // 'The mapAccumL function behaves like a combination of map and foldl;
    // it applies a function to each element of a list, passing an accumulating
    // parameter from left to right, and returning a final value of this
    // accumulator together with the new list.' (See hoogle )

    // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
    const mapAccumL = (f, acc, xs) =>
        xs.reduce((a, x) => {
            const pair = f(a[0], x);

            return [pair[0], a[1].concat([pair[1]])];
        }, [acc, []]);

    // show ::
    // (a -> String) f,  Num n =>
    // a -> maybe f -> maybe n -> String
    const show = JSON.stringify;

    // snd :: (a, b) -> b
    const snd = tpl => Array.isArray(tpl) ? tpl[1] : undefined;

    // succ :: Int -> Int
    const succ = x => x + 1

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

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

    // TEST ( n=5 and n=14 rows ) ---------------------------------------------

    return unlines(map(n => showFloyd(floyd(n)) + '\n', [5, 14]))
})();


Four bit adder

"''Simulate''" a four-bit adder.

This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two gate. ;

Finally a half adder can be made using an   ''xor''   gate and an   ''and''   gate.

The   ''xor''   gate can be made using two   ''not''s,   two   ''and''s   and one   ''or''.

'''Not''',   '''or'''   and   '''and''',   the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.

If there is not a ''bit type'' in your language, to be sure that the   ''not''   does not "invert" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   ''nand''   (''and''   then   ''not'')   with the constant   '''1'''   on one input.

Instead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   ''connecting'' the other "constructive blocks",   in turn made of "simpler" and "smaller" ones.

{|
|+Schematics of the "constructive blocks"
!(Xor gate with ANDs, ORs and NOTs)
!   (A half adder)
!          (A full adder)
!                (A 4-bit adder)
|-
|Xor gate done with ands, ors and nots
|A half adder
|A full adder
|A 4-bit adder
|}

Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".

It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.

To test the implementation, show the sum of two four-bit numbers (in binary).

Solution:
// basic building blocks allowed by the rules are ~, &, and |, we'll fake these
// in a way that makes what they do (at least when you use them) more obvious
// than the other available options do.

function not(a) {
    if (arePseudoBin(a))
        return a == 1 ? 0 : 1;
}

function and(a, b) {
    if (arePseudoBin(a, b))
        return a + b < 2 ? 0 : 1;
}

function nand(a, b) {
    if (arePseudoBin(a, b))
        return not(and(a, b));
}

function or(a, b) {
    if (arePseudoBin(a, b))
        return nand(nand(a,a), nand(b,b));
}

function xor(a, b) {
    if (arePseudoBin(a, b))
        return nand(nand(nand(a,b), a), nand(nand(a,b), b));
}

function halfAdder(a, b) {
    if (arePseudoBin(a, b))
        return { carry: and(a, b), sum: xor(a, b) };
}

function fullAdder(a, b, c) {
    if (arePseudoBin(a, b, c)) {
        var h0 = halfAdder(a, b),
            h1 = halfAdder(h0.sum, c);
        return {carry: or(h0.carry, h1.carry), sum: h1.sum };
    }
}

function fourBitAdder(a, b) {
    if (typeof a.length == 'undefined' || typeof b.length == 'undefined')
        throw new Error('bad values');
    // not sure if the rules allow this, but we need to pad the values
    // if they're too short and trim them if they're too long
    var inA = Array(4),
        inB = Array(4),
        out = Array(4),
        i = 4,
        pass;

    while (i--) {
        inA[i] = a[i] != 1 ? 0 : 1;
        inB[i] = b[i] != 1 ? 0 : 1;
    }

    // now we can start adding... I'd prefer to do this in a loop,
    // but that wouldn't be "connecting the other 'constructive blocks',
    // in turn made of 'simpler' and 'smaller' ones"

    pass = halfAdder(inA[3], inB[3]);
    out[3] = pass.sum;
    pass = fullAdder(inA[2], inB[2], pass.carry);
    out[2] = pass.sum;
    pass = fullAdder(inA[1], inB[1], pass.carry);
    out[1] = pass.sum;
    pass = fullAdder(inA[0], inB[0], pass.carry);
    out[0] = pass.sum;
    return out.join('');
}


Four is magic

Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.

Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word.

Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.

For instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.'''

      '''Three is five, five is four, four is magic.'''

For reference, here are outputs for 0 through 9.

      Zero is four, four is magic.
      One is three, three is five, five is four, four is magic.
      Two is three, three is five, five is four, four is magic.
      Three is five, five is four, four is magic.
      Four is magic.
      Five is four, four is magic.
      Six is three, three is five, five is four, four is magic.
      Seven is five, five is four, four is magic.
      Eight is five, five is four, four is magic.
      Nine is four, four is magic.

;Some task guidelines:
:* You may assume the input will only contain integer numbers.
:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)
:* Cardinal number conversions should follow the  English short scale. (billion is 1e9, trillion is 1e12, etc.)
:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)
:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.
:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.
:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.
:* The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
:* The output can either be the return value from the function, or be displayed from within the function.
:* You are encouraged, though not mandated to use proper sentence capitalization.
:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.
:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.

You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.

If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)

Four is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.

;Related tasks:
:*   [[Four is the number of_letters in the ...]]
:*   [[Look-and-say sequence]]
:*   [[Number names]]
:*   [[Self-describing numbers]]
:*   [[Summarize and say sequence]]
:*   [[Spelling of ordinal numbers]]
:*   [[De Bruijn sequences]]

Solution:
const reverseOrderedNumberToTextMap = (function () {
    const rawNumberToTextMapping = { // Ported over from the Python solution.
        [1n]: "one",
        [2n]: "two",
        [3n]: "three",
        [4n]: "four",
        [5n]: "five",
        [6n]: "six",
        [7n]: "seven",
        [8n]: "eight",
        [9n]: "nine",
        [10n]: "ten",
        [11n]: "eleven",
        [12n]: "twelve",
        [13n]: "thirteen",
        [14n]: "fourteen",
        [15n]: "fifteen",
        [16n]: "sixteen",
        [17n]: "seventeen",
        [18n]: "eighteen",
        [19n]: "nineteen",
        [20n]: "twenty",
        [30n]: "thirty",
        [40n]: "forty",
        [50n]: "fifty",
        [60n]: "sixty",
        [70n]: "seventy",
        [80n]: "eighty",
        [90n]: "ninety",
        [100n]: "hundred",
        [1000n]: "thousand",
        [10n ** 6n]: "million",
        [10n ** 9n]: "billion",
        [10n ** 12n]: "trillion",
        [10n ** 15n]: "quadrillion",
        [10n ** 18n]: "quintillion",
        [10n ** 21n]: "sextillion",
        [10n ** 24n]: "septillion",
        [10n ** 27n]: "octillion",
        [10n ** 30n]: "nonillion",
        [10n ** 33n]: "decillion",
        [10n ** 36n]: "undecillion",
        [10n ** 39n]: "duodecillion",
        [10n ** 42n]: "tredecillion",
        [10n ** 45n]: "quattuordecillion",
        [10n ** 48n]: "quinquadecillion",
        [10n ** 51n]: "sedecillion",
        [10n ** 54n]: "septendecillion",
        [10n ** 57n]: "octodecillion",
        [10n ** 60n]: "novendecillion",
        [10n ** 63n]: "vigintillion",
        [10n ** 66n]: "unvigintillion",
        [10n ** 69n]: "duovigintillion",
        [10n ** 72n]: "tresvigintillion",
        [10n ** 75n]: "quattuorvigintillion",
        [10n ** 78n]: "quinquavigintillion",
        [10n ** 81n]: "sesvigintillion",
        [10n ** 84n]: "septemvigintillion",
        [10n ** 87n]: "octovigintillion",
        [10n ** 90n]: "novemvigintillion",
        [10n ** 93n]: "trigintillion",
        [10n ** 96n]: "untrigintillion",
        [10n ** 99n]: "duotrigintillion",
        [10n ** 102n]: "trestrigintillion",
        [10n ** 105n]: "quattuortrigintillion",
        [10n ** 108n]: "quinquatrigintillion",
        [10n ** 111n]: "sestrigintillion",
        [10n ** 114n]: "septentrigintillion",
        [10n ** 117n]: "octotrigintillion",
        [10n ** 120n]: "noventrigintillion",
        [10n ** 123n]: "quadragintillion",
        [10n ** 153n]: "quinquagintillion",
        [10n ** 183n]: "sexagintillion",
        [10n ** 213n]: "septuagintillion",
        [10n ** 243n]: "octogintillion",
        [10n ** 273n]: "nonagintillion",
        [10n ** 303n]: "centillion",
        [10n ** 306n]: "uncentillion",
        [10n ** 309n]: "duocentillion",
        [10n ** 312n]: "trescentillion",
        [10n ** 333n]: "decicentillion",
        [10n ** 336n]: "undecicentillion",
        [10n ** 363n]: "viginticentillion",
        [10n ** 366n]: "unviginticentillion",
        [10n ** 393n]: "trigintacentillion",
        [10n ** 423n]: "quadragintacentillion",
        [10n ** 453n]: "quinquagintacentillion",
        [10n ** 483n]: "sexagintacentillion",
        [10n ** 513n]: "septuagintacentillion",
        [10n ** 543n]: "octogintacentillion",
        [10n ** 573n]: "nonagintacentillion",
        [10n ** 603n]: "ducentillion",
        [10n ** 903n]: "trecentillion",
        [10n ** 1203n]: "quadringentillion",
        [10n ** 1503n]: "quingentillion",
        [10n ** 1803n]: "sescentillion",
        [10n ** 2103n]: "septingentillion",
        [10n ** 2403n]: "octingentillion",
        [10n ** 2703n]: "nongentillion",
        [10n ** 3003n]: "millinillion"
    };

    return new Map(Object.entries(rawNumberToTextMapping)
                         .sort((a, b) => BigInt(a[0]) > BigInt(b[0]) ? -1 : 1)
                         .map(numberAndText => [BigInt(numberAndText[0]), numberAndText[1]]));
})();

function getCardinalRepresentation(number)
{
    if (number == 0n)
    {
        return "zero";
    }

    function* generateCardinalRepresentationTokens(number)
    {
        if (number <= 0n)
        {
            yield "negative";
            number *= -1n;
        }

        for (const [currentEntryNumber, currentEntryText] of reverseOrderedNumberToTextMap.entries())
        {
            if (number >= currentEntryNumber)
            {
                if (currentEntryNumber >= 100n)
                {
                    yield* generateCardinalRepresentationTokens(number / currentEntryNumber);
                }

                yield currentEntryText;
                number -= currentEntryNumber;
            }
        }
    }

    return [...generateCardinalRepresentationTokens(number)].join(" ");
}

function* generateFourIsMagicParts(number)
{
    if (typeof number != "bigint")
    {
        number = BigInt(number);
    }

    if (number == 4n)
    {
        yield "four is magic";
    }
    else
    {
        const cardinalRepresentation = getCardinalRepresentation(number);
        yield `${cardinalRepresentation} is ${getCardinalRepresentation(BigInt(cardinalRepresentation.length))}`;
        yield* generateFourIsMagicParts(cardinalRepresentation.length);
    }

}

function capitalizeFirstLetter(str)
{
    return str.replace(/^([a-z])/, chr => chr.toUpperCase());
}

function fourIsMagic(number)
{
    return capitalizeFirstLetter(`${[...generateFourIsMagicParts(number)].join(", ")}.`);
}

[
    0,
    -150,
    210,
    10n ** 2703n + 1225n,
    4,
    -4,
    10n ** 3003n + 42n
].map(fourIsMagic).join("\n\n");


Function prototype

Some languages provide the facility to declare functions and subroutines through the use of function prototyping.

;Task:
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:

* An explanation of any placement restrictions for prototype declarations
* A prototype declaration for a function that does not require arguments
* A prototype declaration for a function that requires two arguments
* A prototype declaration for a function that utilizes varargs
* A prototype declaration for a function that utilizes optional arguments
* A prototype declaration for a function that utilizes named parameters
* Example of prototype declarations for subroutines or procedures (if these differ from functions)
* An explanation and example of any special forms of prototyping not covered by the above

Languages that do not provide function prototyping facilities should be omitted from this task.

Solution:
// A prototype declaration for a function that does not require arguments
function List() {}

List.prototype.push = function() {
  return [].push.apply(this, arguments);
};

List.prototype.pop = function() {
  return [].pop.call(this);
};

var l = new List();
l.push(5);
l.length; // 1
l[0]; 5
l.pop(); // 5
l.length; // 0

// A prototype declaration for a function that utilizes varargs
function List() {
  this.push.apply(this, arguments);
}

List.prototype.push = function() {
  return [].push.apply(this, arguments);
};

List.prototype.pop = function() {
  return [].pop.call(this);
};

var l = new List(5, 10, 15);
l.length; // 3
l[0]; 5
l.pop(); // 15
l.length; // 2


Functional coverage tree

Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional ''requirements'' of the
system have been verified.

This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.

;Task Description:
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.

She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.

The overall hierarchy of (sub)tasks is as follows,
cleaning
    house1
        bedrooms
        bathrooms
            bathroom1
            bathroom2
            outside lavatory
        attic
        kitchen
        living rooms
            lounge
            dining room
            conservatory
            playroom
        basement
        garage
        garden
    house2
        upstairs
            bedrooms
                suite 1
                suite 2
                bedroom 3
                bedroom 4
            bathroom
            toilet
            attics
        groundfloor
            kitchen
            living rooms
                lounge
                dining room
                conservatory
                playroom
            wet room & toilet
            garage
            garden
            hot tub suite
        basement
            cellars
            wine cellar
            cinema

The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.

Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY                  |WEIGHT  |COVERAGE  |
cleaning                        |        |          |
    house1                      |40      |          |
        bedrooms                |        |0.25      |
        bathrooms               |        |          |
            bathroom1           |        |0.5       |
            bathroom2           |        |          |
            outside_lavatory    |        |1         |
        attic                   |        |0.75      |
        kitchen                 |        |0.1       |
        living_rooms            |        |          |
            lounge              |        |          |
            dining_room         |        |          |
            conservatory        |        |          |
            playroom            |        |1         |
        basement                |        |          |
        garage                  |        |          |
        garden                  |        |0.8       |
    house2                      |60      |          |
        upstairs                |        |          |
            bedrooms            |        |          |
                suite_1         |        |          |
                suite_2         |        |          |
                bedroom_3       |        |          |
                bedroom_4       |        |          |
            bathroom            |        |          |
            toilet              |        |          |
            attics              |        |0.6       |
        groundfloor             |        |          |
            kitchen             |        |          |
            living_rooms        |        |          |
                lounge          |        |          |
                dining_room     |        |          |
                conservatory    |        |          |
                playroom        |        |          |
            wet_room_&_toilet   |        |          |
            garage              |        |          |
            garden              |        |0.9       |
            hot_tub_suite       |        |1         |
        basement                |        |          |
            cellars             |        |1         |
            wine_cellar         |        |1         |
            cinema              |        |0.75      |

;Calculation:
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.

'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.

;Extra Credit:
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.

The pseudo code would be:

    method delta_calculation(this, power):
        sum_of_weights = sum(node.weight for node in children)
        this.delta  = (1 - this.coverage) * power
        for node in self.children:
            node.delta_calculation(power * node.weight / sum_of_weights)
        return this.delta

Followed by a call to:

    top.delta_calculation(power=1)

'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.

Solution: Parsing the outline text to a tree structure, and traversing this with two computations (one bottom-up, and one top-down), before serialising the updated tree to a new outline text.