Magic squares of singly even order

A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').

A  magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.

;Task
Create a magic square of 6 x 6.

; Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of doubly even order]]

; See also
* Singly Even Magic Squares (1728.org)

Solution:
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;

class magicSqr
{
public:
    magicSqr() { sqr = 0; }
    ~magicSqr() { if( sqr ) delete [] sqr; }

    void create( int d ) {
        if( sqr ) delete [] sqr;
        if( d & 1 ) d++;
        while( d % 4 == 0 ) { d += 2; }
        sz = d;
        sqr = new int[sz * sz];
        memset( sqr, 0, sz * sz * sizeof( int ) );
        fillSqr();
    }
    void display() {
        cout << "Singly Even Magic Square: " << sz << " x " << sz << "\n";
        cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
        ostringstream cvr; cvr << sz * sz;
        int l = cvr.str().size();

        for( int y = 0; y < sz; y++ ) {
            int yy = y * sz;
            for( int x = 0; x < sz; x++ ) {
                cout << setw( l + 2 ) << sqr[yy + x];
            }
            cout << "\n";
        }
        cout << "\n\n";
    }
private:
    void siamese( int from, int to ) {
        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;

        while( count > 0 ) {
            bool done = false;
            while ( false == done ) {
                if( curCol >= oneSide ) curCol = 0;
                if( curRow < 0 ) curRow = oneSide - 1;
                done = true;
                if( sqr[curCol + sz * curRow] != 0 ) {
                    curCol -= 1; curRow += 2;
                    if( curCol < 0 ) curCol = oneSide - 1;
                    if( curRow >= oneSide ) curRow -= oneSide;

                    done = false;
                }
            }
            sqr[curCol + sz * curRow] = s;
            s++; count--; curCol++; curRow--;
        }
    }
    void fillSqr() {
        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;

        siamese( 0, n );

        for( int r = 0; r < n; r++ ) {
            int row = r * sz;
            for( int c = n; c < sz; c++ ) {
                int m = sqr[c - n + row];

                sqr[c + row] = m + add1;
                sqr[c + row + ns] = m + add3;
                sqr[c - n + row + ns] = m + add2;
            }
        }

        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 );
        for( int r = 0; r < n; r++ ) {
            int row = r * sz;
            for( int c = co; c < sz; c++ ) {
                sqr[c + row] -= add3;
                sqr[c + row + ns] += add3;
            }
        }
        for( int r = 0; r < n; r++ ) {
            int row = r * sz;
            for( int c = 0; c < lc; c++ ) {
                int cc = c;
                if( r == lc ) cc++;
                sqr[cc + row] += add2;
                sqr[cc + row + ns] -= add2;
            }
        }
    }
    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }

    void inc( int& a ) { if( ++a == sz ) a = 0; }

    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }

    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }

    bool isInside( int s ) { return ( s < sz && s > -1 ); }

    int* sqr;
    int sz;
};
int main( int argc, char* argv[] ) {
    magicSqr s; s.create( 6 );
    s.display();
    return 0;
}


Map range

Given two ranges:
:::*   [a_1,a_2]   and
:::*   [b_1,b_2];
:::*   then a value   s   in range   [a_1,a_2]
:::*   is linearly mapped to a value   t   in range   [b_1,b_2]
   where:

:::*   t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)}

;Task:
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.

Use this function to map values from the range    [0, 10]    to the range    [-1, 0].

;Extra credit:
Show additional idiomatic ways of performing the mapping, using tools available to the language.

Solution:
#include <iostream>
#include <utility>

template<typename tVal>
tVal map_value(std::pair<tVal,tVal> a, std::pair<tVal, tVal> b, tVal inVal)
{
  tVal inValNorm = inVal - a.first;
  tVal aUpperNorm = a.second - a.first;
  tVal normPosition = inValNorm / aUpperNorm;

  tVal bUpperNorm = b.second - b.first;
  tVal bValNorm = normPosition * bUpperNorm;
  tVal outVal = b.first + bValNorm;

  return outVal;
}

int main()
{
  std::pair<float,float> a(0,10), b(-1,0);

  for(float value = 0.0; 10.0 >= value; ++value)
    std::cout << "map_value(" << value << ") = " << map_value(a, b, value) << std::endl;

  return 0;
}


Maximum triangle path sum

Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:

                          55
                        94 48
                       95 30 96
                     77 71 26 67

One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.

Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.

;Task:
Find the maximum total in the triangle below:

                          55
                        94 48
                       95 30 96
                     77 71 26 67
                    97 13 76 38 45
                  07 36 79 16 37 68
                 48 07 09 18 70 26 06
               18 72 79 46 59 79 29 90
              20 76 87 11 32 07 07 49 18
            27 83 58 35 71 11 25 57 29 85
           14 64 36 96 27 11 58 56 92 18 55
         02 90 03 60 48 49 41 46 33 36 47 23
        92 50 48 02 36 59 42 79 72 20 82 77 42
      56 78 38 80 39 75 02 71 66 66 01 03 55 72
     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93

Such numbers can be included in the solution code, or read from a "triangle.txt" file.

This task is derived from the Euler Problem #18.

Solution:
/* Algorithm complexity: n*log(n) */
#include <iostream>

int main( int argc, char* argv[] )
{
    int triangle[] =
    {
	55,
	94, 48,
	95, 30, 96,
	77, 71, 26, 67,
	97, 13, 76, 38, 45,
	7, 36, 79, 16, 37, 68,
	48, 7, 9, 18, 70, 26, 6,
	18, 72, 79, 46, 59, 79, 29, 90,
	20, 76, 87, 11, 32, 7, 7, 49, 18,
	27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
	14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
	2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
	92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
	56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
	44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
	85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
	6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
	27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
    };

    const int size = sizeof( triangle ) / sizeof( int );
    const int tn = static_cast<int>(sqrt(2.0 * size));
    assert(tn * (tn + 1) == 2 * size);    // size should be a triangular number

    // walk backward by rows, replacing each element with max attainable therefrom
    for (int n = tn - 1; n > 0; --n)   // n is size of row, note we do not process last row
        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) // from the start to the end of row
            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);

    std::cout << "Maximum total: " << triangle[0] << "\n\n";
}


Mian-Chowla sequence

The Mian-Chowla sequence is an integer sequence defined recursively.

Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.

The sequence starts with:

::a1 = 1

then for n > 1, an is the smallest positive integer such that every pairwise sum

::ai + aj

is distinct, for all i and j less than or equal to n.

;The Task:

:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.
:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.

Demonstrating working through the first few terms longhand:

::a1 = 1

::1 + 1 = 2

Speculatively try a2 = 2

::1 + 1 = 2
::1 + 2 = 3
::2 + 2 = 4

There are no repeated sums so '''2''' is the next number in the sequence.

Speculatively try a3 = 3

::1 + 1 = 2
::1 + 2 = 3
::1 + 3 = 4
::2 + 2 = 4
::2 + 3 = 5
::3 + 3 = 6

Sum of '''4''' is repeated so '''3''' is rejected.

Speculatively try a3 = 4

::1 + 1 = 2
::1 + 2 = 3
::1 + 4 = 5
::2 + 2 = 4
::2 + 4 = 6
::4 + 4 = 8

There are no repeated sums so '''4''' is the next number in the sequence.

And so on...

;See also:

:* OEIS:A005282 Mian-Chowla sequence

Solution:
using namespace std;

#include <iostream>
#include <ctime>

#define n 100
#define nn ((n * (n + 1)) >> 1)

bool Contains(int lst[], int item, int size) {
	for (int i = 0; i < size; i++) if (item == lst[i]) return true;
	return false;
}

int * MianChowla()
{
	static int mc[n]; mc[0] = 1;
	int sums[nn];	sums[0] = 2;
	int sum, le, ss = 1;
	for (int i = 1; i < n; i++) {
		le = ss;
		for (int j = mc[i - 1] + 1; ; j++) {
			mc[i] = j;
			for (int k = 0; k <= i; k++) {
				sum = mc[k] + j;
				if (Contains(sums, sum, ss)) {
					ss = le; goto nxtJ;
				}
				sums[ss++] = sum;
			}
			break;
		nxtJ:;
		}
	}
	return mc;
}

int main() {
	clock_t st = clock(); int * mc; mc = MianChowla();
	double et = ((double)(clock() - st)) / CLOCKS_PER_SEC;
	cout << "The first 30 terms of the Mian-Chowla sequence are:\n";
	for (int i = 0; i < 30; i++) { cout << mc[i] << ' '; }
	cout << "\n\nTerms 91 to 100 of the Mian-Chowla sequence are:\n";
	for (int i = 90; i < 100; i++) { cout << mc[i] << ' '; }
	cout << "\n\nComputation time was " << et << " seconds.";
}


Middle three digits

Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.

Note: The order of the middle digits should be preserved.

Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:

123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0

Show your output on this page.

Solution:
#include <iostream>

std::string middleThreeDigits(int n)
{
    auto number = std::to_string(std::abs(n));
    auto length = number.size();

    if (length < 3) {
        return "less than three digits";
    } else if (length % 2 == 0) {
        return "even number of digits";
    } else {
        return number.substr(length / 2 - 1, 3);
    }
}

int main()
{
    auto values {123, 12345, 1234567, 987654321, 10001,
                 -10001, -123, -100, 100, -12345,
                 1, 2, -1, -10, 2002, -2002, 0};

    for (auto&& v : values) {
        std::cout << "middleThreeDigits(" << v << "): " <<
                     middleThreeDigits(v) << "\n";
    }
}


Minimum multiple of m where digital sum equals m

Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''.

;Task

* Find the first 40 elements of the sequence.

;Stretch

* Find the next 30 elements of the sequence.

;See also

;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n

Solution:
#include <iomanip>
#include <iostream>

int digit_sum(int n) {
    int sum = 0;
    for (; n > 0; n /= 10)
        sum += n % 10;
    return sum;
}

int main() {
    for (int n = 1; n <= 70; ++n) {
        for (int m = 1;; ++m) {
            if (digit_sum(m * n) == n) {
                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' ');
                break;
            }
        }
    }
}


Minimum positive multiple in base 10 using only 0 and 1

Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.

This is simple to do, but can be challenging to do efficiently.

To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "'''B10'''".

;Task:

Write a routine to find the B10 of a given integer.

E.G.

       '''n'''                  '''B10'''      '''n'''  x '''multiplier'''
       1                    1    ( 1  x 1         )
       2                   10    ( 2  x 5         )
       7                 1001    ( 7  x 143       )
       9            111111111    ( 9  x 12345679  )
      10                   10    ( 10 x 1         )

and so on.

Use the routine to find and display here, on this page, the '''B10''' value for:

    1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999

Optionally find '''B10''' for:

    1998, 2079, 2251, 2277

Stretch goal; find '''B10''' for:

    2439, 2997, 4878

There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.

;See also:

:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
:* How to find Minimum Positive Multiple in base 10 using only 0 and 1

Solution:
#include <iostream>
#include <vector>

__int128 imax(__int128 a, __int128 b) {
    if (a > b) {
        return a;
    }
    return b;
}

__int128 ipow(__int128 b, __int128 n) {
    if (n == 0) {
        return 1;
    }
    if (n == 1) {
        return b;
    }

    __int128 res = b;
    while (n > 1) {
        res *= b;
        n--;
    }
    return res;
}

__int128 imod(__int128 m, __int128 n) {
    __int128 result = m % n;
    if (result < 0) {
        result += n;
    }
    return result;
}

bool valid(__int128 n) {
    if (n < 0) {
        return false;
    }
    while (n > 0) {
        int r = n % 10;
        if (r > 1) {
            return false;
        }
        n /= 10;
    }
    return true;
}

__int128 mpm(const __int128 n) {
    if (n == 1) {
        return 1;
    }

    std::vector<__int128> L(n * n, 0);
    L[0] = 1;
    L[1] = 1;

    __int128 m, k, r, j;
    m = 0;
    while (true) {
        m++;
        if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) {
            break;
        }
        L[m * n + 0] = 1;
        for (k = 1; k < n; k++) {
            L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]);
        }
    }

    r = ipow(10, m);
    k = imod(-r, n);

    for (j = m - 1; j >= 1; j--) {
        if (L[(j - 1) * n + k] == 0) {
            r = r + ipow(10, j);
            k = imod(k - ipow(10, j), n);
        }
    }

    if (k == 1) {
        r++;
    }
    return r / n;
}

std::ostream& operator<<(std::ostream& os, __int128 n) {
    char buffer[64]; // more then is needed, but is nice and round;
    int pos = (sizeof(buffer) / sizeof(char)) - 1;
    bool negative = false;

    if (n < 0) {
        negative = true;
        n = -n;
    }

    buffer[pos] = 0;
    while (n > 0) {
        int rem = n % 10;
        buffer[--pos] = rem + '0';
        n /= 10;
    }
    if (negative) {
        buffer[--pos] = '-';
    }
    return os << &buffer[pos];
}

void test(__int128 n) {
    __int128 mult = mpm(n);
    if (mult > 0) {
        std::cout << n << " * " << mult << " = " << (n * mult) << '\n';
    } else {
        std::cout << n << "(no solution)\n";
    }
}

int main() {
    int i;

    // 1-10 (inclusive)
    for (i = 1; i <= 10; i++) {
        test(i);
    }
    // 95-105 (inclusive)
    for (i = 95; i <= 105; i++) {
        test(i);
    }
    test(297);
    test(576);
    test(594); // needs a larger number type (64 bits signed)
    test(891);
    test(909);
    test(999); // needs a larger number type (87 bits signed)

    // optional
    test(1998);
    test(2079);
    test(2251);
    test(2277);

    // stretch
    test(2439);
    test(2997);
    test(4878);

    return 0;
}


Modular arithmetic

equivalence relation called ''congruence''.

For any positive integer p called the ''congruence modulus'',
two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:
:a = b + k\,p

The corresponding set of multiplicative inverse for this task.

Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.

The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.

You will use the following function for demonstration:
:f(x) = x^{100} + x + 1
You will use 13 as the congruence modulus and you will compute f(10).

It is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.

Solution:
#include <iostream>
#include <ostream>

template<typename T>
T f(const T& x) {
    return (T) pow(x, 100) + x + 1;
}

class ModularInteger {
private:
    int value;
    int modulus;

    void validateOp(const ModularInteger& rhs) const {
        if (modulus != rhs.modulus) {
            throw std::runtime_error("Left-hand modulus does not match right-hand modulus.");
        }
    }

public:
    ModularInteger(int v, int m) {
        modulus = m;
        value = v % m;
    }

    int getValue() const {
        return value;
    }

    int getModulus() const {
        return modulus;
    }

    ModularInteger operator+(const ModularInteger& rhs) const {
        validateOp(rhs);
        return ModularInteger(value + rhs.value, modulus);
    }

    ModularInteger operator+(int rhs) const {
        return ModularInteger(value + rhs, modulus);
    }

    ModularInteger operator*(const ModularInteger& rhs) const {
        validateOp(rhs);
        return ModularInteger(value * rhs.value, modulus);
    }

    friend std::ostream& operator<<(std::ostream&, const ModularInteger&);
};

std::ostream& operator<<(std::ostream& os, const ModularInteger& self) {
    return os << "ModularInteger(" << self.value << ", " << self.modulus << ")";
}

ModularInteger pow(const ModularInteger& lhs, int pow) {
    if (pow < 0) {
        throw std::runtime_error("Power must not be negative.");
    }

    ModularInteger base(1, lhs.getModulus());
    while (pow-- > 0) {
        base = base * lhs;
    }
    return base;
}

int main() {
    using namespace std;

    ModularInteger input(10, 13);
    auto output = f(input);
    cout << "f(" << input << ") = " << output << endl;

    return 0;
}


Modular inverse

From Wikipedia:

In modulo    ''m''    is an integer    ''x''    such that

::a\,x \equiv 1 \pmod{m}.

Or in other words, such that:

::\exists k \in\Z,\qquad a\, x = 1 + k\,m

It can be shown that such an inverse exists   if and only if    ''a''    and    ''m''    are coprime,   but we will ignore this for this task.

;Task:
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language,   compute the modular inverse of   42 modulo 2017.

Solution:
#include <iostream>

int mul_inv(int a, int b)
{
	int b0 = b, t, q;
	int x0 = 0, x1 = 1;
	if (b == 1) return 1;
	while (a > 1) {
		q = a / b;
		t = b, b = a % b, a = t;
		t = x0, x0 = x1 - q * x0, x1 = t;
	}
	if (x1 < 0) x1 += b0;
	return x1;
}

int main(void) {
	std::cout << mul_inv(42, 2017) << std::endl;
	return 0;
}


Monads/List monad

A Monad is a combination of a data-type with two helper functions written for that type.

The data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.

The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.

A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.

The natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.

Demonstrate in your programming language the following:

#Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String
#Compose the two functions with bind

Solution:
#include <iostream>
#include <vector>

using namespace std;

// std::vector can be a list monad.  Use the >> operator as the bind function
template <typename T>
auto operator>>(const vector<T>& monad, auto f)
{
    // Declare a vector of the same type that the function f returns
    vector<remove_reference_t<decltype(f(monad.front()).front())>> result;
    for(auto& item : monad)
    {
        // Apply the function f to each item in the monad. f will return a
        // new list monad containing 0 or more items.
        const auto r = f(item);
        // Concatenate the results of f with previous results
        result.insert(result.end(), begin(r), end(r));
    }

    return result;
}

// The Pure function returns a vector containing one item, t
auto Pure(auto t)
{
    return vector{t};
}

// A function to double items in the list monad
auto Double(int i)
{
    return Pure(2 * i);
}

// A function to increment items
auto Increment(int i)
{
    return Pure(i + 1);
}

// A function to convert items to a string
auto NiceNumber(int i)
{
    return Pure(to_string(i) + " is a nice number\n");
}

// A function to map an item to a sequence ending at max value
// for example: 497 -> {497, 498, 499, 500}
auto UpperSequence = [](auto startingVal)
{
    const int MaxValue = 500;
    vector<decltype(startingVal)> sequence;
    while(startingVal <= MaxValue)
        sequence.push_back(startingVal++);
    return sequence;
};

// Print contents of a vector
void PrintVector(const auto& vec)
{
    cout << " ";
    for(auto value : vec)
    {
        cout << value << " ";
    }
    cout << "\n";
}

// Print the Pythagorean triples
void PrintTriples(const auto& vec)
{
    cout << "Pythagorean triples:\n";
    for(auto it = vec.begin(); it != vec.end();)
    {
        auto x = *it++;
        auto y = *it++;
        auto z = *it++;

        cout << x << ", " << y << ", " << z << "\n";
    }
    cout << "\n";
}

int main()
{
    // Apply Increment, Double, and NiceNumber to {2, 3, 4} using the monadic bind
    auto listMonad =
        vector<int> {2, 3, 4} >>
        Increment >>
        Double >>
        NiceNumber;

    PrintVector(listMonad);

    // Find Pythagorean triples using the list monad.  The 'x' monad list goes
    // from 1 to the max; the 'y' goes from the current 'x' to the max; and 'z'
    // goes from the current 'y' to the max.  The last bind returns the triplet
    // if it is Pythagorean, otherwise it returns an empty list monad.
    auto pythagoreanTriples = UpperSequence(1) >>
        [](int x){return UpperSequence(x) >>
        [x](int y){return UpperSequence(y) >>
        [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};

    PrintTriples(pythagoreanTriples);
}


Monads/Maybe monad

Demonstrate in your programming language the following:

#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
#Compose the two functions with bind

A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.

A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.

Solution:
#include <iostream>
#include <cmath>
#include <optional>
#include <vector>

using namespace std;

// std::optional can be a maybe monad.  Use the >> operator as the bind function
template <typename T>
auto operator>>(const optional<T>& monad, auto f)
{
    if(!monad.has_value())
    {
        // Return an empty maybe monad of the same type as if there
        // was a value
        return optional<remove_reference_t<decltype(*f(*monad))>>();
    }

    return f(*monad);
}

// The Pure function returns a maybe monad containing the value t
auto Pure(auto t)
{
    return optional{t};
}

// A safe function to invert a value
auto SafeInverse(double v)
{
    if (v == 0)
    {
        return optional<decltype(v)>();
    }
    else
    {
        return optional(1/v);
    }
}

// A safe function to calculate the arc cosine
auto SafeAcos(double v)
{
    if(v < -1 || v > 1)
    {
        // The input is out of range, return an empty monad
        return optional<decltype(acos(v))>();
    }
    else
    {
        return optional(acos(v));
    }
}

// Print the monad
template<typename T>
ostream& operator<<(ostream& s, optional<T> v)
{
    s << (v ? to_string(*v) : "nothing");
    return s;
}

int main()
{
    // Use bind to compose SafeInverse and SafeAcos
    vector<double> tests {-2.5, -1, -0.5, 0, 0.5, 1, 2.5};

    cout << "x -> acos(1/x) , 1/(acos(x)\n";
    for(auto v : tests)
    {
        auto maybeMonad = Pure(v);
        auto inverseAcos = maybeMonad >> SafeInverse >> SafeAcos;
        auto acosInverse = maybeMonad >> SafeAcos >> SafeInverse;
        cout << v << " -> " << inverseAcos << ", " << acosInverse << "\n";
    }
}


Monads/Writer monad

The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.

Demonstrate in your programming language the following:

# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
# Write three simple functions: root, addOne, and half
# Derive Writer monad versions of each of these functions
# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)

Solution:
#include <cmath>
#include <iostream>
#include <string>

using namespace std;

// Use a struct as the monad
struct LoggingMonad
{
    double Value;
    string Log;
};

// Use the >> operator as the bind function
auto operator>>(const LoggingMonad& monad, auto f)
{
    auto result = f(monad.Value);
    return LoggingMonad{result.Value, monad.Log + "\n" + result.Log};
}

// Define the three simple functions
auto Root = [](double x){ return sqrt(x); };
auto AddOne = [](double x){ return x + 1; };
auto Half = [](double x){ return x / 2.0; };

// Define a function to create writer monads from the simple functions
auto MakeWriter = [](auto f, string message)
{
    return [=](double x){return LoggingMonad(f(x), message);};
};

// Derive writer versions of the simple functions
auto writerRoot = MakeWriter(Root, "Taking square root");
auto writerAddOne = MakeWriter(AddOne, "Adding 1");
auto writerHalf = MakeWriter(Half, "Dividing by 2");

int main()
{
    // Compose the writers to compute the golden ratio
    auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf;
    cout << result.Log << "\nResult: " << result.Value;
}


Move-to-front algorithm

Given a symbol table of a ''zero-indexed'' array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).

The transform in many cases acts to give frequently repeated input symbols
lower indices which is  useful in some compression algorithms.

;Encoding algorithm:

    for each symbol of the input sequence:
        output the index of the symbol in the symbol table
        move that symbol to the front of the symbol table

;Decoding algorithm:

    # Using the same starting symbol table
    for each index of the input sequence:
        output the symbol at that index of the symbol table
        move that symbol to the front of the symbol table

;Example:
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   '''a'''-to-'''z'''

:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
| '''b'''roood
| 1
| 'abcdefghijklmnopqrstuvwxyz'
|-
| b'''r'''oood
| 1 17
| 'bacdefghijklmnopqrstuvwxyz'
|-
| br'''o'''ood
| 1 17 15
| 'rbacdefghijklmnopqstuvwxyz'
|-
| bro'''o'''od
| 1 17 15 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| broo'''o'''d
| 1 17 15 0 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| brooo'''d'''
| 1 17 15 0 0 5
| 'orbacdefghijklmnpqstuvwxyz'
|}

Decoding the indices back to the original symbol order:
:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
|  '''1''' 17 15 0 0 5
| b
| 'abcdefghijklmnopqrstuvwxyz'
|-
| 1 '''17''' 15 0 0 5
| br
| 'bacdefghijklmnopqrstuvwxyz'
|-
| 1 17 '''15''' 0 0 5
| bro
| 'rbacdefghijklmnopqstuvwxyz'
|-
| 1 17 15 '''0''' 0 5
| broo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 '''0''' 5
| brooo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 0 '''5'''
| broood
| 'orbacdefghijklmnpqstuvwxyz'
|}

;Task:
:*   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   '''a'''-to-'''z'''   as above.
:*   Show the strings and their encoding here.
:*   Add a check to ensure that the decoded string is the same as the original.

The strings are:

    broood
 bananaaa
 hiphophiphop
(Note the misspellings in the above strings.)

Solution:
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

using namespace std;

class MTF
{
public:
    string encode( string str )
    {
	fillSymbolTable();
	vector<int> output;
	for( string::iterator it = str.begin(); it != str.end(); it++ )
	{
	    for( int i = 0; i < 26; i++ )
	    {
		if( *it == symbolTable[i] )
		{
		    output.push_back( i );
		    moveToFront( i );
		    break;
		}
	    }
	}
	string r;
	for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
	{
	    ostringstream ss;
	    ss << *it;
	    r += ss.str() + " ";
	}
	return r;
    }

    string decode( string str )
    {
	fillSymbolTable();
	istringstream iss( str ); vector<int> output;
	copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );
	string r;
	for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
	{
	    r.append( 1, symbolTable[*it] );
	    moveToFront( *it );
	}
	return r;
    }

private:
    void moveToFront( int i )
    {
	char t = symbolTable[i];
	for( int z = i - 1; z >= 0; z-- )
	    symbolTable[z + 1] = symbolTable[z];

        symbolTable[0] = t;
    }

    void fillSymbolTable()
    {
        for( int x = 0; x < 26; x++ )
	    symbolTable[x] = x + 'a';
    }

    char symbolTable[26];
};

int main()
{
    MTF mtf;
    string a, str[] = { "broood", "bananaaa", "hiphophiphop" };
    for( int x = 0; x < 3; x++ )
    {
        a = str[x];
        cout << a << " -> encoded = ";
        a = mtf.encode( a );
        cout << a << "; decoded = " << mtf.decode( a ) << endl;
    }
    return 0;
}


Multi-dimensional array

For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.

It is enough to:
# State the number and extent of each index to the array.
# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.
# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.

;Task:
* State if the language supports multi-dimensional arrays in its syntax and usual implementation.
* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.
:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).
* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.

Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).

Solution:
#include <iostream>
#include <vector>

// convienince for printing the contents of a collection
template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& c) {
    auto it = c.cbegin();
    auto end = c.cend();

    out << '[';
    if (it != end) {
        out << *it;
        it = std::next(it);
    }
    while (it != end) {
        out << ", " << *it;
        it = std::next(it);
    }
    return out << ']';
}

void fourDim() {
    using namespace std;

    // create a 4d jagged array, with bounds checking etc...
    vector<vector<vector<vector<int>>>> arr;
    int cnt = 0;

    arr.push_back(vector<vector<vector<int>>>{});
    arr[0].push_back(vector<vector<int>>{});
    arr[0][0].push_back(vector<int>{});
    arr[0][0][0].push_back(cnt++);
    arr[0][0][0].push_back(cnt++);
    arr[0][0][0].push_back(cnt++);
    arr[0][0][0].push_back(cnt++);
    arr[0].push_back(vector<vector<int>>{});
    arr[0][1].push_back(vector<int>{});
    arr[0][1][0].push_back(cnt++);
    arr[0][1][0].push_back(cnt++);
    arr[0][1][0].push_back(cnt++);
    arr[0][1][0].push_back(cnt++);
    arr[0][1].push_back(vector<int>{});
    arr[0][1][1].push_back(cnt++);
    arr[0][1][1].push_back(cnt++);
    arr[0][1][1].push_back(cnt++);
    arr[0][1][1].push_back(cnt++);

    arr.push_back(vector<vector<vector<int>>>{});
    arr[1].push_back(vector<vector<int>>{});
    arr[1][0].push_back(vector<int>{});
    arr[1][0][0].push_back(cnt++);
    arr[1][0][0].push_back(cnt++);
    arr[1][0][0].push_back(cnt++);
    arr[1][0][0].push_back(cnt++);

    cout << arr << '\n';
}

int main() {
    /* C++ does not have native support for multi-dimensional arrays,
     * but classes could be written to make things easier to work with.
     * There are standard library classes which can be used for single dimension arrays.
     * Also raw access is supported through pointers as in C.
     */

    fourDim();

    return 0;
}


Multifactorial

The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).

Multifactorials generalize factorials as follows:
: n! = n(n-1)(n-2)...(2)(1)
: n!! = n(n-2)(n-4)...
: n!! ! = n(n-3)(n-6)...
: n!! !! = n(n-4)(n-8)...
: n!! !! ! = n(n-5)(n-10)...

In all cases, the terms in the products are positive integers.

If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
# Write a function that given n and the degree, calculates the multifactorial.
# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.

'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.

Solution:
#include <algorithm>
#include <iostream>
#include <iterator>
/*Generate multifactorials to 9

  Nigel_Galloway
  November 14th., 2012.
*/
int main(void) {
   for (int g = 1; g < 10; g++) {
     int v[11], n=0;
     generate_n(std::ostream_iterator<int>(std::cout, " "), 10, [&]{n++; return v[n]=(g<n)? v[n-g]*n : n;});
     std::cout << std::endl;
   }
   return 0;
}


Multiple distinct objects

Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.

By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.

By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.

This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.

This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).

See also: [[Closures/Value capture]]

Solution:
#include <vector>
#include <tr1/memory>
using namespace std;
using namespace std::tr1;

typedef shared_ptr<T> TPtr_t;
// the following is NOT correct:
std::vector<TPtr_t > bvec_WRONG(n, p); // create n copies of p, which all point to the same opject p points to.

// nor is this:
std::vector<TPtr_t> bvec_ALSO_WRONG(n, TPtr_t(new T(*p)) ); // create n pointers to a single copy of *p

// the correct solution
std::vector<TPtr_t > bvec(n);
for (int i = 0; i < n; ++i)
  bvec[i] = TPtr_t(new T(*p); //or any other call to T's constructor

// another correct solution
// this solution avoids uninitialized pointers at any point
std::vector<TPtr_t> bvec2;
for (int i = 0; i < n; ++i)
  bvec2.push_back(TPtr_t(new T(*p));


Multisplit

It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.

This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.

The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.

The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.

Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=".

For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.

'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.

Solution:
#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>

int main( ) {
   std::string str( "a!===b=!=c" ) , output ;
   typedef boost::tokenizer<boost::char_separator<char> > tokenizer ;
   boost::char_separator<char> separator ( "==" , "!=" ) , sep ( "!" )  ;
   tokenizer mytok( str , separator ) ;
   tokenizer::iterator tok_iter = mytok.begin( ) ;
   for ( ; tok_iter != mytok.end( ) ; ++tok_iter )
      output.append( *tok_iter ) ;
   tokenizer nexttok ( output , sep ) ;
   for ( tok_iter = nexttok.begin( ) ; tok_iter != nexttok.end( ) ;
	 ++tok_iter )
      std::cout << *tok_iter << " " ;
   std::cout << '\n' ;
   return 0 ;
}


Munchausen numbers

A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.

('''Munchausen''' is also spelled: '''Munchhausen'''.)

For instance:    3435 = 33 + 44 + 33 + 55

;Task
Find all Munchausen numbers between   '''1'''   and   '''5000'''.

;Also see:
:* The OEIS entry:  A046253
:* The Wikipedia entry:  Perfect digit-to-digit invariant, redirected from ''Munchausen Number''

Solution:
#include <math.h>
#include <iostream>

unsigned pwr[10];

unsigned munch( unsigned i ) {
    unsigned sum = 0;
    while( i ) {
        sum += pwr[(i % 10)];
        i /= 10;
    }
    return sum;
}

int main( int argc, char* argv[] ) {
    for( int i = 0; i < 10; i++ )
        pwr[i] = (unsigned)pow( (float)i, (float)i );
    std::cout << "Munchausen Numbers\n==================\n";
    for( unsigned i = 1; i < 5000; i++ )
        if( i == munch( i ) ) std::cout << i << "\n";
    return 0;
}


Musical scale

Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.

These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfege.

For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.

For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file),  or the task can be omitted.

Solution:
#include <iostream>
#include <windows.h>
#include <mmsystem.h>

#pragma comment ( lib, "winmm.lib" )

typedef unsigned char byte;

typedef union
{
    unsigned long word;
    unsigned char data[4];
}
midi_msg;

class midi
{
public:
    midi()
    {
	if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR )
	{
	    std::cout << "Error opening MIDI Output..." << std::endl;
	    device = 0;
	}
    }
    ~midi()
    {
	midiOutReset( device );
	midiOutClose( device );
    }
    bool isOpen() { return device != 0; }
    void setInstrument( byte i )
    {
	message.data[0] = 0xc0; message.data[1] = i;
	message.data[2] = 0; message.data[3] = 0;
	midiOutShortMsg( device, message.word );
    }
    void playNote( byte n, unsigned i )
    {
	playNote( n ); Sleep( i ); stopNote( n );
    }

private:
    void playNote( byte n )
    {
	message.data[0] = 0x90; message.data[1] = n;
	message.data[2] = 127; message.data[3] = 0;
	midiOutShortMsg( device, message.word );
    }
    void stopNote( byte n )
    {
	message.data[0] = 0x90; message.data[1] = n;
	message.data[2] = 0; message.data[3] = 0;
	midiOutShortMsg( device, message.word );
    }
    HMIDIOUT device;
    midi_msg message;
};

int main( int argc, char* argv[] )
{
    midi m;
    if( m.isOpen() )
    {
	byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };
	m.setInstrument( 42 );
	for( int x = 0; x < 8; x++ )
	    m.playNote( notes[x], rand() % 100 + 158 );
	Sleep( 1000 );
    }
    return 0;
}


N-queens problem

right

Solve the eight queens puzzle.

You can extend the problem to solve the puzzle with a board of size   '''N'''x'''N'''.

For the number of solutions for small values of   '''N''',   see   OEIS: A000170.

;Related tasks:
* [[A* search algorithm]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[Peaceful chess queen armies]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]

Solution:
// Much shorter than the version below;
// uses C++11 threads to parallelize the computation; also uses backtracking
// Outputs all solutions for any table size
#include <vector>
#include <iostream>
#include <iomanip>
#include <thread>
#include <future>

// Print table. 'pos' is a vector of positions – the index in pos is the row,
// and the number at that index is the column where the queen is placed.
static void print(const std::vector<int> &pos)
{
	// print table header
	for (int i = 0; i < pos.size(); i++) {
		std::cout << std::setw(3) << char('a' + i);
	}

	std::cout << '\n';

	for (int row = 0; row < pos.size(); row++) {
		int col = pos[row];
		std::cout << row + 1 << std::setw(3 * col + 3) << " # ";
		std::cout << '\n';
	}

	std::cout << "\n\n";
}

static bool threatens(int row_a, int col_a, int row_b, int col_b)
{
	return row_a == row_b // same row
		or col_a == col_b // same column
		or std::abs(row_a - row_b) == std::abs(col_a - col_b); // diagonal
}

// the i-th queen is in the i-th row
// we only check rows up to end_idx
// so that the same function can be used for backtracking and checking the final solution
static bool good(const std::vector<int> &pos, int end_idx)
{
	for (int row_a = 0; row_a < end_idx; row_a++) {
		for (int row_b = row_a + 1; row_b < end_idx; row_b++) {
			int col_a = pos[row_a];
			int col_b = pos[row_b];
			if (threatens(row_a, col_a, row_b, col_b)) {
				return false;
			}
		}
	}

	return true;
}

static std::mutex print_count_mutex; // mutex protecting 'n_sols'
static int n_sols = 0; // number of solutions

// recursive DFS backtracking solver
static void n_queens(std::vector<int> &pos, int index)
{
	// if we have placed a queen in each row (i. e. we are at a leaf of the search tree), check solution and return
	if (index >= pos.size()) {
		if (good(pos, index)) {
			std::lock_guard<std::mutex> lock(print_count_mutex);
			print(pos);
			n_sols++;
		}

		return;
	}

	// backtracking step
	if (not good(pos, index)) {
		return;
	}

	// optimization: the first level of the search tree is parallelized
	if (index == 0) {
		std::vector<std::future<void>> fts;
		for (int col = 0; col < pos.size(); col++) {
			pos[index] = col;
			auto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); });
			fts.push_back(std::move(ft));
		}

		for (const auto &ft : fts) {
			ft.wait();
		}
	} else { // deeper levels are not
		for (int col = 0; col < pos.size(); col++) {
			pos[index] = col;
			n_queens(pos, index + 1);
		}
	}
}

int main()
{
	std::vector<int> start(12); // 12: table size
	n_queens(start, 0);
	std::cout << n_sols << " solutions found.\n";
	return 0;
}


Narcissistic decimal number

A   Narcissistic decimal number   is a non-negative integer,   n,   that is equal to the sum of the   m-th   powers of each of the digits in the decimal representation of   n,   where   m   is the number of digits in the decimal representation of   n.

Narcissistic (decimal) numbers are sometimes called   '''Armstrong'''   numbers, named after Michael F. Armstrong.
They are also known as   '''Plus Perfect'''   numbers.

;An example:
::::*   if   n   is   '''153'''
::::*   then   m,   (the number of decimal digits)   is   '''3'''
::::*   we have    13 + 53 + 33   =   1 + 125 + 27   =   '''153'''
::::*   and so   '''153'''   is a narcissistic decimal number

;Task:
Generate and show here the first   '''25'''   narcissistic decimal numbers.

Note:   0^1 = 0,   the first in the series.

;See also:
*   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.
*   MathWorld entry:   Narcissistic Number.
*   Wikipedia entry:     Narcissistic number.

Solution:
#include <iostream>
#include <vector>
using namespace std;
typedef unsigned int uint;

class NarcissisticDecs
{
public:
    void makeList( int mx )
    {
	uint st = 0, tl; int pwr = 0, len;
        while( narc.size() < mx )
	{
	    len = getDigs( st );
	    if( pwr != len )
	    {
		pwr = len;
		fillPower( pwr );
	    }
            tl = 0;
	    for( int i = 1; i < 10; i++ )
		tl += static_cast<uint>( powr[i] * digs[i] );

	    if( tl == st ) narc.push_back( st );
	    st++;
	}
    }

    void display()
    {
	for( vector<uint>::iterator i = narc.begin(); i != narc.end(); i++ )
	    cout << *i << " ";
	cout << "\n\n";
    }

private:
    int getDigs( uint st )
    {
	memset( digs, 0, 10 * sizeof( int ) );
	int r = 0;
	while( st )
	{
	    digs[st % 10]++;
	    st /= 10;
	    r++;
	}
        return r;
    }

    void fillPower( int z )
    {
	for( int i = 1; i < 10; i++ )
	    powr[i] = pow( static_cast<float>( i ), z );
    }

    vector<uint> narc;
    uint powr[10];
    int digs[10];
};

int main( int argc, char* argv[] )
{
    NarcissisticDecs n;
    n.makeList( 25 );
    n.display();
    return system( "pause" );
}


Nautical bell

Task

Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.

The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.

It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type.

;Related task:
* [[Sleep]]

Solution:
#include <iostream>
#include <string>
#include <windows.h>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
class bells
{
public:
    void start()
    {
	watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] =  "First";
	count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight";
	_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );
    }
private:
    static DWORD WINAPI bell( LPVOID p )
    {
	DWORD wait = _inst->waitTime();
	while( true )
	{
	    Sleep( wait );
	    _inst->playBell();
	    wait = _inst->waitTime();
	}
	return 0;
    }

    DWORD waitTime()
    {
	GetLocalTime( &st );
	int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;
	return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );
    }

    void playBell()
    {
	GetLocalTime( &st );
	int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;
	int w = ( 60 * st.wHour + st.wMinute );
	if( w < 1 ) w = 5; else w = ( w - 1 ) / 240;
	char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );

	cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell";
	if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;

	for( int x = 0, c = 1; x < b; x++, c++ )
	{
	    cout << "\7"; Sleep( 500 );
	    if( !( c % 2 ) ) Sleep( 300 );
	}
    }

    SYSTEMTIME st;
    string watch[7], count[8];
    static bells* _inst;
};
//--------------------------------------------------------------------------------------------------
bells* bells::_inst = 0;
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    bells b; b.start();
    while( 1 ); // <- runs forever!
    return 0;
}
//--------------------------------------------------------------------------------------------------


Negative base numbers

Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia

;Task:

*Encode the decimal number 10 as negabinary (expect 11110)
*Encode the decimal number 146 as negaternary (expect 21102)
*Encode the decimal number 15 as negadecimal (expect 195)
*In each of the above cases, convert the encoded number back to decimal.

;extra credit:

* supply an integer, that when encoded to base   -62   (or something "higher"),   expresses the name of the language being used   (with correct capitalization).   If the computer language has non-alphanumeric characters,   try to encode them into the negatory numerals,   or use other characters instead.

Solution:
#include <iomanip>
#include <iostream>
#include <tuple>
#include <vector>

const std::string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

std::string encodeNegativeBase(int64_t n, int b) {
    if (b < -62 || b > -1) {
        throw std::runtime_error("Argument out of range: b");
    }
    if (n == 0) {
        return "0";
    }

    std::string output;
    int64_t nn = n;
    while (nn != 0) {
        int rem = nn % b;
        nn /= b;
        if (rem < 0) {
            nn++;
            rem -= b;
        }
        output += DIGITS[rem];
    }

    std::reverse(output.begin(), output.end());
    return output;
}

int64_t decodeNegativeBase(const std::string& ns, int b) {
    if (b < -62 || b > -1) {
        throw std::runtime_error("Argument out of range: b");
    }
    if (ns == "0") {
        return 0;
    }

    int64_t total = 0;
    int64_t bb = 1;

    for (auto it = ns.crbegin(); it != ns.crend(); it = std::next(it)) {
        auto ptr = std::find(DIGITS.cbegin(), DIGITS.cend(), *it);
        if (ptr != DIGITS.cend()) {
            auto idx = ptr - DIGITS.cbegin();
            total += idx * bb;
        }
        bb *= b;
    }
    return total;
}

int main() {
    using namespace std;

    vector<pair<int64_t, int>> nbl({
        make_pair(10, -2),
        make_pair(146, -3),
        make_pair(15, -10),
        make_pair(142961, -62)
        });

    for (auto& p : nbl) {
        string ns = encodeNegativeBase(p.first, p.second);
        cout << setw(12) << p.first << " encoded in base " << setw(3) << p.second << " = " << ns.c_str() << endl;

        int64_t n = decodeNegativeBase(ns, p.second);
        cout << setw(12) << ns.c_str() << " decoded in base " << setw(3) << p.second << " = " << n << endl;

        cout << endl;
    }

    return 0;
}


Nested function

In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.

;Task:
Write a program consisting of two nested functions that prints the following text.

 1. first
 2. second
 3. third

The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.

The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.

;References:
:* Nested function

Solution:
#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> makeList(std::string separator) {
  auto counter = 0;
  auto makeItem = [&](std::string item) {
    return std::to_string(++counter) + separator + item;
  };
  return {makeItem("first"), makeItem("second"), makeItem("third")};
}

int main() {
  for (auto item : makeList(". "))
    std::cout << item << "\n";
}


Nested templated data

A template for data is an arbitrarily nested tree of integer indices.

Data payloads are given as a separate mapping, array or other simpler, flat,
association of indices to individual items of data, and are strings.
The idea is to create a data structure with the templates' nesting, and the
payload corresponding to each index appearing at the position of each index.

Answers using simple string replacement or regexp are to be avoided. The idea is
to use the native, or usual implementation of lists/tuples etc of the language
and to hierarchically traverse the template to generate the output.

;Task Detail:
Given the following input template t  and list of payloads p:
# Square brackets are used here to denote nesting but may be changed for other,
# clear, visual representations of nested data appropriate to ones programming
# language.
t = [
    [[1, 2],
     [3, 4, 1],
     5]]

p = 'Payload#0' ... 'Payload#6'

The correct output should have the following structure, (although spacing and
linefeeds may differ, the nesting and order should follow):
[[['Payload#1', 'Payload#2'],
  ['Payload#3', 'Payload#4', 'Payload#1'],
  'Payload#5']]

1. Generate the output for the above template, t.

;Optional Extended tasks:
2. Show which payloads remain unused.
3. Give some indication/handling of indices without a payload.

''Show output on this page.''

Solution:
#include <iostream>
#include <set>
#include <tuple>
#include <vector>

using namespace std;

// print a single payload
template<typename P>
void PrintPayloads(const P &payloads, int index, bool isLast)
{
    if(index < 0 || index >= (int)size(payloads)) cout << "null";
    else cout << "'" << payloads[index] << "'";
    if (!isLast) cout << ", ";  // add a comma between elements
}

// print a tuple of playloads
template<typename P, typename... Ts>
void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)
{
    std::apply  // recursively call PrintPayloads on each element of the tuple
    (
        [&payloads, isLast](Ts const&... tupleArgs)
        {
            size_t n{0};
            cout << "[";
            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);
            cout << "]";
            cout << (isLast ? "\n" : ",\n");
        }, nestedTuple
    );
}

// find the unique index of a single index (helper for the function below)
void FindUniqueIndexes(set<int> &indexes, int index)
{
    indexes.insert(index);
}

// find the unique indexes in the tuples
template<typename... Ts>
void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)
{
    std::apply
    (
        [&indexes](Ts const&... tupleArgs)
        {
            (FindUniqueIndexes(indexes, tupleArgs),...);
        }, nestedTuple
    );
}

// print the payloads that were not used
template<typename P>
void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)
{
    for(size_t i = 0; i < size(payloads); i++)
    {
        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n";
    }
}

int main()
{
    // define the playloads, they can be in most containers
    vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"};
    const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"}; // as a C array

    // define the indexes as a nested tuple
    auto tpl = make_tuple(make_tuple(
        make_tuple(1, 2),
        make_tuple(3, 4, 1),
        5));

    cout << "Mapping indexes to payloads:\n";
    PrintPayloads(payloads, tpl);

    cout << "\nFinding unused payloads:\n";
    set<int> usedIndexes;
    FindUniqueIndexes(usedIndexes, tpl);
    PrintUnusedPayloads(usedIndexes, payloads);

    cout << "\nMapping to some out of range payloads:\n";
    PrintPayloads(shortPayloads, tpl);

    return 0;
}


Nim game

Nim is a simple game where the second player-if they know the trick-will always win.

The game has only 3 rules:
::*   start with   '''12'''   tokens
::*   each player takes    '''1,  2,  or  3'''   tokens in turn
::*  the player who takes the last token wins.

To win every time,   the second player simply takes 4 minus the number the first player took.   So if the first player takes 1,   the second takes 3; if the first player takes 2,   the second should take 2; and if the first player takes 3,   the second player will take 1.

;Task:
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.

Solution:
#include <iostream>
#include <limits>

using namespace std;

void showTokens(int tokens) {
    cout << "Tokens remaining " << tokens << endl << endl;
}

int main() {
    int tokens = 12;
    while (true) {
        showTokens(tokens);
        cout << "  How many tokens 1, 2 or 3? ";
        int t;
        cin >> t;
        if (cin.fail()) {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << endl << "Invalid input, try again." << endl << endl;
        } else if (t < 1 || t > 3) {
            cout << endl << "Must be a number between 1 and 3, try again." << endl << endl;
        } else {
            int ct = 4 - t;
            string s  = (ct > 1) ? "s" : "";
            cout << "  Computer takes " << ct << " token" << s << endl << endl;
            tokens -= 4;
        }
        if (tokens == 0) {
            showTokens(0);
            cout << "  Computer wins!" << endl;
            return 0;
        }
    }
}


Nonoblock

Nonogram puzzle.

;Given:
* The number of cells in a row.
* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.

;Task:
* show all possible positions.
* show the number of positions of the blocks for the following cases within the row.
* show all output on this page.
* use a "neat" diagram of the block positions.

;Enumerate the following configurations:
#   '''5'''   cells   and   '''[2, 1]'''   blocks
#   '''5'''   cells   and   '''[]'''   blocks   (no blocks)
#   '''10'''   cells   and   '''[8]'''   blocks
#   '''15'''   cells   and   '''[2, 3, 2, 3]'''   blocks
#   '''5'''   cells   and   '''[2, 3]'''   blocks   (should give some indication of this not being possible)

;Example:
Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:

    |_|_|_|_|_| # 5 cells and [2, 1] blocks

And would expand to the following 3 possible rows of block positions:

    |A|A|_|B|_|
    |A|A|_|_|B|
    |_|A|A|_|B|

Note how the sets of blocks are always separated by a space.

Note also that it is not necessary for each block to have a separate letter.
Output approximating

This:
                        |#|#|_|#|_|
                        |#|#|_|_|#|
                        |_|#|#|_|#|

This would also work:
                        ##.#.
                        ##..#
                       .##.#

;An algorithm:
* Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).
* The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.
* for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block.

(This is the algorithm used in the [[Nonoblock#Python]] solution).

;Reference:
* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.

Solution:
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>

typedef std::pair<int, std::vector<int> > puzzle;

class nonoblock {
public:
    void solve( std::vector<puzzle>& p ) {
        for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) {
            counter = 0;
            std::cout << " Puzzle: " << ( *i ).first << " cells and blocks [ ";
            for( std::vector<int>::iterator it = ( *i ).second.begin(); it != ( *i ).second.end(); it++ )
                std::cout << *it << " ";
            std::cout << "] ";
            int s = std::accumulate( ( *i ).second.begin(), ( *i ).second.end(), 0 ) + ( ( *i ).second.size() > 0 ? ( *i ).second.size() - 1 : 0 );
            if( ( *i ).first - s < 0 ) {
                std::cout << "has no solution!\n\n\n";
                continue;
            }
            std::cout << "\n Possible configurations:\n\n";
            std::string b( ( *i ).first, '-' );
            solve( *i, b, 0 );
            std::cout << "\n\n";
        }
    }

private:
    void solve( puzzle p, std::string n, int start ) {
        if( p.second.size() < 1 ) {
            output( n );
            return;
        }
        std::string temp_string;
        int offset,
            this_block_size = p.second[0];

        int space_need_for_others = std::accumulate( p.second.begin() + 1, p.second.end(), 0 );
        space_need_for_others += p.second.size() - 1;

        int space_for_curr_block = p.first - space_need_for_others - std::accumulate( p.second.begin(), p.second.begin(), 0 );

        std::vector<int> v1( p.second.size() - 1 );
        std::copy( p.second.begin() + 1, p.second.end(), v1.begin() );
        puzzle p1 = std::make_pair( space_need_for_others, v1 );

        for( int a = 0; a < space_for_curr_block; a++ ) {
            temp_string = n;

            if( start + this_block_size > n.length() ) return;

            for( offset = start; offset < start + this_block_size; offset++ )
                temp_string.at( offset ) = 'o';

            if( p1.first ) solve( p1, temp_string, offset + 1 );
            else output( temp_string );

            start++;
        }
    }
    void output( std::string s ) {
        char b = 65 - ( s.at( 0 ) == '-' ? 1 : 0 );
        bool f = false;
        std::cout << std::setw( 3 ) << ++counter << "\t|";
        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
            b += ( *i ) == 'o' && f ? 1 : 0;
            std::cout << ( ( *i ) == 'o' ? b : '_' ) << "|";
            f = ( *i ) == '-' ? true : false;
        }
        std::cout << "\n";
    }

    unsigned counter;
};

int main( int argc, char* argv[] )
{
    std::vector<puzzle> problems;
    std::vector<int> blocks;
    blocks.push_back( 2 ); blocks.push_back( 1 );
    problems.push_back( std::make_pair( 5, blocks ) );
    blocks.clear();
    problems.push_back( std::make_pair( 5, blocks ) );
    blocks.push_back( 8 );
    problems.push_back( std::make_pair( 10, blocks ) );
    blocks.clear();
    blocks.push_back( 2 ); blocks.push_back( 3 );
    problems.push_back( std::make_pair( 5, blocks ) );
    blocks.push_back( 2 ); blocks.push_back( 3 );
    problems.push_back( std::make_pair( 15, blocks ) );

    nonoblock nn;
    nn.solve( problems );

    return 0;
}


Nonogram solver

nonogram is a puzzle that provides
numeric clues used to fill in a grid of cells,
establishing for each cell whether it is filled or not.
The puzzle solution is typically a picture of some kind.

Each row and column of a rectangular grid is annotated with the lengths
of its distinct runs of occupied cells.
Using only these lengths you should find one valid configuration
of empty and occupied cells, or show a failure message.

;Example
Problem:                 Solution:

. . . . . . . .  3       . # # # . . . .  3
. . . . . . . .  2 1     # # . # . . . .  2 1
. . . . . . . .  3 2     . # # # . . # #  3 2
. . . . . . . .  2 2     . . # # . . # #  2 2
. . . . . . . .  6       . . # # # # # #  6
. . . . . . . .  1 5     # . # # # # # .  1 5
. . . . . . . .  6       # # # # # # . .  6
. . . . . . . .  1       . . . . # . . .  1
. . . . . . . .  2       . . . # # . . .  2
1 3 1 7 5 3 4 3          1 3 1 7 5 3 4 3
2 1 5 1                  2 1 5 1
The problem above could be represented by two lists of lists:
x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]
y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]
A more compact representation of the same problem uses strings,
where the letters represent the numbers, A=1, B=2, etc:
x = "C BA CB BB F AE F A B"
y = "AB CA AE GA E C D C"

;Task
For this task, try to solve the 4 problems below, read from a "nonogram_problems.txt" file that has this content
(the blank lines are separators):
C BA CB BB F AE F A B
AB CA AE GA E C D C

F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC
D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA

CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC
BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC

E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G
E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM

'''Extra credit''': generate nonograms with unique solutions, of desired height and width.

This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).

; Related tasks
* [[Nonoblock]].

;See also
* Arc Consistency Algorithm
* http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)
* http://twanvl.nl/blog/haskell/Nonograms (Haskell)
* http://picolisp.com/5000/!wiki?99p98 (PicoLisp)

Solution:
// A class to solve Nonogram (Hadje) Puzzles
// Nigel Galloway - January 23rd., 2017
template<uint _N, uint _G> class Nonogram {
  enum class ng_val : char {X='#',B='.',V='?'};
  template<uint _NG> struct N {
    N() {}
    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}
    std::bitset<_NG> X, B, T, Tx, Tb;
    std::vector<int> ng;
    int En, gNG;
    void        fn (const int n,const int i,const int g,const int e,const int l){
      if (fe(g,l,false) and fe(g+l,e,true)){
      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}
      else {
        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}
      }}
      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);
    }
    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}
    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}
    inline bool fe (const int n,const int i, const bool g){
      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;
      return true;
    }
    int         fl (){
      if (En == 1) return 1;
      Tx.set(); Tb.set(); En=0;
      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);
      return En;
    }}; // end of N
  std::vector<N<_G>> ng;
  std::vector<N<_N>> gn;
  int En, zN, zG;
  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}
public:
  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {
    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));
    for (int i=0; i<zN; i++) {
      ng.push_back(N<_G>(n[i],zG));
      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);
    }}
  bool solve(){
    int i{}, g{};
    for (int l = 0; l<zN; l++) {
      if ((g = ng[l].fl()) == 0) return false; else i+=g;
      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);
    }
    for (int l = 0; l<zG; l++) {
      if ((g = gn[l].fl()) == 0) return false; else i+=g;
      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);
    }
    if (i == En)    return false; else En = i;
    if (i == zN+zG) return true;  else return solve();
  }
  const std::string toStr() const {
    std::ostringstream n;
    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}
    return n.str();
  }};


Example
Consider the number 24. Its proper divisors are: 1, 2, 3, 4, 6, 8 and 12. Their product is 13,824 and the cube root of this is 24. So 24 satisfies the definition in the task title.

;Task
Compute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors.

Also show the '''500th''' and '''5,000th''' such numbers.

;Stretch
Compute and show the '''50,000th''' such number.

;Reference
* OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors.

;Note
OEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.

Solution:
#include <iomanip>
#include <iostream>

unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;
    for (; (n & 1) == 0; n >>= 1)
        ++total;
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1;
        for (; n % p == 0; n /= p)
            ++count;
        total *= count;
    }
    if (n > 1)
        total *= 2;
    return total;
}

int main() {
    std::cout.imbue(std::locale(""));
    std::cout << "First 50 numbers which are the cube roots of the products of "
                 "their proper divisors:\n";
    for (unsigned int n = 1, count = 0; count < 50000; ++n) {
        if (n == 1 || divisor_count(n) == 8) {
            ++count;
            if (count <= 50)
                std::cout << std::setw(3) << n
                          << (count % 10 == 0 ? '\n' : ' ');
            else if (count == 500 || count == 5000 || count == 50000)
                std::cout << std::setw(6) << count << "th: " << n << '\n';
        }
    }
}


Numbers with equal rises and falls

When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right).

;Definition:
Given the decimal digits of the number are written as a series   d:
:*   A   ''rise''         is an index   i   such that    d(i)  <  d(i+1)
:*   A   ''fall''    is an index   i   such that    d(i)  >  d(i+1)

;Examples:
:*   The number          '''726,169'''   has   '''3'''   rises and   '''2'''   falls,   so it isn't in the sequence.
:*   The number     '''83,548'''    has   '''2'''   rises and   '''2'''   falls,   so it   is   in the sequence.

;Task:
:*   Print the first   '''200'''    numbers in the sequence
:*   Show that the   '''10 millionth'''   (10,000,000th)   number in the sequence is   '''41,909,002'''

;See also:
*   OEIS Sequence  A296712   describes numbers whose digit sequence in base 10 have equal "rises" and "falls".

;Related tasks:
*   Esthetic numbers

Solution:
#include <iomanip>
#include <iostream>

bool equal_rises_and_falls(int n) {
    int total = 0;
    for (int previous_digit = -1; n > 0; n /= 10) {
        int digit = n % 10;
        if (previous_digit > digit)
            ++total;
        else if (previous_digit >= 0 && previous_digit < digit)
            --total;
        previous_digit = digit;
    }
    return total == 0;
}

int main() {
    const int limit1 = 200;
    const int limit2 = 10000000;
    int n = 0;
    std::cout << "The first " << limit1 << " numbers in the sequence are:\n";
    for (int count = 0; count < limit2; ) {
        if (equal_rises_and_falls(++n)) {
            ++count;
            if (count <= limit1)
                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\n' : ' ');
        }
    }
    std::cout << "\nThe " << limit2 << "th number in the sequence is " << n << ".\n";
}


Numeric error propagation

If   '''f''',   '''a''',   and   '''b'''   are values with uncertainties   sf,   sa,   and   sb,   and   '''c'''   is a constant;
then if   '''f'''   is derived from   '''a''',   '''b''',   and   '''c'''   in the following ways,
then   sf   can be calculated as follows:

:;Addition/Subtraction
:* If   f = a +- c,   or   f = c +- a   then   '''sf = sa'''
:* If   f = a +- b   then   '''sf2 = sa2 + sb2'''

:;Multiplication/Division
:* If   f = ca   or   f = ac       then   '''sf = |csa|'''
:* If   f = ab   or   f = a / b              then   '''sf2 = f2( (sa / a)2 + (sb / b)2)'''

:;Exponentiation
:* If   f = ac   then   '''sf = |fc(sa / a)|'''

Caution:
::This implementation of error propagation does not address issues of dependent and independent values.   It is assumed that   '''a'''   and   '''b'''   are independent and so the formula for multiplication should not be applied to   '''a*a'''   for example.   See   the talk page   for some of the implications of this issue.

;Task details:
# Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations.
# Given coordinates and their errors:x1 = 100 +- 1.1y1 =  50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:   d =    (x1 - x2)2   +   (y1 - y2)2
# Print and display both    '''d'''    and its error.

;References:
* A Guide to Error Propagation B. Keeney, 2005.
* Propagation of uncertainty Wikipedia.

;Related task:
*   [[Quaternion type]]

Solution:
#pragma once

#include <cmath>
#include <string>
#include <sstream>
#include <iomanip>

class Approx {
public:
    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}

    operator std::string() const {
        std::ostringstream os("");
        os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s << std::ends;
        return os.str();
    }

    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }
    Approx operator +(double d) const { return Approx(v + d, s); }
    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }
    Approx operator -(double d) const { return Approx(v - d, s); }

    Approx operator *(const Approx& a) const {
        const double t = v * a.v;
        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));
    }

    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }

    Approx operator /(const Approx& a) const {
        const double t = v / a.v;
        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));
    }

    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }

    Approx pow(double d) const {
        const double t = ::pow(v, d);
        return Approx(t, fabs(t * d * s / v));
    }

private:
    double v, s;
};


Old Russian measure of length

Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa).

It is an example of a linear transformation of several variables.

The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''.

;Also see:
:*   Old Russian measure of length

Solution:
#include <iostream>
#include <iomanip>
//-------------------------------------------------------------------------------------------
using namespace std;

//-------------------------------------------------------------------------------------------
class ormConverter
{
public:
    ormConverter() :  AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),
		      MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}
    void convert( char c, float l )
    {
	system( "cls" );
	cout << endl << l;
	switch( c )
	{
	    case 'A': cout << " Arshin to:";     l *= AR; break;
	    case 'C': cout << " Centimeter to:"; l *= CE; break;
	    case 'D': cout << " Diuym to:";      l *= DI; break;
	    case 'F': cout << " Fut to:";        l *= FU; break;
	    case 'K': cout << " Kilometer to:";  l *= KI; break;
	    case 'L': cout << " Liniya to:";     l *= LI; break;
	    case 'M': cout << " Meter to:";      l *= ME; break;
	    case 'I': cout << " Milia to:";      l *= MI; break;
	    case 'P': cout << " Piad to:";       l *= PI; break;
	    case 'S': cout << " Sazhen to:";     l *= SA; break;
	    case 'T': cout << " Tochka to:";     l *= TO; break;
	    case 'V': cout << " Vershok to:";    l *= VE; break;
	    case 'E': cout << " Versta to:";     l *= VR;
	}

	float ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,
	      mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;
	cout << left << endl << "=================" << endl
	     << setw( 12 ) << "Arshin:" << ar << endl << setw( 12 ) << "Centimeter:" << ce << endl
	     << setw( 12 ) << "Diuym:" << di << endl << setw( 12 ) << "Fut:" << fu << endl
	     << setw( 12 ) << "Kilometer:" << ki << endl << setw( 12 ) << "Liniya:" << li << endl
	     << setw( 12 ) << "Meter:" << me << endl << setw( 12 ) << "Milia:" << mi << endl
	     << setw( 12 ) << "Piad:" << pi << endl << setw( 12 ) << "Sazhen:" << sa << endl
	     << setw( 12 ) << "Tochka:" << to << endl << setw( 12 ) << "Vershok:" << ve << endl
	     << setw( 12 ) << "Versta:" << vr << endl << endl << endl;
    }
private:
    const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;
};
//-------------------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
    ormConverter c;
    char s; float l;
    while( true )
    {
	cout << "What unit:\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\n";
	cin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;
	cout << "Length (0 to Quit): "; cin >> l; if( l == 0 ) return 0;
	c.convert( s, l ); system( "pause" ); system( "cls" );
    }
    return 0;
}
//-------------------------------------------------------------------------------------------


Old lady swallowed a fly

Present a program which emits the lyrics to the song   ''I Knew an Old Lady Who Swallowed a Fly'',   taking advantage of the repetitive structure of the song's lyrics.

This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.

Solution:
#include <iostream>

const char *CREATURES[] = { "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse" };
const char *COMMENTS[] = {
    "I don't know why she swallowed that fly.\nPerhaps she'll die\n",
    "That wiggled and jiggled and tickled inside her",
    "How absurd, to swallow a bird",
    "Imagine that. She swallowed a cat",
    "What a hog to swallow a dog",
    "She just opened her throat and swallowed that goat",
    "I don't know how she swallowed that cow",
    "She's dead of course"
};

int main() {
    auto max = sizeof(CREATURES) / sizeof(char*);
    for (size_t i = 0; i < max; ++i) {
        std::cout << "There was an old lady who swallowed a " << CREATURES[i] << '\n';
        std::cout << COMMENTS[i] << '\n';
        for (int j = i; j > 0 && i < max - 1; --j) {
            std::cout << "She swallowed the " << CREATURES[j] << " to catch the " << CREATURES[j - 1] << '\n';
            if (j == 1)
                std::cout << COMMENTS[j - 1] << '\n';
        }
    }

    return 0;
}


One of n lines in a file

A method of choosing a line randomly from a file:
::* Without reading the file more than once
::* When substantial parts of the file cannot be held in memory
::* Without knowing how many lines are in the file
Is to:
::* keep the first line of the file as a possible choice, then
::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
::* ...
::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N

::* Return the computed possible choice when no further lines exist in the file.

;Task:
# Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run.
# Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times.
# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.

Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.

Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling

Solution:
#include <random>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;

mt19937 engine; //mersenne twister

unsigned int one_of_n(unsigned int n) {
	unsigned int choice;
	for(unsigned int i = 0; i < n; ++i) {
		uniform_int_distribution<unsigned int> distribution(0, i);
		if(!distribution(engine))
			choice = i;
	}
	return choice;
}

int main() {
	engine = mt19937(random_device()()); //seed random generator from system
	unsigned int results[10] = {0};
	for(unsigned int i = 0; i < 1000000; ++i)
		results[one_of_n(10)]++;
	ostream_iterator<unsigned int> out_it(cout, " ");
	copy(results, results+10, out_it);
	cout << '\n';
}


Operator precedence

Operators in C and C++}}

;Task:
Provide a list of   [[wp:order of operations|precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.

State whether arguments are passed by value or by reference.

Solution:
The following is a table that lists the [[wp:order of operations|precedence]] and [[wp:operator associativity|associativity]] of all the operators in the [[wp:C (programming language)|C]] and [[wp:C++|C++]] languages. An operator's precedence is unaffected by overloading.

{| class="wikitable"
|-
! style="text-align: left" | Precedence
! style="text-align: left" | Operator
! style="text-align: left" | Description
! style="text-align: left" | Associativity
|-
! 1
highest
| ::
| Scope resolution (C++ only)
| style="vertical-align: top" rowspan="12" | Left-to-right
|-
! rowspan=11| 2
| style="border-bottom-style: none" | ++
| style="border-bottom-style: none" | Suffix increment
|-
| style="border-bottom-style: none; border-top-style: none" | --
| style="border-bottom-style: none; border-top-style: none" | Suffix decrement
|-
| style="border-bottom-style: none; border-top-style: none" | ()
| style="border-bottom-style: none; border-top-style: none" | Function call
|-
| style="border-bottom-style: none; border-top-style: none" | []
| style="border-bottom-style: none; border-top-style: none" | Array subscripting
|-
| style="border-bottom-style: none; border-top-style: none" | .
| style="border-bottom-style: none; border-top-style: none" | Element selection by reference
|-
| style="border-bottom-style: none; border-top-style: none" | ->
| style="border-bottom-style: none; border-top-style: none" | Element selection through pointer
|-
| style="border-bottom-style: none; border-top-style: none" | typeid()
| style="border-bottom-style: none; border-top-style: none" | [[wp:Run-time type information|Run-time type information]] (C++ only) (see [[wp:typeid|typeid]])
|-
| style="border-bottom-style: none; border-top-style: none" | const_cast
| style="border-bottom-style: none; border-top-style: none" | Type cast (C++ only) (see [[wp:const cast|const cast]])
|-
| style="border-bottom-style: none; border-top-style: none" | dynamic_cast
| style="border-bottom-style: none; border-top-style: none" | Type cast (C++ only) (see [[wp:dynamic_cast|dynamic cast]])
|-
| style="border-bottom-style: none; border-top-style: none" | reinterpret_cast
| style="border-bottom-style: none; border-top-style: none" | Type cast (C++ only) (see [[wp:reinterpret cast|reinterpret cast]])
|-
| style="border-top-style: none" | static_cast
| style="border-top-style: none" | Type cast (C++ only) (see [[wp:static cast|static cast]])
|-
! rowspan=12| 3
| style="border-bottom-style: none" | ++
| style="border-bottom-style: none" | Prefix increment
| style="vertical-align: top" rowspan="12" | Right-to-left
|-
| style="border-bottom-style: none; border-top-style: none" | --
| style="border-bottom-style: none; border-top-style: none" | Prefix decrement
|-
| style="border-bottom-style: none; border-top-style: none" | +
| style="border-bottom-style: none; border-top-style: none" | Unary plus
|-
| style="border-bottom-style: none; border-top-style: none" | -
| style="border-bottom-style: none; border-top-style: none" | Unary minus
|-
| style="border-bottom-style: none; border-top-style: none" | !
| style="border-bottom-style: none; border-top-style: none" | Logical NOT
|-
| style="border-bottom-style: none; border-top-style: none" | ~
| style="border-bottom-style: none; border-top-style: none" | Bitwise NOT
|-
| style="border-bottom-style: none; border-top-style: none" | (''type'')
| style="border-bottom-style: none; border-top-style: none" | Type cast
|-
| style="border-bottom-style: none; border-top-style: none" | *
| style="border-bottom-style: none; border-top-style: none" | Indirection (dereference)
|-
| style="border-bottom-style: none; border-top-style: none" | &
| style="border-bottom-style: none; border-top-style: none" | Address-of
|-
| style="border-bottom-style: none; border-top-style: none" | sizeof
| style="border-bottom-style: none; border-top-style: none" | [[wp:sizeof|Size-of]]
|-
| style="border-bottom-style: none; border-top-style: none" | new, new[]
| style="border-bottom-style: none; border-top-style: none" | Dynamic memory allocation (C++ only)
|-
| style="border-top-style: none" | delete, delete[]
| style="border-top-style: none" | Dynamic memory deallocation (C++ only)
|-
! rowspan=2| 4
| style="border-bottom-style: none" | .*
| style="border-bottom-style: none" | Pointer to member (C++ only)
| style="vertical-align: top" rowspan="20" | Left-to-right
|-
| style="border-bottom-style: none; border-top-style: none" | ->*
| style="border-bottom-style: none; border-top-style: none" | Pointer to member (C++ only)
|-
! rowspan=3| 5
| style="border-bottom-style: none" | *
| style="border-bottom-style: none" | Multiplication
|-
| style="border-bottom-style: none; border-top-style: none" | /
| style="border-bottom-style: none; border-top-style: none" | Division
|-
| style="border-bottom-style: none; border-top-style: none" | %
| style="border-bottom-style: none; border-top-style: none" | [[wp:Modulo operation|Modulo]] (remainder)
|-
! rowspan=2| 6
| style="border-bottom-style: none" | +
| style="border-bottom-style: none" | Addition
|-
| style="border-bottom-style: none; border-top-style: none" | -
| style="border-bottom-style: none; border-top-style: none" | Subtraction
|-
! rowspan=2| 7
| style="border-bottom-style: none" | <<
| style="border-bottom-style: none" | [[wp:Bitwise operation|Bitwise]] left shift
|-
| style="border-bottom-style: none; border-top-style: none" | >>
| style="border-bottom-style: none; border-top-style: none" | [[wp:Bitwise operation|Bitwise]] right shift
|-
! rowspan=4| 8
| style="border-bottom-style: none" | <
| style="border-bottom-style: none" | Less than
|-
| style="border-bottom-style: none; border-top-style: none" | <=
| style="border-bottom-style: none; border-top-style: none" | Less than or equal to
|-
| style="border-bottom-style: none; border-top-style: none" | >
| style="border-bottom-style: none; border-top-style: none" | Greater than
|-
| style="border-bottom-style: none; border-top-style: none" | >=
| style="border-bottom-style: none; border-top-style: none" | Greater than or equal to
|-
! rowspan=2| 9
| style="border-bottom-style: none" | ==
| style="border-bottom-style: none" | Equal to
|-
| style="border-bottom-style: none; border-top-style: none" | !=
| style="border-bottom-style: none; border-top-style: none" | Not equal to
|-
! 10
| &
| Bitwise AND
|-
! 11
| ^
| Bitwise XOR (exclusive or)
|-
! 12
| <nowiki>|</nowiki>
| Bitwise OR (inclusive or)
|-
! 13
| &&
| Logical AND
|-
! 14
| <nowiki>||</nowiki>
| Logical OR
|-
! 15
| ?:
| [[wp:Ternary operator|Ternary]] conditional (see [[wp:?:|?:]])
| style="vertical-align: top" rowspan="12" | Right-to-left
|-
! rowspan=11| 16
| style="border-bottom-style: none" | =
| style="border-bottom-style: none" | Direct assignment
|-
| style="border-bottom-style: none; border-top-style: none" | +=
| style="border-bottom-style: none; border-top-style: none" | Assignment by sum
|-
| style="border-bottom-style: none; border-top-style: none" | -=
| style="border-bottom-style: none; border-top-style: none" | Assignment by difference
|-
| style="border-bottom-style: none; border-top-style: none" | *=
| style="border-bottom-style: none; border-top-style: none" | Assignment by product
|-
| style="border-bottom-style: none; border-top-style: none" | /=
| style="border-bottom-style: none; border-top-style: none" | Assignment by quotient
|-
| style="border-bottom-style: none; border-top-style: none" | %=
| style="border-bottom-style: none; border-top-style: none" | Assignment by remainder
|-
| style="border-bottom-style: none; border-top-style: none" | <<=
| style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise left shift
|-
| style="border-bottom-style: none; border-top-style: none" | >>=
| style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise right shift
|-
| style="border-bottom-style: none; border-top-style: none" | &=
| style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise AND
|-
| style="border-bottom-style: none; border-top-style: none" | ^=
| style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise XOR
|-
| style="border-bottom-style: none; border-top-style: none" | <nowiki>|</nowiki>=
| style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise OR
|-
! 17
| throw
| Throw operator (exceptions throwing, C++ only)
|
|-
! 18
| ,
| [[wp:Comma operator|Comma]]
| Left-to-right
|}

For quick reference, see also [http://cpp.operator-precedence.com this] equivalent, color-coded table.