Self numbers

A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.

The task is:
  Display the first 50 self numbers;
  I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.

224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.

;See also:

;*OEIS: A003052 - Self numbers or Colombian numbers
;*Wikipedia: Self numbers

Solution:
#include
#include
#include

typedef unsigned char bool;

#define TRUE 1
#define FALSE 0
#define MILLION 1000000
#define BILLION 1000 * MILLION
#define MAX_COUNT 2*BILLION + 9*9 + 1

void sieve(bool *sv) {
    int n = 0, s[8], a, b, c, d, e, f, g, h, i, j;
    for (a = 0; a < 2; ++a) {
        for (b = 0; b < 10; ++b) {
            s[0] = a + b;
            for (c = 0; c < 10; ++c) {
                s[1] = s[0] + c;
                for (d = 0; d < 10; ++d) {
                    s[2] = s[1] + d;
                    for (e = 0; e < 10; ++e) {
                        s[3] = s[2] + e;
                        for (f = 0; f < 10; ++f) {
                            s[4] = s[3] + f;
                            for (g = 0; g < 10; ++g) {
                                s[5] = s[4] + g;
                                for (h = 0; h < 10; ++h) {
                                    s[6] = s[5] + h;
                                    for (i = 0; i < 10; ++i) {
                                        s[7] = s[6] + i;
                                        for (j = 0; j < 10; ++j) {
                                            sv[s[7] + j+ n++] = TRUE;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

int main() {
    int count = 0;
    clock_t begin = clock();
    bool *p, *sv = (bool*) calloc(MAX_COUNT, sizeof(bool));
    sieve(sv);
    printf("The first 50 self numbers are:\n");
    for (p = sv; p < sv + MAX_COUNT; ++p) {
        if (!*p) {
            if (++count <= 50) printf("%ld ", p-sv);
            if (count == 100 * MILLION) {
                printf("\n\nThe 100 millionth self number is %ld\n", p-sv);
                break;
            }
        }
    }
    free(sv);
    printf("Took %lf seconds.\n", (double)(clock() - begin) / CLOCKS_PER_SEC);
    return 0;
}


Self numbers

Solution:
class DigitSumer :
    def __init__(self):
        sumdigit = lambda n : sum( map( int,str( n )))
        self.t = [sumdigit( i ) for i in xrange( 10000 )]
    def __call__ ( self,n ):
        r = 0
        while n >= 10000 :
            n,q = divmod( n,10000 )
            r += self.t[q]
        return r + self.t[n]

def self_numbers ():
    d = DigitSumer()
    s = set([])
    i = 1
    while 1 :
        n = i + d( i )
        if i in s :
            s.discard( i )
        else:
            yield i
        s.add( n )
        i += 1

import time
p = 100
t = time.time()
for i,s in enumerate( self_numbers(),1 ):
    if i <= 50 :
        print s,
        if i == 50 : print
    if i == p :
        print '%7.1f sec  %9dth = %d'%( time.time()-t,i,s )
        p *= 10


Semordnilap

A [https://en.wiktionary.org/wiki/semordnilap#Noun semordnilap] is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.

Example: ''lager'' and ''regal''

;Task
This task does not consider semordnilap phrases, only single words.
Using only words from [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt this list], report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)

Solution:
#include
#include
#include  /* stdlib.h might not have obliged. */
#include

static void reverse(char *s, int len)
{
    int i, j;
    char tmp;

    for (i = 0, j = len - 1; i < len / 2; ++i, --j)
        tmp = s[i], s[i] = s[j], s[j] = tmp;
}

/* Wrap strcmp() for qsort(). */
static int strsort(const void *s1, const void *s2)
{
    return strcmp(*(char *const *) s1, *(char *const *) s2);
}

int main(void)
{
    int i, c, ct = 0, len, sem = 0;
    char **words, **drows, tmp[24];
    FILE *dict = fopen("unixdict.txt", "r");

    /* Determine word count. */
    while ((c = fgetc(dict)) != EOF)
        ct += c == '\n';
    rewind(dict);

    /* Using alloca() is generally discouraged, but we're not doing
     * anything too fancy and the memory gains are significant. */
    words = alloca(ct * sizeof words);
    drows = alloca(ct * sizeof drows);

    for (i = 0; fscanf(dict, "%s%n", tmp, &len) != EOF; ++i) {
        /* Use just enough memory to store the next word. */
        strcpy(words[i] = alloca(len), tmp);

        /* Store it again, then reverse it. */
        strcpy(drows[i] = alloca(len), tmp);
        reverse(drows[i], len - 1);
    }

    fclose(dict);
    qsort(drows, ct, sizeof drows, strsort);

    /* Walk both sorted lists, checking only the words which could
     * possibly be a semordnilap pair for the current reversed word. */
    for (c = i = 0; i < ct; ++i) {
        while (strcmp(drows[i], words[c]) > 0 && c < ct - 1)
            c++;
        /* We found a semordnilap. */
        if (!strcmp(drows[i], words[c])) {
            strcpy(tmp, drows[i]);
            reverse(tmp, strlen(tmp));
            /* Unless it was a palindrome. */
            if (strcmp(drows[i], tmp) > 0 && sem++ < 5)
                printf("%s\t%s\n", drows[i], tmp);
        }
    }

    printf("Semordnilap pairs: %d\n", sem);
    return 0;
}


Semordnilap

Solution:
#!/usr/bin/env node
var  fs = require('fs');
var sys = require('sys');

var dictFile = process.argv[2] || "unixdict.txt";

var dict = {};
fs.readFileSync(dictFile)
  .toString()
  .split('\n')
  .forEach(function(word) {
    dict[word] = word.split("").reverse().join("");
  });

function isSemordnilap(word) { return dict[dict[word]]; };

var semordnilaps = []
for (var key in dict) {
  if (isSemordnilap(key)) {
    var rev = dict[key];
    if (key < rev) {
      semordnilaps.push([key,rev]) ;
    }
  }
}

var count = semordnilaps.length;
sys.puts("There are " + count + " semordnilaps in " +
         dictFile + ".  Here are 5:" );

var indices=[]
for (var i=0; i

===Rhino===


Semordnilap

Solution:
#!/usr/bin/env rhino

importPackage (java.io)

var dictFile = arguments[0] || "unixdict.txt";

var reader = new BufferedReader(new FileReader(dictFile));
var dict = {};
var word;
while (word = reader.readLine()) {
  dict[word] = word.split("").reverse().join("");
}

function isSemordnilap(word) { return dict[dict[word]]; };

var semordnilaps = []
for (var key in dict) {
  if (isSemordnilap(key)) {
    var rev = dict[key];
    if (key < rev) {
      semordnilaps.push([key,rev]) ;
    }
  }
}

var count = semordnilaps.length;
print("There are " + count + " semordnilaps in " +
      dictFile + ".  Here are 5:" );
var indices=[]
for (var i=0; i


Semordnilap

Solution:
>>> with open('unixdict.txt') as f:
	wordset = set(f.read().strip().split())

>>> revlist = (''.join(word[::-1]) for word in wordset)
>>> pairs   = set((word, rev) for word, rev in zip(wordset, revlist)
                  if word < rev and rev in wordset)
>>> len(pairs)
158
>>> sorted(pairs, key=lambda p: (len(p[0]), p))[-5:]
[('damon', 'nomad'), ('lager', 'regal'), ('leper', 'repel'), ('lever', 'revel'), ('kramer', 'remark')]
>>>


Semordnilap

Solution:
'''Dictionary words paired by equivalence under reversal'''

from functools import (reduce)
from itertools import (chain)
import urllib.request

# semordnilaps :: [String] -> [String]
def semordnilaps(xs):
    '''The subset of words in a list which
       are paired (by equivalence under reversal)
       with other words in that list.
    '''
    def go(tpl, w):
        (s, ws) = tpl
        if w[::-1] in s:
            return (s, ws + [w])
        else:
            s.add(w)
            return (s, ws)
    return reduce(go, xs, (set(), []))[1]

# TEST ----------------------------------------------------
def main():
    '''Test'''

    url = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'
    ws = semordnilaps(
        urllib.request.urlopen(
            url
        ).read().splitlines()
    )
    print(
        fTable(
            __doc__ + ':\n\n(longest of ' +
            str(len(ws)) + ' in ' + url + ')\n'
        )(snd)(fst)(identity)(
            sorted(
                concatMap(
                    lambda x: (
                        lambda s=x.decode('utf8'): [
                            (s, s[::-1])
                        ] if 4 < len(x) else []
                    )()
                )(ws),
                key=compose(len)(fst),
                reverse=True
            )
        )
    )

# GENERIC -------------------------------------------------

# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
    '''Right to left function composition.'''
    return lambda f: lambda x: g(f(x))

# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
    '''A concatenated list over which a function has been mapped.
       The list monad can be derived by using a function f which
       wraps its output in a list,
       (using an empty list to represent computational failure).'''
    return lambda xs: list(
        chain.from_iterable(map(f, xs))
    )

# FORMATTING ----------------------------------------------

# fTable :: String -> (a -> String) ->
#                     (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
                     f -> xs -> tabular string.
    '''
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )

# fst :: (a, b) -> a
def fst(tpl):
    '''First member of a pair.'''
    return tpl[0]

# identity :: a -> a
def identity(x):
    '''The identity function.'''
    return x

# snd :: (a, b) -> b
def snd(tpl):
    '''Second member of a pair.'''
    return tpl[1]

if __name__ == '__main__':
    main()


Sequence: nth number with exactly n divisors

Calculate the sequence where each term an is the nth that has '''n''' divisors.

;Task

Show here, on this page, at least the first '''15''' terms of the sequence.

;See also

:*OEIS:A073916

;Related tasks

:*[[Sequence: smallest number greater than previous term with exactly n divisors]]
:*[[Sequence: smallest number with exactly n divisors]]

Solution:
#include
#include
#include
#include

#define LIMIT 15
int smallPrimes[LIMIT];

static void sieve() {
    int i = 2, j;
    int p = 5;

    smallPrimes[0] = 2;
    smallPrimes[1] = 3;

    while (i < LIMIT) {
        for (j = 0; j < i; j++) {
            if (smallPrimes[j] * smallPrimes[j] <= p) {
                if (p % smallPrimes[j] == 0) {
                    p += 2;
                    break;
                }
            } else {
                smallPrimes[i++] = p;
                p += 2;
                break;
            }
        }
    }
}

static bool is_prime(uint64_t n) {
    uint64_t i;

    for (i = 0; i < LIMIT; i++) {
        if (n % smallPrimes[i] == 0) {
            return n == smallPrimes[i];
        }
    }

    i = smallPrimes[LIMIT - 1] + 2;
    for (; i * i <= n; i += 2) {
        if (n % i == 0) {
            return false;
        }
    }

    return true;
}

static uint64_t divisor_count(uint64_t n) {
    uint64_t count = 1;
    uint64_t d;

    while (n % 2 == 0) {
        n /= 2;
        count++;
    }

    for (d = 3; d * d <= n; d += 2) {
        uint64_t q = n / d;
        uint64_t r = n % d;
        uint64_t dc = 0;
        while (r == 0) {
            dc += count;
            n = q;
            q = n / d;
            r = n % d;
        }
        count += dc;
    }

    if (n != 1) {
        return count *= 2;
    }
    return count;
}

static uint64_t OEISA073916(size_t n) {
    uint64_t count = 0;
    uint64_t result = 0;
    size_t i;

    if (is_prime(n)) {
        return (uint64_t)pow(smallPrimes[n - 1], n - 1);
    }

    for (i = 1; count < n; i++) {
        if (n % 2 == 1) {
            //  The solution for an odd (non-prime) term is always a square number
            uint64_t root = (uint64_t)sqrt(i);
            if (root * root != i) {
                continue;
            }
        }
        if (divisor_count(i) == n) {
            count++;
            result = i;
        }
    }

    return result;
}

int main() {
    size_t n;

    sieve();

    for (n = 1; n <= LIMIT; n++) {
        if (n == 13) {
            printf("A073916(%lu) = One more bit needed to represent result.\n", n);
        } else {
            printf("A073916(%lu) = %llu\n", n, OEISA073916(n));
        }
    }

    return 0;
}


Solution:
def divisors(n):
    divs = [1]
    for ii in range(2, int(n ** 0.5) + 3):
        if n % ii == 0:
            divs.append(ii)
            divs.append(int(n / ii))
    divs.append(n)
    return list(set(divs))

def is_prime(n):
    return len(divisors(n)) == 2

def primes():
    ii = 1
    while True:
        ii += 1
        if is_prime(ii):
            yield ii

def prime(n):
    generator = primes()
    for ii in range(n - 1):
        generator.__next__()
    return generator.__next__()

def n_divisors(n):
    ii = 0
    while True:
        ii += 1
        if len(divisors(ii)) == n:
            yield ii

def sequence(max_n=None):
    if max_n is not None:
        for ii in range(1, max_n + 1):
            if is_prime(ii):
                yield prime(ii) ** (ii - 1)
            else:
                generator = n_divisors(ii)
                for jj, out in zip(range(ii - 1), generator):
                    pass
                yield generator.__next__()
    else:
        ii = 1
        while True:
            ii += 1
            if is_prime(ii):
                yield prime(ii) ** (ii - 1)
            else:
                generator = n_divisors(ii)
                for jj, out in zip(range(ii - 1), generator):
                    pass
                yield generator.__next__()

if __name__ == '__main__':
    for item in sequence(15):
        print(item)


Sequence: smallest number greater than previous term with exactly n divisors

Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.

;Task
Show here, on this page, at least the first '''15''' terms of the sequence.

;See also
:* OEIS:A069654

;Related tasks
:* [[Sequence: smallest number with exactly n divisors]]
:* [[Sequence: nth number with exactly n divisors]]

Solution:
#include

#define MAX 15

int count_divisors(int n) {
    int i, count = 0;
    for (i = 1; i * i <= n; ++i) {
        if (!(n % i)) {
            if (i == n / i)
                count++;
            else
                count += 2;
        }
    }
    return count;
}

int main() {
    int i, next = 1;
    printf("The first %d terms of the sequence are:\n", MAX);
    for (i = 1; next <= MAX; ++i) {
        if (next == count_divisors(i)) {
            printf("%d ", i);
            next++;
        }
    }
    printf("\n");
    return 0;
}


Solution:
def divisors(n):
    divs = [1]
    for ii in range(2, int(n ** 0.5) + 3):
        if n % ii == 0:
            divs.append(ii)
            divs.append(int(n / ii))
    divs.append(n)
    return list(set(divs))

def sequence(max_n=None):
    previous = 0
    n = 0
    while True:
        n += 1
        ii = previous
        if max_n is not None:
            if n > max_n:
                break
        while True:
            ii += 1
            if len(divisors(ii)) == n:
                yield ii
                previous = ii
                break

if __name__ == '__main__':
    for item in sequence(15):
        print(item)


Sequence: smallest number with exactly n divisors

Calculate the sequence where each term   an   is the '''smallest natural number''' that has exactly   '''n'''   divisors.

;Task
Show here, on this page, at least the first  '''15'''  terms of the sequence.

;Related tasks:
:* [[Sequence: smallest number greater than previous term with exactly n divisors]]
:* [[Sequence: nth number with exactly n divisors]]

;See also:
:* OEIS:A005179

Solution:
#include

#define MAX 15

int count_divisors(int n) {
    int i, count = 0;
    for (i = 1; i * i <= n; ++i) {
        if (!(n % i)) {
            if (i == n / i)
                count++;
            else
                count += 2;
        }
    }
    return count;
}

int main() {
    int i, k, n, seq[MAX];
    for (i = 0; i < MAX; ++i) seq[i] = 0;
    printf("The first %d terms of the sequence are:\n", MAX);
    for (i = 1, n = 0; n <  MAX; ++i) {
        k = count_divisors(i);
        if (k <= MAX && seq[k - 1] == 0) {
            seq[k - 1] = i;
            ++n;
        }
    }
    for (i = 0; i < MAX; ++i) printf("%d ", seq[i]);
    printf("\n");
    return 0;
}


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

    // a005179 :: () -> [Int]
    const a005179 = () =>
        fmapGen(
            n => find(
                compose(
                    eq(n),
                    succ,
                    length,
                    properDivisors
                )
            )(enumFrom(1)).Just
        )(enumFrom(1));

    // ------------------------TEST------------------------
    // main :: IO ()
    const main = () =>
        console.log(
            take(15)(
                a005179()
            )
        );

    // [1,2,4,6,16,12,64,24,36,48,1024,60,4096,192,144]

    // -----------------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) =>
        fs.reduce(
            (f, g) => x => f(g(x)),
            x => 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 = succ(v);
        }
    };

    // eq (==) :: Eq a => a -> a -> Bool
    const eq = a =>
        // True when a and b are equivalent in the terms
        // defined below for their shared data type.
        b => a === b;

    // find :: (a -> Bool) -> Gen [a] -> Maybe a
    const find = p => xs => {
        const mb = until(tpl => {
            const nxt = tpl[0];
            return nxt.done || p(nxt.value);
        })(
            tpl => Tuple(tpl[1].next())(
                tpl[1]
            )
        )(Tuple(xs.next())(xs))[0];
        return mb.done ? (
            Nothing()
        ) : Just(mb.value);
    }

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

    // group :: [a] -> [[a]]
    const group = xs => {
        // A list of lists, each containing only equal elements,
        // such that the concatenation of these lists is xs.
        const go = xs =>
            0 < xs.length ? (() => {
                const
                    h = xs[0],
                    i = xs.findIndex(x => h !== x);
                return i !== -1 ? (
                    [xs.slice(0, i)].concat(go(xs.slice(i)))
                ) : [xs];
            })() : [];
        return go(xs);
    };

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

    // liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c]
    const liftA2List = f => xs => ys =>
        // The binary operator f lifted to a function over two
        // lists. f applied to each pair of arguments in the
        // cartesian product of xs and ys.
        xs.flatMap(
            x => ys.map(f(x))
        );

    // mul (*) :: Num a => a -> a -> a
    const mul = a => b => a * b;

    // properDivisors :: Int -> [Int]
    const properDivisors = n =>
        // The ordered divisors of n,
        // excluding n itself.
        1 < n ? (
            sort(group(primeFactors(n)).reduce(
                (a, g) => liftA2List(mul)(a)(
                    scanl(mul)([1])(g)
                ),
                [1]
            )).slice(0, -1)
        ) : [];

    // primeFactors :: Int -> [Int]
    const primeFactors = n => {
        // A list of the prime factors of n.
        const
            go = x => {
                const
                    root = Math.floor(Math.sqrt(x)),
                    m = until(
                        ([q, _]) => (root < q) || (0 === (x % q))
                    )(
                        ([_, r]) => [step(r), 1 + r]
                    )(
                        [0 === x % 2 ? 2 : 3, 1]
                    )[0];
                return m > root ? (
                    [x]
                ) : ([m].concat(go(Math.floor(x / m))));
            },
            step = x => 1 + (x << 2) - ((x >> 1) << 1);
        return go(n);
    };

    // scanl :: (b -> a -> b) -> b -> [a] -> [b]
    const scanl = f => startValue => xs =>
        xs.reduce((a, x) => {
            const v = f(a[0])(x);
            return Tuple(v)(a[1].concat(v));
        }, Tuple(startValue)([startValue]))[1];

    // sort :: Ord a => [a] -> [a]
    const sort = xs => xs.slice()
        .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));

    // succ :: Enum a => a -> a
    const succ = x =>
        1 + x;

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

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

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


Solution:
def divisors(n):
    divs = [1]
    for ii in range(2, int(n ** 0.5) + 3):
        if n % ii == 0:
            divs.append(ii)
            divs.append(int(n / ii))
    divs.append(n)
    return list(set(divs))

def sequence(max_n=None):
    n = 0
    while True:
        n += 1
        ii = 0
        if max_n is not None:
            if n > max_n:
                break
        while True:
            ii += 1
            if len(divisors(ii)) == n:
                yield ii
                break

if __name__ == '__main__':
    for item in sequence(15):
        print(item)


Set consolidation

Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:
*  The two input sets if no common item exists between the two input sets of items.
*  The single set that is the union of the two input sets if they share a common item.

Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.

;'''Example 1:'''
:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
;'''Example 2:'''
:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}.  (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
;'''Example 3:'''
:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
;'''Example 4:'''
:The consolidation of the five sets:
::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
:Is the two sets:
::{A, C, B, D}, and {G, F, I, H, K}

'''See also'''
* Connected component (graph theory)
* [[Range consolidation]]

Solution:
#include
#include
#include

struct edge { int to; struct edge *next; };
struct node { int group; struct edge *e; };

int **consolidate(int **x)
{
#	define alloc(v, size) v = calloc(size, sizeof(v[0]));
	int group, n_groups, n_nodes;
	int n_edges = 0;
	struct edge *edges, *ep;
	struct node *nodes;
	int pos, *stack, **ret;

	void add_edge(int a, int b) {
		ep->to = b;
		ep->next = nodes[a].e;
		nodes[a].e = ep;
		ep++;
	}

	void traverse(int a) {
		if (nodes[a].group) return;

		nodes[a].group = group;
		stack[pos++] = a;

		for (struct edge *e = nodes[a].e; e; e = e->next)
			traverse(e->to);
	}

	n_groups = n_nodes = 0;
	for (int i = 0; x[i]; i++, n_groups++)
		for (int j = 0; x[i][j]; j++) {
			n_edges ++;
			if (x[i][j] >= n_nodes)
				n_nodes = x[i][j] + 1;
		}

	alloc(ret, n_nodes);
	alloc(nodes, n_nodes);
	alloc(stack, n_nodes);
	ep = alloc(edges, n_edges);

	for (int i = 0; x[i]; i++)
		for (int *s = x[i], j = 0; s[j]; j++)
			add_edge(s[j], s[j + 1] ? s[j + 1] : s[0]);

	group = 0;
	for (int i = 1; i < n_nodes; i++) {
		if (nodes[i].group) continue;

		group++, pos = 0;
		traverse(i);

		stack[pos++] = 0;
		ret[group - 1] = malloc(sizeof(int) * pos);
		memcpy(ret[group - 1], stack, sizeof(int) * pos);
	}

	free(edges);
	free(stack);
	free(nodes);

	// caller is responsible for freeing ret
	return realloc(ret, sizeof(ret[0]) * (1 + group));
#	undef alloc
}

void show_sets(int **x)
{
	for (int i = 0; x[i]; i++) {
		printf("%d: ", i);
		for (int j = 0; x[i][j]; j++)
			printf(" %d", x[i][j]);
		putchar('\n');
	}
}

int main(void)
{
	int *x[] = {
		(int[]) {1, 2, 0},	// 0: end of set
		(int[]) {3, 4, 0},
		(int[]) {3, 1, 0},
		(int[]) {0},		// empty set
		(int[]) {5, 6, 0},
		(int[]) {7, 6, 0},
		(int[]) {3, 9, 10, 0},
		0			// 0: end of sets
	};

	puts("input:");
	show_sets(x);

	puts("components:");
	show_sets(consolidate(x));

	return 0;
}


Set consolidation

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

    // consolidated :: Ord a => [Set a] -> [Set a]
    const consolidated = xs => {
        const go = (s, xs) =>
            0 !== xs.length ? (() => {
                const h = xs[0];
                return 0 === intersection(h, s).size ? (
                    [h].concat(go(s, tail(xs)))
                ) : go(union(h, s), tail(xs));
            })() : [s];
        return foldr(go, [], xs);
    };

    // TESTS ----------------------------------------------
    const main = () =>
        map(xs => intercalate(
                ', and ',
                map(showSet, consolidated(xs))
            ),
            map(x => map(
                    s => new Set(chars(s)),
                    x
                ),
                [
                    ['ab', 'cd'],
                    ['ab', 'bd'],
                    ['ab', 'cd', 'db'],
                    ['hik', 'ab', 'cd', 'db', 'fgh']
                ]
            )
        ).join('\n');

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

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

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

    // elems :: Dict -> [a]
    // elems :: Set -> [a]
    const elems = x =>
        'Set' !== x.constructor.name ? (
            Object.values(x)
        ) : Array.from(x.values());

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

    // Note that that the Haskell signature of foldr differs from that of
    // foldl - the positions of accumulator and current value are reversed

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

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

    // intersection :: Ord a => Set a -> Set a -> Set a
    const intersection = (s, s1) =>
        new Set([...s].filter(x => s1.has(x)));

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

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

    // showSet :: Set -> String
    const showSet = s =>
        intercalate(elems(s), ['{', '}']);

    // sort :: Ord a => [a] -> [a]
    const sort = xs => xs.slice()
        .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));

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

    // union :: Ord a => Set a -> Set a -> Set a
    const union = (s, s1) =>
        Array.from(s1.values())
        .reduce(
            (a, x) => (a.add(x), a),
            new Set(s)
        );

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


Set consolidation

Solution:
def _test(consolidate=consolidate):

    def freze(list_of_sets):
        'return a set of frozensets from the list of sets to allow comparison'
        return set(frozenset(s) for s in list_of_sets)

    # Define some variables
    A,B,C,D,E,F,G,H,I,J,K = 'A,B,C,D,E,F,G,H,I,J,K'.split(',')
    # Consolidate some lists of sets
    assert (freze(consolidate([{A,B}, {C,D}])) == freze([{'A', 'B'}, {'C', 'D'}]))
    assert (freze(consolidate([{A,B}, {B,D}])) == freze([{'A', 'B', 'D'}]))
    assert (freze(consolidate([{A,B}, {C,D}, {D,B}])) == freze([{'A', 'C', 'B', 'D'}]))
    assert (freze(consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])) ==
             freze([{'A', 'C', 'B', 'D'}, {'G', 'F', 'I', 'H', 'K'}]))
    assert (freze(consolidate([{A,H}, {H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])) ==
             freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]))
    assert (freze(consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}])) ==
             freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]))
    # Confirm order-independence
    from copy import deepcopy
    import itertools
    sets = [{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}]
    answer = consolidate(deepcopy(sets))
    for perm in itertools.permutations(sets):
            assert consolidate(deepcopy(perm)) == answer

    assert (answer == [{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}])
    assert (len(list(itertools.permutations(sets))) == 720)

    print('_test(%s) complete' % consolidate.__name__)

if __name__ == '__main__':
    _test(consolidate)
    _test(conso)


Set of real numbers

All real numbers form the uncountable set ℝ.  Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' ≤ ''b''.  There are actually four cases for the meaning of "between", depending on open or closed boundary:
* [''a'', ''b'']: {''x'' | ''a'' ≤ ''x'' and ''x'' ≤ ''b'' }
* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }
* [''a'', ''b''): {''x'' | ''a'' ≤ ''x'' and ''x'' < ''b'' }
* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' ≤ ''b'' }
Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.

'''Task'''
* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):
:* ''x'' ∈ ''A'': determine if ''x'' is an element of ''A''
:: example: 1 is in [1, 2), while 2, 3, ... are not.
:* ''A'' ∪ ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ∈ ''A'' or ''x'' ∈ ''B''}
:: example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
:* ''A'' ∩ ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ∈ ''A'' and ''x'' ∈ ''B''}
:: example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \ ''B'', i.e. {''x'' | ''x'' ∈ ''A'' and ''x'' ∉ ''B''}
:: example: [0, 2) − (1, 3) = [0, 1]
* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
:* (0, 1] ∪ [0, 2)
:* [0, 2) ∩ (1, 2]
:* [0, 3) − (0, 1)
:* [0, 3) − [0, 1]

'''Implementation notes'''
* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'.  Cantor's set needs not apply.
* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).

'''Optional work'''
* Create a function to determine if a given set is empty (contains no element).
* Define ''[http://www.wolframalpha.com/input/?i=%7Csin%28pi+x2%29%7C%3E1%2F2%2C+0+%3C+x+%3C+10 A]'' = {''x'' | 0 < ''x'' < 10 and |sin(π ''x''²)| > 1/2 }, ''[http://www.wolframalpha.com/input/?i=%7Csin%28pi+x%29%7C%3E1%2F2%2C+0+%3C+x+%3C+10 B]'' = {''x'' | 0 < ''x'' < 10 and |sin(π ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' − ''B''.  Note that
|sin(π ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.

Solution:
#include
#include
#include
#include

struct RealSet {
    bool(*contains)(struct RealSet*, struct RealSet*, double);
    struct RealSet *left;
    struct RealSet *right;
    double low, high;
};

typedef enum {
    CLOSED,
    LEFT_OPEN,
    RIGHT_OPEN,
    BOTH_OPEN,
} RangeType;

double length(struct RealSet *self) {
    const double interval = 0.00001;
    double p = self->low;
    int count = 0;

    if (isinf(self->low) || isinf(self->high)) return -1.0;
    if (self->high <= self->low) return 0.0;

    do {
        if (self->contains(self, NULL, p)) count++;
        p += interval;
    } while (p < self->high);
    return count * interval;
}

bool empty(struct RealSet *self) {
    if (self->low == self->high) {
        return !self->contains(self, NULL, self->low);
    }
    return length(self) == 0.0;
}

static bool contains_closed(struct RealSet *self, struct RealSet *_, double d) {
    return self->low <= d && d <= self->high;
}

static bool contains_left_open(struct RealSet *self, struct RealSet *_, double d) {
    return self->low < d && d <= self->high;
}

static bool contains_right_open(struct RealSet *self, struct RealSet *_, double d) {
    return self->low <= d && d < self->high;
}

static bool contains_both_open(struct RealSet *self, struct RealSet *_, double d) {
    return self->low < d && d < self->high;
}

static bool contains_intersect(struct RealSet *self, struct RealSet *_, double d) {
    return self->left->contains(self->left, NULL, d) && self->right->contains(self->right, NULL, d);
}

static bool contains_union(struct RealSet *self, struct RealSet *_, double d) {
    return self->left->contains(self->left, NULL, d) || self->right->contains(self->right, NULL, d);
}

static bool contains_subtract(struct RealSet *self, struct RealSet *_, double d) {
    return self->left->contains(self->left, NULL, d) && !self->right->contains(self->right, NULL, d);
}

struct RealSet* makeSet(double low, double high, RangeType type) {
    bool(*contains)(struct RealSet*, struct RealSet*, double);
    struct RealSet *rs;

    switch (type) {
    case CLOSED:
        contains = contains_closed;
        break;
    case LEFT_OPEN:
        contains = contains_left_open;
        break;
    case RIGHT_OPEN:
        contains = contains_right_open;
        break;
    case BOTH_OPEN:
        contains = contains_both_open;
        break;
    default:
        return NULL;
    }

    rs = malloc(sizeof(struct RealSet));
    rs->contains = contains;
    rs->left = NULL;
    rs->right = NULL;
    rs->low = low;
    rs->high = high;
    return rs;
}

struct RealSet* makeIntersect(struct RealSet *left, struct RealSet *right) {
    struct RealSet *rs = malloc(sizeof(struct RealSet));
    rs->contains = contains_intersect;
    rs->left = left;
    rs->right = right;
    rs->low = fmin(left->low, right->low);
    rs->high = fmin(left->high, right->high);
    return rs;
}

struct RealSet* makeUnion(struct RealSet *left, struct RealSet *right) {
    struct RealSet *rs = malloc(sizeof(struct RealSet));
    rs->contains = contains_union;
    rs->left = left;
    rs->right = right;
    rs->low = fmin(left->low, right->low);
    rs->high = fmin(left->high, right->high);
    return rs;
}

struct RealSet* makeSubtract(struct RealSet *left, struct RealSet *right) {
    struct RealSet *rs = malloc(sizeof(struct RealSet));
    rs->contains = contains_subtract;
    rs->left = left;
    rs->right = right;
    rs->low = left->low;
    rs->high = left->high;
    return rs;
}

int main() {
    struct RealSet *a = makeSet(0.0, 1.0, LEFT_OPEN);
    struct RealSet *b = makeSet(0.0, 2.0, RIGHT_OPEN);
    struct RealSet *c = makeSet(1.0, 2.0, LEFT_OPEN);
    struct RealSet *d = makeSet(0.0, 3.0, RIGHT_OPEN);
    struct RealSet *e = makeSet(0.0, 1.0, BOTH_OPEN);
    struct RealSet *f = makeSet(0.0, 1.0, CLOSED);
    struct RealSet *g = makeSet(0.0, 0.0, CLOSED);
    int i;

    for (i = 0; i < 3; ++i) {
        struct RealSet *t;

        t = makeUnion(a, b);
        printf("(0, 1]   union   [0, 2) contains %d is %d\n", i, t->contains(t, NULL, i));
        free(t);

        t = makeIntersect(b, c);
        printf("[0, 2) intersect (1, 2] contains %d is %d\n", i, t->contains(t, NULL, i));
        free(t);

        t = makeSubtract(d, e);
        printf("[0, 3)     -     (0, 1) contains %d is %d\n", i, t->contains(t, NULL, i));
        free(t);

        t = makeSubtract(d, f);
        printf("[0, 3)     -     [0, 1] contains %d is %d\n", i, t->contains(t, NULL, i));
        free(t);

        printf("\n");
    }

    printf("[0, 0] is empty %d\n", empty(g));

    free(a);
    free(b);
    free(c);
    free(d);
    free(e);
    free(f);
    free(g);

    return 0;
}


Set of real numbers

Solution:
class Setr():
    def __init__(self, lo, hi, includelo=True, includehi=False):
        self.eqn = "(%i<%sX<%s%i)" % (lo,
                                      '=' if includelo else '',
                                      '=' if includehi else '',
                                      hi)

    def __contains__(self, X):
        return eval(self.eqn, locals())

    # union
    def __or__(self, b):
        ans = Setr(0,0)
        ans.eqn = "(%sor%s)" % (self.eqn, b.eqn)
        return ans

    # intersection
    def __and__(self, b):
        ans = Setr(0,0)
        ans.eqn = "(%sand%s)" % (self.eqn, b.eqn)
        return ans

    # difference
    def __sub__(self, b):
        ans = Setr(0,0)
        ans.eqn = "(%sand not%s)" % (self.eqn, b.eqn)
        return ans

    def __repr__(self):
        return "Setr%s" % self.eqn

sets = [
    Setr(0,1, 0,1) | Setr(0,2, 1,0),
    Setr(0,2, 1,0) & Setr(1,2, 0,1),
    Setr(0,3, 1,0) - Setr(0,1, 0,0),
    Setr(0,3, 1,0) - Setr(0,1, 1,1),
]
settexts = '(0, 1] ∪ [0, 2);[0, 2) ∩ (1, 2];[0, 3) − (0, 1);[0, 3) − [0, 1]'.split(';')

for s,t in zip(sets, settexts):
    print("Set %s %s. %s" % (t,
                             ', '.join("%scludes %i"
                                     % ('in' if v in s else 'ex', v)
                                     for v in range(3)),
                             s.eqn))


Set right-adjacent bits

Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
* Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).

'''Some examples:'''

    Set of examples showing how one bit in a nibble gets changed:

        n = 2; Width e = 4:

             Input b: 1000
              Result: 1110

             Input b: 0100
              Result: 0111

             Input b: 0010
              Result: 0011

             Input b: 0000
              Result: 0000

    Set of examples with the same input with set bits of varying distance apart:

        n = 0; Width e = 66:

             Input b: 010000000000100000000010000000010000000100000010000010000100010010
              Result: 010000000000100000000010000000010000000100000010000010000100010010

        n = 1; Width e = 66:

             Input b: 010000000000100000000010000000010000000100000010000010000100010010
              Result: 011000000000110000000011000000011000000110000011000011000110011011

        n = 2; Width e = 66:

             Input b: 010000000000100000000010000000010000000100000010000010000100010010
              Result: 011100000000111000000011100000011100000111000011100011100111011111

        n = 3; Width e = 66:

             Input b: 010000000000100000000010000000010000000100000010000010000100010010
              Result: 011110000000111100000011110000011110000111100011110011110111111111

'''Task:'''

* Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e.
* Use it to show, here, the results for the input examples above.
* Print the output aligned in a way that allows easy checking by eye of the binary input vs output.

Solution:
from operator import or_
from functools import reduce

def set_right_adjacent_bits(n: int, b: int) -> int:
    return reduce(or_, (b >> x for x in range(n+1)), 0)

if __name__ == "__main__":
    print("SAME n & Width.\n")
    n = 2  # bits to the right of set bits, to also set
    bits = "1000 0100 0010 0000"
    first = True
    for b_str in bits.split():
        b = int(b_str, 2)
        e = len(b_str)
        if first:
            first = False
            print(f"n = {n}; Width e = {e}:\n")
        result = set_right_adjacent_bits(n, b)
        print(f"     Input b: {b:0{e}b}")
        print(f"      Result: {result:0{e}b}\n")

    print("SAME Input & Width.\n")
    #bits = "01000010001001010110"
    bits = '01' + '1'.join('0'*x for x in range(10, 0, -1))
    for n in range(4):
        first = True
        for b_str in bits.split():
            b = int(b_str, 2)
            e = len(b_str)
            if first:
                first = False
                print(f"n = {n}; Width e = {e}:\n")
            result = set_right_adjacent_bits(n, b)
            print(f"     Input b: {b:0{e}b}")
            print(f"      Result: {result:0{e}b}\n")


Shoelace formula for polygonal area

Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:

abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
     (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
   ) / 2
(Where abs returns the absolute value)

;Task:
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
      (3,4), (5,11), (12,8), (9,5), and (5,6)

Show the answer here, on this page.

Solution:
#include
#include
#include

typedef struct{
	double x,y;
}point;

double shoelace(char* inputFile){
	int i,numPoints;
	double leftSum = 0,rightSum = 0;

	point* pointSet;
	FILE* fp = fopen(inputFile,"r");

	fscanf(fp,"%d",&numPoints);

	pointSet = (point*)malloc((numPoints + 1)*sizeof(point));

	for(i=0;i",argV[0]);

	else
		printf("The polygon area is %lf square units.",shoelace(argV[1]));

	return 0;
}


Shoelace formula for polygonal area

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

    // ------- SHOELACE FORMULA FOR POLYGONAL AREA -------

    // shoelaceArea :: [(Float, Float)] -> Float
    const shoeLaceArea = vertices => abs(
        uncurry(subtract)(
            ap(zip)(compose(tail, cycle))(
                vertices
            )
            .reduce(
                (a, x) => [0, 1].map(b => {
                    const n = Number(b);

                    return a[n] + (
                        x[0][n] * x[1][Number(!b)]
                    );
                }),
                [0, 0]
            )
        )
    ) / 2;

    // ----------------------- TEST -----------------------
    const main = () => {
        const ps = [
            [3, 4],
            [5, 11],
            [12, 8],
            [9, 5],
            [5, 6]
        ];

        return [
                "Polygonal area by shoelace formula:",
                `${JSON.stringify(ps)} -> ${shoeLaceArea(ps)}`
            ]
            .join("\n");
    };

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

    // abs :: Num -> Num
    const abs = x =>
        // Absolute value of a given number
        // without the sign.
        0 > x ? -x : x;

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

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

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

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

    // length :: [a] -> Int
    const length = xs =>
        // Returns Infinity over objects without finite
        // length. This enables zip and zipWith to choose
        // the shorter argument when one is non-finite,
        // like cycle, repeat etc
        "GeneratorFunction" !== xs.constructor
        .constructor.name ? (
            xs.length
        ) : Infinity;

    // subtract :: Num -> Num -> Num
    const subtract = x =>
        y => y - x;

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

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

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

    // uncurry :: (a -> b -> c) -> ((a, b) -> c)
    const uncurry = f =>
        // A function over a pair, derived
        // from a curried function.
        (...args) => {
            const [x, y] = Boolean(args.length % 2) ? (
                args[0]
            ) : args;

            return f(x)(y);
        };

    // zip :: [a] -> [b] -> [(a, b)]
    const zip = xs => ys => {
        const
            n = Math.min(length(xs), length(ys)),
            vs = take(n)(ys);

        return take(n)(xs)
            .map((x, i) => [x, vs[i]]);
    };

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


Shoelace formula for polygonal area

Solution:
# Even simpler:
# In python we can take an advantage of that x[-1] refers to the last element in an array, same as x[N-1].
# Introducing the index i=[0,1,2,...,N-1]; i-1=[-1,0,...,N-2]; N is the number of vertices of a polygon.
# Thus x[i] is a sequence of the x-coordinate of the polygon vertices, x[i-1] is the sequence shifted by 1 index.
# Note that the shift must be negative. The positive shift x[i+1] results in an error: x[N] index out of bound.

import numpy as np
# x,y are arrays containing coordinates of the polygon vertices
x=np.array([3,5,12,9,5])
y=np.array([4,11,8,5,6])
i=np.arange(len(x))
#Area=np.sum(x[i-1]*y[i]-x[i]*y[i-1])*0.5 # signed area, positive if the vertex sequence is counterclockwise
Area=np.abs(np.sum(x[i-1]*y[i]-x[i]*y[i-1])*0.5) # one line of code for the shoelace formula

# Remember that applying the Shoelace formula
# will result in a loss of precision if x,y have big offsets.
# Remove the offsets first, e.g.
# x=x-np.mean(x);y=y-np.mean(y)
# or
# x=x-x[0];y=y-y[0]
# before applying the Shoelace formula.


Shoelace formula for polygonal area

Solution:
'''Polygonal area by shoelace formula'''

from itertools import cycle, islice
from functools import reduce
from operator import sub

# --------- SHOELACE FORMULA FOR POLYGONAL AREA ----------

# shoelaceArea :: [(Float, Float)] -> Float
def shoelaceArea(xys):
    '''Area of polygon with vertices
       at (x, y) points in xys.
    '''
    def go(a, tpl):
        l, r = a
        (x, y), (dx, dy) = tpl
        return l + x * dy, r + y * dx

    return abs(sub(*reduce(
        go,
        zip(
            xys,
            islice(cycle(xys), 1, None)
        ),
        (0, 0)
    ))) / 2

# ------------------------- TEST -------------------------
# main :: IO()
def main():
    '''Sample calculation'''

    ps = [(3, 4), (5, 11), (12, 8), (9, 5), (5, 6)]
    print(__doc__ + ':')
    print(repr(ps) + '  ->  ' + str(shoelaceArea(ps)))

if __name__ == '__main__':
    main()


Shortest common supersequence

The   '''shortest common supersequence'''   is a problem closely related to the   [[longest common subsequence]],   which you can use as an external function for this task.

;;Task:
Given two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s.  Defined as such, s is not necessarily unique.

Demonstrate this by printing s where u = “abcbdab” and v = “bdcaba”.

;Also see:
* Wikipedia: shortest common supersequence

Solution:
#include
#include

typedef struct link link_t;
struct link {
	int len;
	char letter;
	link_t *next;
};

// Stores a copy of a SCS of x and y in out.  Caller needs to make sure out is long enough.
int scs(char *x, char *y, char *out)
{
	int lx = strlen(x), ly = strlen(y);
	link_t lnk[ly + 1][lx + 1];

	for (int i = 0; i < ly; i++)
		lnk[i][lx] = (link_t) {ly - i, y[i], &lnk[i + 1][lx]};

	for (int j = 0; j < lx; j++)
		lnk[ly][j] = (link_t) {lx - j, x[j], &lnk[ly][j + 1]};

	lnk[ly][lx] = (link_t) {0};

	for (int i = ly; i--; ) {
		for (int j = lx; j--; ) {
			link_t *lp = &lnk[i][j];
			if (y[i] == x[j]) {
				lp->next = &lnk[i+1][j+1];
				lp->letter = x[j];
			} else if (lnk[i][j+1].len < lnk[i+1][j].len) {
				lp->next = &lnk[i][j+1];
				lp->letter = x[j];
			} else {
				lp->next = &lnk[i+1][j];
				lp->letter = y[i];
			}
			lp->len = lp->next->len + 1;
		}
	}

	for (link_t *lp = &lnk[0][0]; lp; lp = lp->next)
		*out++ = lp->letter;

	return 0;
}

int main(void)
{
	char x[] = "abcbdab", y[] = "bdcaba", res[128];
	scs(x, y, res);
	printf("SCS(%s, %s) -> %s\n", x, y, res);
	return 0;
}


Shortest common supersequence

Solution:
# Use the Longest Common Subsequence algorithm

def shortest_common_supersequence(a, b):
    lcs = longest_common_subsequence(a, b)
    scs = ""
    # Consume lcs
    while len(lcs) > 0:
        if a[0]==lcs[0] and b[0]==lcs[0]:
        # Part of the LCS, so consume from all strings
            scs += lcs[0]
            lcs = lcs[1:]
            a = a[1:]
            b = b[1:]
        elif a[0]==lcs[0]:
            scs += b[0]
            b = b[1:]
        else:
            scs += a[0]
            a = a[1:]
    # append remaining characters
    return scs + a + b


Show ASCII table

;Task:
Show  [https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/ASCII-Table.svg/1261px-ASCII-Table.svg.png the ASCII character set]  from values   '''32'''   to   '''127'''   (decimal)   in a table format.

Solution:
#include

int main() {
    int i, j;
    char k[4];
    for (i = 0; i < 16; ++i) {
        for (j = 32 + i; j < 128; j += 16) {
            switch (j) {
                default:  sprintf(k, "%c", j); break;
                case 32:  sprintf(k, "Spc"); break;
                case 127: sprintf(k, "Del"); break;
            }
            printf("%3d : %-3s   ", j, k);
        }
        printf("\n");
    }
    return 0;
}


Show ASCII table

Solution:
(() => {

    "use strict";

    // ------------------- ASCII TABLE -------------------

    // asciiTable :: String
    const asciiTable = () =>
        transpose(
            chunksOf(16)(
                enumFromTo(32)(127)
                .map(asciiEntry)
            )
        )
        .map(
            xs => xs.map(justifyLeft(12)(" "))
            .join("")
        )
        .join("\n");

    // asciiEntry :: Int -> String
    const asciiEntry = n => {
        const k = asciiName(n);

        return "" === k ? (
            ""
        ) : `${justifyRight(4)(" ")(n.toString())} : ${k}`;
    };

    // asciiName :: Int -> String
    const asciiName = n =>
        32 > n || 127 < n ? (
            ""
        ) : 32 === n ? (
            "Spc"
        ) : 127 === n ? (
            "Del"
        ) : chr(n);

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

    // chr :: Int -> Char
    const chr = x =>
        // The character at unix code-point x.
        String.fromCodePoint(x);

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

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

        return go;
    };

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

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

    // 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 => Boolean(s) ? (
            s.padStart(n, c)
        ) : "";

    // transpose :: [[a]] -> [[a]]
    const transpose = rows =>
        // The columns of the input transposed
        // into new rows.
        // This version assumes input rows of even length.
        0 < rows.length ? rows[0].map(
            (x, i) => rows.flatMap(
                v => v[i]
            )
        ) : [];

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


Show ASCII table

Solution:
for i in range(16):
    for j in range(32+i, 127+1, 16):
        if j == 32:
            k = 'Spc'
        elif j == 127:
            k = 'Del'
        else:
            k = chr(j)
        print("%3d : %-3s" % (j,k), end="")
    print()


Show the epoch

;Task:
Choose popular date libraries used by your language and show the   epoch   those libraries use.

A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.

For consistency's sake, show the date in UTC time where possible.

;Related task:
*   [[Date format]]

Solution:
#include
#include

int main() {
    time_t t = 0;
    printf("%s", asctime(gmtime(&t)));
    return 0;
}


Show the epoch

Solution:
>>> import time
>>> time.asctime(time.gmtime(0))
'Thu Jan  1 00:00:00 1970'
>>>


Sierpinski pentagon

Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.

;See also
* [http://ecademy.agnesscott.edu/~lriddle/ifs/pentagon/pentagon.htm Sierpinski pentagon]

Solution:
#include
#include
#include
#include
#include

#define pi M_PI

int main(){

	time_t t;
	double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
	int i,iter,choice,numSides;

	printf("Enter number of sides : ");
	scanf("%d",&numSides);

	printf("Enter polygon side length : ");
	scanf("%lf",&side);

	printf("Enter number of iterations : ");
	scanf("%d",&iter);

	initwindow(windowSide,windowSide,"Polygon Chaos");

	vertices = (double**)malloc(numSides*sizeof(double*));

	for(i=0;i


Sierpinski pentagon

Solution:
Click Pentaflake to iterate.  Order: 0

 	(Reset anytime: to start new Pentaflake and change color.)


Sierpinski pentagon

Solution:
from turtle import *
import math
speed(0)      # 0 is the fastest speed. Otherwise, 1 (slow) to 10 (fast)
hideturtle()  # hide the default turtle

part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)

hide_turtles = True   # show/hide turtles as they draw
path_color = "black"  # path color
fill_color = "black"  # fill color

# turtle, size
def pentagon(t, s):
  t.color(path_color, fill_color)
  t.pendown()
  t.right(36)
  t.begin_fill()
  for i in range(5):
    t.forward(s)
    t.right(72)
  t.end_fill()

# iteration, turtle, size
def sierpinski(i, t, s):
  t.setheading(0)
  new_size = s * side_ratio

  if i > 1:
    i -= 1

    # create four more turtles
    for j in range(4):
      t.right(36)
      short = s * side_ratio / part_ratio
      dist = [short, s, s, short][j]

      # spawn a turtle
      spawn = Turtle()
      if hide_turtles:spawn.hideturtle()
      spawn.penup()
      spawn.setposition(t.position())
      spawn.setheading(t.heading())
      spawn.forward(dist)

      # recurse for spawned turtles
      sierpinski(i, spawn, new_size)

    # recurse for parent turtle
    sierpinski(i, t, new_size)

  else:
    # draw a pentagon
    pentagon(t, s)
    # delete turtle
    del t

def main():
  t = Turtle()
  t.hideturtle()
  t.penup()
  screen = t.getscreen()
  y = screen.window_height()
  t.goto(0, y/2-20)

  i = 5       # depth. i >= 1
  size = 300  # side length

  # so the spawned turtles move only the distance to an inner pentagon
  size *= part_ratio

  # begin recursion
  sierpinski(i, t, size)

main()


Sierpinski triangle/Graphical

Produce a graphical representation of a Sierpinski triangle of order N in any orientation.

An example of Sierpinski's triangle (order = 8) looks like this:
[[File:Sierpinski_Triangle_Unicon.PNG]]

Solution:
#include
#include
#include
#include

long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;

void sc_up()
{
	scale *= 2; x *= 2; y *= 2;
	cscale *= 3;
}

void h_rgb(long long x, long long y)
{
	rgb *p = &pix[y][x];

#	define SAT 1
	double h = 6.0 * clen / cscale;
	double VAL = 1;
	double c = SAT * VAL;
	double X = c * (1 - fabs(fmod(h, 2) - 1));

	switch((int)h) {
	case 0: p->r += c; p->g += X; return;
	case 1:	p->r += X; p->g += c; return;
	case 2: p->g += c; p->b += X; return;
	case 3: p->g += X; p->b += c; return;
	case 4: p->r += X; p->b += c; return;
	default:
		p->r += c; p->b += X;
	}
}

void iter_string(const char * str, int d)
{
	long long len;
	while (*str != '\0') {
		switch(*(str++)) {
		case 'X':
			if (d)	iter_string("XHXVX", d - 1);
			else{
				clen ++;
				h_rgb(x/scale, y/scale);
				x += dx;
				y -= dy;
			}
			continue;
		case 'V':
			len = 1LLU << d;
			while (len--) {
				clen ++;
				h_rgb(x/scale, y/scale);
				y += dy;
			}
			continue;
		case 'H':
			len = 1LLU << d;
			while(len --) {
				clen ++;
				h_rgb(x/scale, y/scale);
				x -= dx;
			}
			continue;
		}
	}
}

void sierp(long leng, int depth)
{
	long i;
	long h = leng + 20, w = leng + 20;

	/* allocate pixel buffer */
	rgb *buf = malloc(sizeof(rgb) * w * h);
	pix = malloc(sizeof(rgb *) * h);
	for (i = 0; i < h; i++)
		pix[i] = buf + w * i;
	memset(buf, 0, sizeof(rgb) * w * h);

        /* init coords; scale up to desired; exec string */
	x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;
	for (i = 0; i < depth; i++) sc_up();
	iter_string("VXH", depth);

	/* write color PNM file */
	unsigned char *fpix = malloc(w * h * 3);
	double maxv = 0, *dbuf = (double*)buf;

	for (i = 3 * w * h - 1; i >= 0; i--)
		if (dbuf[i] > maxv) maxv = dbuf[i];
	for (i = 3 * h * w - 1; i >= 0; i--)
		fpix[i] = 255 * dbuf[i] / maxv;

	printf("P6\n%ld %ld\n255\n", w, h);
	fflush(stdout); /* printf and fwrite may treat buffer differently */
	fwrite(fpix, h * w * 3, 1, stdout);
}

int main(int c, char ** v)
{
	int size, depth;

	depth  = (c > 1) ? atoi(v[1]) : 10;
	size = 1 << depth;

	fprintf(stderr, "size: %d depth: %d\n", size, depth);
	sierp(size, depth + 2);

	return 0;
}


Sierpinski triangle/Graphical

Solution:
;Note:
* "Order" to calculate a size of resulting plot/matrix is not used in this algorithm, Instead, construction is done in accordance to a square   m x m matrix. In our case it should be equal to a size of the square canvas.
* Change canvas setting from size "640" to "1280". You will discover that density of dots in plotted triangle is stable for this algorithm. Size of the plotted figure is constantly increasing in the S-E direction. Also, the number of all triangles in N-W triangular part of the canvas is always the same.
* So, in this case it could be called: "Sierpinski ever-expanding field of triangles".
<br>


Sierpinski triangle/Graphical

Solution:
Sierpinski Triangle Fractal

Please click to start and/or change color:

  Sierpinski triangle fractal


Sierpinski triangle/Graphical

Solution:
##########################################################################################
#		The drawing function
#		--------------------
#
# level		level of Sierpinski triangle (minimum value = 1)
# ss		screensize (Draws on a screen of size ss x ss. Default value = 400.)
#-----------------------------------------------------------------------------------------
def DrawSierpinskiTriangle(level, ss=400):
	# typical values
	turn = 0		# initial turn (0 to start horizontally)
	angle=60.0 		# in degrees

	# Initialize the turtle
	turtle.hideturtle()
	turtle.screensize(ss,ss)
	turtle.penup()
	turtle.degrees()

	# The starting point on the canvas
	fwd0         = float(ss)
	point=array([-fwd0/2.0, -fwd0/2.0])

	# Setting up the Lindenmayer system
	# Assuming that the triangle will be drawn in the following way:
	#	1.) Start at a point
	#	2.) Draw a straight line - the horizontal line (H)
	#	3.) Bend twice by 60 degrees to the left (--)
	#	4.) Draw a straight line - the slanted line (X)
	#	5.) Bend twice by 60 degrees to the left (--)
	#	6.) Draw a straight line - another slanted line (X)
	# 		This produces the triangle in the first level. (so the axiom to begin with is H--X--X)
	#	7.) For the next level replace each horizontal line using
	#		X->XX
	#		H -> H--X++H++X--H
	#			The lengths will be halved.

	decode    = {'-':Left, '+':Right, 'X':Forward, 'H':Forward}
	axiom     = 'H--X--X'

	# Start the drawing
	turtle.goto(point[0], point[1])
	turtle.pendown()
	turtle.hideturtle()
	turt=turtle.getpen()
	startposition=turt.clone()

	# Get the triangle in the Lindenmayer system
	fwd       = fwd0/(2.0**level)
	path      = axiom
	for i in range(0,level):
		path=path.replace('X','XX')
		path=path.replace('H','H--X++H++X--H')

	# Draw it.
	for i in path:
		[turn, point, fwd, angle, turt]=decode[i](turn, point, fwd, angle, turt)
##########################################################################################

DrawSierpinskiTriangle(5)


Simple turtle graphics

The first turtle graphic discussed in [https://mindstorms.media.mit.edu Mindstorms: Children, Computers, and Powerful Ideas] by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.

For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.

thumb

;Task:
::* Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as depicted. Optionally make it lovely by adding details such as, for example, doors and windows.

::* Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.

::* Both functions should return the turtle to the location it was at and facing in the same direction  as it was immediately before the function was executed.

Solution:
from turtle import *

def rectangle(width, height):
    for _ in range(2):
        forward(height)
        left(90)
        forward(width)
        left(90)

def square(size):
    rectangle(size, size)

def triangle(size):
    for _ in range(3):
        forward(size)
        right(120)

def house(size):
    right(180)
    square(size)
    triangle(size)
    right(180)

def barchart(lst, size):
    scale = size/max(lst)
    width = size/len(lst)
    for i in lst:
        rectangle(i*scale, width)
        penup()
        forward(width)
        pendown()
    penup()
    back(size)
    pendown()

clearscreen()
hideturtle()
house(150)
penup()
forward(10)
pendown()
barchart([0.5, (1/3), 2, 1.3, 0.5], 200)
penup()
back(10)
pendown()


Singular value decomposition

A is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by X^{−1}AX.
The eigenvectors in X have three big problems: They are usually not orthogonal, there
are not always enough eigenvectors, and Ax = λx requires A to be a square matrix. The
singular vectors of A solve all those problems in a perfect way.

[https://math.mit.edu/classes/18.095/2016IAP/lec2/SVD_Notes.pdf The Singular Value Decomposition (SVD)]

According to the web page above, for any rectangular matrix A, we can decomposite it as A=UΣV^T

''' Task Description'''

Firstly, input two numbers "m" and "n".

Then, input a square/rectangular matrix A^{m\times n}.

Finally, output U,Σ,V with respect to A.

''' Example '''

Sample Input

2 2
3 0
4 5

From the input above we can know that A is a 2 by 2 matrix.

Sample Output

0.31622776601683794 -0.9486832980505138
0.9486832980505138 0.31622776601683794

6.708203932499369 0
0 2.23606797749979

0.7071067811865475 -0.7071067811865475
0.7071067811865475 0.7071067811865475

The output may vary depending your choice of the data types.

'''Remark'''

1. It’s encouraged to implement the algorithm by yourself while using libraries is still acceptible.

2. The algorithm should be applicable for general case(m\times n).

Solution:
#include
#include

/* Custom function for printing a gsl_matrix in matrix form. */
void gsl_matrix_print(const gsl_matrix *M) {
    int rows = M->size1;
    int cols = M->size2;
    for (int i = 0; i < rows; i++) {
        printf("|");
        for (int j = 0; j < cols; j++) {
            printf("% 12.10f ", gsl_matrix_get(M, i, j));
        }
        printf("\b|\n");
    }
    printf("\n");
}

int main(){
    double a[] = {3, 0, 4, 5};
    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);
    gsl_matrix *V = gsl_matrix_alloc(2, 2);
    gsl_vector *S = gsl_vector_alloc(2);
    gsl_vector *work = gsl_vector_alloc(2);

    /* V is returned here in untransposed form. */
    gsl_linalg_SV_decomp(&A.matrix, V, S, work);
    gsl_matrix_transpose(V);
    double s[] = {S->data[0], 0, 0, S->data[1]};
    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);

    printf("U:\n");
    gsl_matrix_print(&A.matrix);

    printf("S:\n");
    gsl_matrix_print(&SM.matrix);

    printf("VT:\n");
    gsl_matrix_print(V);

    gsl_matrix_free(V);
    gsl_vector_free(S);
    gsl_vector_free(work);
    return 0;
}


Singular value decomposition

Solution:
from numpy import *
A = matrix([[3, 0], [4, 5]])
U, Sigma, VT = linalg.svd(A)
print(U)
print(Sigma)
print(VT)


Smith numbers

sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.

By definition, all primes are ''excluded'' as they (naturally) satisfy this condition!

Smith numbers are also known as   ''joke''   numbers.

;Example
Using the number '''166'''
Find the prime factors of '''166''' which are: '''2''' x '''83'''
Then, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''
Then, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''
Therefore, the number '''166''' is a Smith number.

;Task
Write a program to find all Smith numbers ''below'' 10000.

;See also
* from Wikipedia:   [[https://en.wikipedia.org/wiki/Smith_number Smith number]].
* from MathWorld:   [[http://mathworld.wolfram.com/SmithNumber.html Smith number]].
* from OEIS A6753:   [[https://oeis.org/A006753 OEIS sequence A6753]].
* from OEIS A104170:   [[https://oeis.org/A104170 Number of Smith numbers below 10^n]].
* from The Prime pages:   [[http://primes.utm.edu/glossary/xpage/SmithNumber.html Smith numbers]].

Solution:
#include
#include
#include

int numPrimeFactors(unsigned x) {
    unsigned p = 2;
    int pf = 0;
    if (x == 1)
        return 1;
    else {
        while (true) {
            if (!(x % p)) {
                pf++;
                x /= p;
                if (x == 1)
                    return pf;
            }
            else
                ++p;
        }
    }
}

void primeFactors(unsigned x, unsigned* arr) {
    unsigned p = 2;
    int pf = 0;
    if (x == 1)
        arr[pf] = 1;
    else {
        while (true) {
            if (!(x % p)) {
                arr[pf++] = p;
                x /= p;
                if (x == 1)
                    return;
            }
            else
                p++;
        }
    }
}

unsigned sumDigits(unsigned x) {
    unsigned sum = 0, y;
    while (x) {
        y = x % 10;
        sum += y;
        x /= 10;
    }
    return sum;
}

unsigned sumFactors(unsigned* arr, int size) {
    unsigned sum = 0;
    for (int a = 0; a < size; a++)
        sum += sumDigits(arr[a]);
    return sum;
}

void listAllSmithNumbers(unsigned x) {
    unsigned *arr;
    for (unsigned a = 4; a < x; a++) {
        int numfactors = numPrimeFactors(a);
        arr = (unsigned*)malloc(numfactors * sizeof(unsigned));
        if (numfactors < 2)
            continue;
        primeFactors(a, arr);
        if (sumDigits(a) == sumFactors(arr,numfactors))
            printf("%4u ",a);
        free(arr);
    }
}

int main(int argc, char* argv[]) {
    printf("All the Smith Numbers < 10000 are:\n");
    listAllSmithNumbers(10000);
    return 0;
}


Smith numbers

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

    // isSmith :: Int -> Bool
    const isSmith = n => {
        const pfs = primeFactors(n);
        return (1 < pfs.length || n !== pfs[0]) && (
            sumDigits(n) === pfs.reduce(
                (a, x) => a + sumDigits(x),
                0
            )
        );
    };

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

    // main :: IO ()
    const main = () => {

        // lowSmiths :: [Int]
        const lowSmiths = enumFromTo(2)(9999)
            .filter(isSmith);

        // lowSmithCount :: Int
        const lowSmithCount = lowSmiths.length;
        return [
            "Count of Smith Numbers below 10k:",
            show(lowSmithCount),
            "\nFirst 15 Smith Numbers:",
            unwords(take(15)(lowSmiths)),
            "\nLast 12 Smith Numbers below 10000:",
            unwords(drop(lowSmithCount - 12)(lowSmiths))
        ].join('\n');
    };

    // SMITH ----------------------------------------------

    // primeFactors :: Int -> [Int]
    const primeFactors = x => {
        const go = n => {
            const fs = take(1)(
                dropWhile(x => 0 != n % x)(
                    enumFromTo(2)(
                        floor(sqrt(n))
                    )
                )
            );
            return 0 === fs.length ? [n] : fs.concat(
                go(floor(n / fs[0]))
            );
        };
        return go(x);
    };

    // sumDigits :: Int -> Int
    const sumDigits = n =>
        unfoldl(
            x => 0 === x ? (
                Nothing()
            ) : Just(quotRem(x)(10))
        )(n).reduce((a, x) => a + x, 0);

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

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

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

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

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

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

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

    // floor :: Num -> Int
    const floor = Math.floor;

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

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

    // sqrt :: Num -> Num
    const sqrt = n =>
        (0 <= n) ? Math.sqrt(n) : undefined;

    // sum :: [Num] -> Num
    const sum = xs => xs.reduce((a, x) => a + x, 0);

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

    // unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
    const unfoldl = f => v => {
        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);
            }
        }
    };

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

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

    return main();
})();


Smith numbers

Solution:
from sys import stdout

def factors(n):
    rt = []
    f = 2
    if n == 1:
        rt.append(1);
    else:
        while 1:
            if 0 == ( n % f ):
                rt.append(f);
                n //= f
                if n == 1:
                    return rt
            else:
                f += 1
    return rt

def sum_digits(n):
    sum = 0
    while n > 0:
        m = n % 10
        sum += m
        n -= m
        n //= 10

    return sum

def add_all_digits(lst):
    sum = 0
    for i in range (len(lst)):
        sum += sum_digits(lst[i])

    return sum

def list_smith_numbers(cnt):
    for i in range(4, cnt):
        fac = factors(i)
        if len(fac) > 1:
            if sum_digits(i) == add_all_digits(fac):
                stdout.write("{0} ".format(i) )

# entry point
list_smith_numbers(10_000)


Soloway's recurring rainfall

Soloway's Recurring Rainfall is commonly used to assess general programming knowledge by requiring basic program structure, input/output, and program exit procedure.

'''The problem:'''

Write a program that will read in integers and output their average. Stop reading when the value 99999 is input.

For languages that aren't traditionally interactive, the program can read in values as makes sense and stopping once 99999 is encountered.  The classic rainfall problem comes from identifying success of Computer Science programs with their students, so the original problem statement is written above -- though it may not strictly apply to a given language in the modern era.

'''Implementation Details:'''
* Only Integers are to be accepted as input
* Output should be floating point
* Rainfall can be negative (https://www.geographyrealm.com/what-is-negative-rainfall/)
* For languages where the user is inputting data, the number of data inputs can be "infinite"
* A complete implementation should handle error cases reasonably (asking the user for more input, skipping the bad value when encountered, etc)

The purpose of this problem, as originally proposed in the 1980's through its continued use today, is to just show fundamentals of CS: iteration, branching, program structure, termination, management of data types, input/output (where applicable), etc with things like input validation or management of numerical limits being more "advanced".  It isn't meant to literally be a rainfall calculator so implementations should strive to implement the solution clearly and simply.

'''References:'''
* http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf
* https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppletal-2015-DoweknowhowdifficulttheRainfallProblemis.pdf
* https://en.wikipedia.org/wiki/Moving_average#Cumulative_average

Solution:
#include

int main(int argc, char **argv)
{
	// Unused variables
	(void)argc;
	(void)argv;

	float currentAverage = 0;
	unsigned int currentEntryNumber = 0;

	for (;;)
	{
		int ret, entry;

		printf("Enter rainfall int, 99999 to quit: ");
		ret = scanf("%d", &entry);

		if (ret)
		{
			if (entry == 99999)
			{
				printf("User requested quit.\n");
				break;
			}
			else
			{
				currentEntryNumber++;
				currentAverage = currentAverage + (1.0f/currentEntryNumber)*entry - (1.0f/currentEntryNumber)*currentAverage;

				printf("New Average: %f\n", currentAverage);
			}
		}
		else
		{
			printf("Invalid input\n");
			while (getchar() != '\n');	// Clear input buffer before asking again
		}
	}

	return 0;
}


Soloway's recurring rainfall

Solution:
import sys

def get_next_input():
    try:
        num = int(input("Enter rainfall int, 99999 to quit: "))
    except:
        print("Invalid input")
        return get_next_input()
    return num

current_average = 0.0
current_count = 0

while True:
    next = get_next_input()

    if next == 99999:
        sys.exit()
    else:
        current_count += 1
        current_average = current_average + (1.0/current_count)*next - (1.0/current_count)*current_average

        print("New average: ", current_average)


Solve a Hidato puzzle

The task is to write a program which solves Hidato (aka Hidoku) puzzles.

The rules are:
* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
** The grid is not necessarily rectangular.
** The grid may have holes in it.
** The grid is always connected.
** The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
** A square may only contain one number.
* In a proper Hidato puzzle, the solution is unique.

For example the following problem
Sample Hidato problem, from Wikipedia

has the following solution, with path marked on it:

Solution to sample Hidato problem

;Related tasks:
* [[A* search algorithm]]
* [[N-queens problem]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]];

Solution:
#include
#include
#include
#include

int *board, *flood, *known, top = 0, w, h;

static inline int idx(int y, int x) { return y * w + x; }

int neighbors(int c, int *p)
/*
@c cell
@p list of neighbours
@return amount of neighbours
*/
{
	int i, j, n = 0;
	int y = c / w, x = c % w;

	for (i = y - 1; i <= y + 1; i++) {
		if (i < 0 || i >= h) continue;
		for (j = x - 1; j <= x + 1; j++)
			if (!(j < 0 || j >= w
				|| (j == x && i == y)
				|| board[ p[n] = idx(i,j) ] == -1))
				n++;
	}

	return n;
}

void flood_fill(int c)
/*
fill all free cells around @c with “1” and write output to variable “flood”
@c cell
*/
{
	int i, n[8], nei;

	nei = neighbors(c, n);
	for (i = 0; i < nei; i++) { // for all neighbours
		if (board[n[i]] || flood[n[i]]) continue; // if cell is not free, choose another neighbour

		flood[n[i]] = 1;
		flood_fill(n[i]);
	}
}

/* Check all empty cells are reachable from higher known cells.
   Should really do more checks to make sure cell_x and cell_x+1
   share enough reachable empty cells; I'm lazy. Will implement
   if a good counter example is presented. */
int check_connectity(int lowerbound)
{
	int c;
	memset(flood, 0, sizeof(flood[0]) * w * h);
	for (c = lowerbound + 1; c <= top; c++)
		if (known[c]) flood_fill(known[c]); // mark all free cells around known cells

	for (c = 0; c < w * h; c++)
		if (!board[c] && !flood[c]) // if there are free cells which could not be reached from flood_fill
			return 0;

	return 1;
}

void make_board(int x, int y, const char *s)
{
	int i;

	w = x, h = y;
        top = 0;
	x = w * h;

        known = calloc(x + 1, sizeof(int));
        board = calloc(x,     sizeof(int));
        flood = calloc(x,     sizeof(int));

	while (x--) board[x] = -1;

	for (y = 0; y < h; y++)
	for (x = 0; x < w; x++) {
		i = idx(y, x);

		while (isspace(*s)) s++;

		switch (*s) {
		case '_':	board[i] = 0;
		case '.':	break;
		default:
			known[ board[i] = strtol(s, 0, 10) ] = i;
			if (board[i] > top) top = board[i];
		}

		while (*s && !isspace(*s)) s++;
	}
}

void show_board(const char *s)
{
	int i, j, c;

	printf("\n%s:\n", s);

	for (i = 0; i < h; i++, putchar('\n'))
	for (j = 0; j < w; j++) {
		c = board[ idx(i, j) ];
		printf(!c ? " __" : c == -1 ? "   " : " %2d", c);
	}
}

int fill(int c, int n)
{
	int i, nei, p[8], ko, bo;

	if ((board[c] && board[c] != n) || (known[n] && known[n] != c))
		return 0;

	if (n == top) return 1;

	ko = known[n];
	bo = board[c];
	board[c] = n;

	if (check_connectity(n)) {
		nei = neighbors(c, p);
		for (i = 0; i < nei; i++)
			if (fill(p[i], n + 1))
				return 1;
	}

	board[c] = bo;
	known[n] = ko;
	return 0;
}

int main()
{
	make_board(
#define USE_E 0
#if (USE_E == 0)
		8,8,	" __ 33 35 __ __ .. .. .."
			" __ __ 24 22 __ .. .. .."
			" __ __ __ 21 __ __ .. .."
			" __ 26 __ 13 40 11 .. .."
			" 27 __ __ __  9 __  1 .."
			" .   . __ __ 18 __ __ .."
			" .  ..  .  . __  7 __ __"
			" .  .. .. ..  .  .  5 __"
#elif (USE_E == 1)
	3, 3,	" . 4 ."
		" _ 7 _"
		" 1 _ _"
#else
	50, 3,
	" 1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74"
	" . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ ."
	" . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ ."
#endif
	);

	show_board("Before");
	fill(known[1], 1);
	show_board("After"); /* "40 lbs in two weeks!" */

	return 0;
}


Solve a Hidato puzzle

Solution:
board = []
given = []
start = None

def setup(s):
    global board, given, start
    lines = s.splitlines()
    ncols = len(lines[0].split())
    nrows = len(lines)
    board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)]

    for r, row in enumerate(lines):
        for c, cell in enumerate(row.split()):
            if cell == "__" :
                board[r + 1][c + 1] = 0
                continue
            elif cell == ".":
                continue # -1
            else:
                val = int(cell)
                board[r + 1][c + 1] = val
                given.append(val)
                if val == 1:
                    start = (r + 1, c + 1)
    given.sort()

def solve(r, c, n, next=0):
    if n > given[-1]:
        return True
    if board[r][c] and board[r][c] != n:
        return False
    if board[r][c] == 0 and given[next] == n:
        return False

    back = 0
    if board[r][c] == n:
        next += 1
        back = n

    board[r][c] = n
    for i in xrange(-1, 2):
        for j in xrange(-1, 2):
            if solve(r + i, c + j, n + 1, next):
                return True
    board[r][c] = back
    return False

def print_board():
    d = {-1: "  ", 0: "__"}
    bmax = max(max(r) for r in board)
    form = "%" + str(len(str(bmax)) + 1) + "s"
    for r in board[1:-1]:
        print "".join(form % d.get(c, str(c)) for c in r[1:-1])

hi = """\
__ 33 35 __ __  .  .  .
__ __ 24 22 __  .  .  .
__ __ __ 21 __ __  .  .
__ 26 __ 13 40 11  .  .
27 __ __ __  9 __  1  .
 .  . __ __ 18 __ __  .
 .  .  .  . __  7 __ __
 .  .  .  .  .  .  5 __"""

setup(hi)
print_board()
solve(start[0], start[1], 1)
print
print_board()