Minimal steps down to 1

Given:
* A starting, positive integer (greater than one), N.
* A selection of possible integer perfect divisors, D.
* And a selection of possible subtractors, S.
The goal is find the minimum number of steps  necessary to reduce N down to one.

At any step, the number may be:
* Divided by any member of D if it is perfectly divided by D, (remainder zero).
* OR have one of S subtracted from it, if N is greater than the member of S.

There may be many ways to reduce the initial N down to 1. Your program needs to:
* Find the ''minimum'' number of ''steps'' to reach 1.
* Show '''one''' way of getting fron N to 1 in those minimum steps.

;Examples:
No divisors, D. a single subtractor of 1.
:Obviousely N will take N-1 subtractions of 1 to reach 1

Single divisor of 2; single subtractor of 1:
:N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
:N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1

Divisors 2 and 3; subtractor 1:
:N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1

;Task:
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:

:1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
:2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.

Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:

:3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
:4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.

;Optional stretch goal:
:2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000

;Reference:
* Learn Dynamic Programming (Memoization & Tabulation) Video of similar task.

Solution:
using System;
using System.Collections.Generic;
using System.Linq;

public static class MinimalSteps
{
    public static void Main() {
        var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });
        var lookup = CreateLookup(2_000, divisors, subtractors);
        Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]");
        PrintRange(lookup, 10);
        PrintMaxMins(lookup);
        lookup = CreateLookup(20_000, divisors, subtractors);
        PrintMaxMins(lookup);
        Console.WriteLine();

        subtractors = new [] { 2 };
        lookup = CreateLookup(2_000, divisors, subtractors);
        Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]");
        PrintRange(lookup, 10);
        PrintMaxMins(lookup);
        lookup = CreateLookup(20_000, divisors, subtractors);
        PrintMaxMins(lookup);
    }

    private static void PrintRange((char op, int param, int steps)[] lookup, int limit) {
        for (int goal = 1; goal <= limit; goal++) {
            var x = lookup[goal];
            if (x.param == 0) {
                Console.WriteLine($"{goal} cannot be reached with these numbers.");
                continue;
            }
            Console.Write($"{goal} takes {x.steps} {(x.steps == 1 ? "step" : "steps")}: ");
            for (int n = goal; n > 1; ) {
                Console.Write($"{n},{x.op}{x.param}=> ");
                n = x.op == '/' ? n / x.param : n - x.param;
                x = lookup[n];
            }
            Console.WriteLine("1");
        }
    }

    private static void PrintMaxMins((char op, int param, int steps)[] lookup) {
        var maxSteps = lookup.Max(x => x.steps);
        var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList();
        Console.WriteLine(items.Count == 1
            ? $"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}"
            : $"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}"
        );
    }

    private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors)
    {
        var lookup = new (char op, int param, int steps)[goal+1];
        lookup[1] = ('/', 1, 0);
        for (int n = 1; n < lookup.Length; n++) {
            var ln = lookup[n];
            if (ln.param == 0) continue;
            for (int d = 0; d < divisors.Length; d++) {
                int target = n * divisors[d];
                if (target > goal) break;
                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1);
            }
            for (int s = 0; s < subtractors.Length; s++) {
                int target = n + subtractors[s];
                if (target > goal) break;
                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1);
            }
        }
        return lookup;
    }

    private static string Delimit<T>(this IEnumerable<T> source) => string.Join(", ", source);
}


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:
using System;
using System.Collections.Generic;
using static System.Console;

class Program {

  static string B10(int n) {
    int[] pow = new int[n + 1], val = new int[29];
    for (int count = 0, ten = 1, x = 1; x <= n; x++) {
      val[x] = ten;
      for (int j = 0, t; j <= n; j++)
        if (pow[j] != 0 && pow[j] != x && pow[t = (j + ten) % n] == 0)
          pow[t] = x;
      if (pow[ten] == 0) pow[ten] = x;
      ten = (10 * ten) % n;
      if (pow[0] != 0) {
        x = n;
        string s = "";
        while (x != 0) {
          int p = pow[x % n];
          if (count > p) s += new string('0', count - p);
          count = p - 1;
          s += "1";
          x = (n + x - val[p]) % n;
        }
        if (count > 0) s += new string('0', count);
        return s;
      }
    }
    return "1";
  }

  static void Main(string[] args) {
    string fmt = "{0,4} * {1,24} = {2,-28}\n";
    int[] m = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
      95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
      297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878 };
    string[] r = new string[m.Length];
    WriteLine(fmt + new string('-', 62), "n", "multiplier", "B10");
    var sw = System.Diagnostics.Stopwatch.StartNew();
    for (int i = 0; i < m.Length; i++) r[i] = B10(m[i]);
    sw.Stop();
    for (int i = 0; i < m.Length; i++) Write(fmt, m[i], decimal.Parse(r[i]) / m[i], r[i]);
    Write("\nTook {0}ms", sw.Elapsed.TotalMilliseconds);
  }
}


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:
using System;

namespace ModularArithmetic {
    interface IAddition<T> {
        T Add(T rhs);
    }
    interface IMultiplication<T> {
        T Multiply(T rhs);
    }
    interface IPower<T> {
        T Power(int pow);
    }
    interface IOne<T> {
        T One();
    }

    class ModInt : IAddition<ModInt>, IMultiplication<ModInt>, IPower<ModInt>, IOne<ModInt> {
        private int modulo;

        public ModInt(int value, int modulo) {
            Value = value;
            this.modulo = modulo;
        }

        public int Value { get; }

        public ModInt One() {
            return new ModInt(1, modulo);
        }

        public ModInt Add(ModInt rhs) {
            return this + rhs;
        }

        public ModInt Multiply(ModInt rhs) {
            return this * rhs;
        }

        public ModInt Power(int pow) {
            return Pow(this, pow);
        }

        public override string ToString() {
            return string.Format("ModInt({0}, {1})", Value, modulo);
        }

        public static ModInt operator +(ModInt lhs, ModInt rhs) {
            if (lhs.modulo != rhs.modulo) {
                throw new ArgumentException("Cannot add rings with different modulus");
            }
            return new ModInt((lhs.Value + rhs.Value) % lhs.modulo, lhs.modulo);
        }

        public static ModInt operator *(ModInt lhs, ModInt rhs) {
            if (lhs.modulo != rhs.modulo) {
                throw new ArgumentException("Cannot add rings with different modulus");
            }
            return new ModInt((lhs.Value * rhs.Value) % lhs.modulo, lhs.modulo);
        }

        public static ModInt Pow(ModInt self, int p) {
            if (p < 0) {
                throw new ArgumentException("p must be zero or greater");
            }

            int pp = p;
            ModInt pwr = self.One();
            while (pp-- > 0) {
                pwr *= self;
            }
            return pwr;
        }
    }

    class Program {
        static T F<T>(T x) where T : IAddition<T>, IMultiplication<T>, IPower<T>, IOne<T> {
            return x.Power(100).Add(x).Add(x.One());
        }

        static void Main(string[] args) {
            ModInt x = new ModInt(10, 13);
            ModInt y = F(x);
            Console.WriteLine("x ^ 100 + x + 1 for x = {0} is {1}", x, y);
        }
    }
}


Modular exponentiation

Find the last   '''40'''   decimal digits of   a^b,   where

::*   a = 2988348162058574136915891421498819466320163312926952423791023078876139
::*   b = 2351399303373464486466122544523690094744975233415544072992656881240319

A computer is too slow to find the entire value of   a^b.

Instead, the program must use a fast algorithm for modular exponentiation:   a^b \mod m.

The algorithm must work for any integers   a, b, m,     where   b \ge 0   and   m > 0.

Solution:
using System;
using System.Numerics;

class Program
{
    static void Main() {
        var a = BigInteger.Parse("2988348162058574136915891421498819466320163312926952423791023078876139");
        var b = BigInteger.Parse("2351399303373464486466122544523690094744975233415544072992656881240319");
        var m = BigInteger.Pow(10, 40);
        Console.WriteLine(BigInteger.ModPow(a, b, m));
    }
}


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:
public class Program
{
    static void Main()
    {
        System.Console.WriteLine(42.ModInverse(2017));
    }
}

public static class IntExtensions
{
    public static int ModInverse(this int a, int m)
    {
        if (m == 1) return 0;
        int m0 = m;
        (int x, int y) = (1, 0);

        while (a > 1) {
            int q = a / m;
            (a, m) = (m, a % m);
            (x, y) = (y, x - q * y);
        }
        return x < 0 ? x + m0 : x;
    }
}


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:
using System;

namespace RosettaMaybe
{
    // courtesy of https://www.dotnetcurry.com/patterns-practices/1510/maybe-monad-csharp
    public abstract class Maybe<T>
    {
        public sealed class Some : Maybe<T>
        {
            public Some(T value) => Value = value;
            public T Value { get; }
        }
        public sealed class None : Maybe<T> { }
    }

    class Program
    {
        static Maybe<double> MonadicSquareRoot(double x)
        {
            if (x >= 0)
            {
                return new Maybe<double>.Some(Math.Sqrt(x));
            }
            else
            {
                return new Maybe<double>.None();
            }
        }
        static void Main(string[] args)
        {
            foreach (double x in new double[] { 4.0D, 8.0D, -15.0D, 16.23D, -42 })
            {
                Maybe<double> maybe = MonadicSquareRoot(x);
                if (maybe is Maybe<double>.Some some)
                {
                    Console.WriteLine($"The square root of {x} is " + some.Value);
                }
                else
                {
                    Console.WriteLine($"Square root of {x} is undefined.");
                }
            }
        }
    }
}


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:
using System;
using System.Collections.Generic;
using System.Text;

namespace MoveToFront
{
    class Program
    {
        private static char[] symbolTable;
        private static void setSymbolTable()
        {
            symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
        }

        private static void moveToFront(int charIndex)
        {
            char toFront = symbolTable[charIndex];
            for (int j = charIndex; j > 0; j--)
            {
                symbolTable[j] = symbolTable[j - 1];
            }
            symbolTable[0] = toFront;
        }

        public static int[] Encode(string input)
        {
            setSymbolTable();
            var output = new List<int>();
            foreach (char c in input)
            {
                for (int i = 0; i < 26; i++)
                {
                    if (symbolTable[i] == c)
                    {
                        output.Add(i);
                        moveToFront(i);
                        break;
                    }
                }
            }
            return output.ToArray();
        }

        public static string Decode(int[] input)
        {
            setSymbolTable();
            var output = new StringBuilder(input.Length);
            foreach (int n in input)
            {
                output.Append(symbolTable[n]);
                moveToFront(n);
            }
            return output.ToString();
        }

        static void Main(string[] args)
        {
            string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" };
            int[] encoding;
            foreach (string s in testInputs)
            {
                Console.WriteLine($"Encoding for '{s}':");
                encoding = Encode(s);
                foreach (int i in encoding)
                {
                    Console.Write($"{i} ");
                }
                Console.WriteLine($"\nDecoding for '{s}':");
                Console.WriteLine($"{Decode(encoding)}\n");
            }
        }
    }
}


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:
var array = (int[,,,])Array.CreateInstance(typeof(int), new [] { 5, 4, 3, 2 }, new [] { 10, 10, 10, 10 });
int n = 1;
//Note: GetUpperBound is inclusive
for (int a = array.GetLowerBound(0); a <= array.GetUpperBound(0); a++)
for (int b = array.GetLowerBound(1); b <= array.GetUpperBound(1); b++)
for (int c = array.GetLowerBound(2); c <= array.GetUpperBound(2); c++)
for (int d = array.GetLowerBound(3); d <= array.GetUpperBound(3); d++)
    array[a, b, c, d] = n++;

//To set the first value, we must now use the lower bounds:
array[10, 10, 10, 10] = 999;
//As with all arrays, Length gives the TOTAL length.
Console.WriteLine("Length: " + array.Length);
Console.WriteLine("First 30 elements:");
//The multidimensional array does not implement the generic IEnumerable<int>
//so we need to cast the elements.
Console.WriteLine(string.Join(" ",  array.Cast<int>().Take(30)) + " ...");


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:
namespace RosettaCode.Multifactorial
{
    using System;
    using System.Linq;

    internal static class Program
    {
        private static void Main()
        {
            Console.WriteLine(string.Join(Environment.NewLine,
                                          Enumerable.Range(1, 5)
                                                    .Select(
                                                        degree =>
                                                        string.Join(" ",
                                                                    Enumerable.Range(1, 10)
                                                                              .Select(
                                                                                number =>
                                                                                Multifactorial(number, degree))))));
        }

        private static int Multifactorial(int number, int degree)
        {
            if (degree < 1)
            {
                throw new ArgumentOutOfRangeException("degree");
            }

            var count = 1 + (number - 1) / degree;
            if (count < 1)
            {
                throw new ArgumentOutOfRangeException("number");
            }

            return Enumerable.Range(0, count)
                             .Aggregate(1, (accumulator, index) => accumulator * (number - degree * index));
        }
    }
}


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:
using System;
using System.Linq;
using System.Collections.Generic;

List<Foo> foos = Enumerable.Range(1, n).Select(x => new Foo()).ToList();


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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Multisplit
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            foreach (var s in "a!===b=!=c".Multisplit(true, "==", "!=", "=")) // Split the string and return the separators.
            {
                Console.Write(s); // Write the returned substrings and separators to the console.
            }
            Console.WriteLine();
        }

        private static IEnumerable<string> Multisplit(this string s, bool returnSeparators = false,
                                                      params string[] delimiters)
        {
            var currentString = new StringBuilder(); /* Initiate the StringBuilder. This will hold the current string to return
                                                      * once we find a separator. */

            int index = 0; // Initiate the index counter at 0. This tells us our current position in the string to read.

            while (index < s.Length) // Loop through the string.
            {
                // This will get the highest priority separator found at the current index, or null if there are none.
                string foundDelimiter =
                    (from delimiter in delimiters
                     where s.Length >= index + delimiter.Length &&
                           s.Substring(index, delimiter.Length) == delimiter
                     select delimiter).FirstOrDefault();

                if (foundDelimiter != null)
                {
                    yield return currentString.ToString(); // Return the current string.
                    if (returnSeparators) // Return the separator, if the user specified to do so.
                        yield return
                            string.Format("{{\"{0}\", ({1}, {2})}}",
                                          foundDelimiter,
                                          index, index + foundDelimiter.Length);
                    currentString.Clear(); // Clear the current string.
                    index += foundDelimiter.Length; // Move the index past the current separator.
                }
                else
                {
                    currentString.Append(s[index++]); // Add the character at this index to the current string.
                }
            }

            if (currentString.Length > 0)
                yield return currentString.ToString(); // If we have anything left over, return it.
        }
    }
}


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:
Func<char, int> toInt = c => c-'0';

foreach (var i in Enumerable.Range(1,5000)
	.Where(n => n == n.ToString()
		.Sum(x => Math.Pow(toInt(x), toInt(x)))))
	Console.WriteLine(i);


Munchausen numbers

Solution:
using System;

namespace Munchhausen
{
    class Program
    {
        static readonly long[] cache = new long[10];

        static void Main()
        {
            // Allow for 0 ^ 0 to be 0
            for (int i = 1; i < 10; i++)
            {
                cache[i] = (long)Math.Pow(i, i);
            }

            for (long i = 0L; i <= 500_000_000L; i++)
            {
                if (IsMunchhausen(i))
                {
                    Console.WriteLine(i);
                }
            }
            Console.ReadLine();
        }

        private static bool IsMunchhausen(long n)
        {
            long sum = 0, nn = n;
            do
            {
                sum += cache[(int)(nn % 10)];
                if (sum > n)
                {
                    return false;
                }
                nn /= 10;
            } while (nn > 0);

            return sum == n;
        }
    }
}


Munchausen numbers

Solution:
using System;

static class Program
{
    public static void Main()
    {
        long sum, ten1 = 0, ten2 = 10; byte [] num; int [] pow = new int[10];
        int i, j, n, n1, n2, n3, n4, n5, n6, n7, n8, n9, s2, s3, s4, s5, s6, s7, s8;
        for (i = 1; i <= 9; i++) { pow[i] = i; for (j = 2; j <= i; j++) pow[i] *= i; }
        for (n = 1; n <= 11; n++) { for (n9 = 0; n9 <= n; n9++) { for (n8 = 0; n8 <= n - n9; n8++) {
              for (n7 = 0; n7 <= n - (s8 = n9 + n8); n7++) { for (n6 = 0; n6 <= n - (s7 = s8 + n7); n6++) {
                  for (n5 = 0; n5 <= n - (s6 = s7 + n6); n5++) { for (n4 = 0; n4 <= n - (s5 = s6 + n5); n4++) {
                      for (n3 = 0; n3 <= n - (s4 = s5 + n4); n3++) { for (n2 = 0; n2 <= n - (s3 = s4 + n3); n2++) {
                          for (n1 = 0; n1 <= n - (s2 = s3 + n2); n1++) {
                            sum = n1 * pow[1] + n2 * pow[2] + n3 * pow[3] + n4 * pow[4] +
                                  n5 * pow[5] + n6 * pow[6] + n7 * pow[7] + n8 * pow[8] + n9 * pow[9];
                            if (sum < ten1 || sum >= ten2) continue;
                            num = new byte[10]; foreach (char ch in sum.ToString()) num[Convert.ToByte(ch) - 48] += 1;
                            if (n - (s2 + n1) == num[0] && n1 == num[1] && n2 == num[2]
                              && n3 == num[3] && n4 == num[4] && n5 == num[5] && n6 == num[6]
                              && n7 == num[7] && n8 == num[8] && n9 == num[9]) Console.WriteLine(sum);
                          } } } } } } } } }
          ten1 = ten2; ten2 *= 10;
        }
    }
}


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:
=== Roger Hui (1981) Algorithm ===
From Hui, Roger, The N Queens Problem, APL Quote-Quad, Volume 11, Number 3, 1981-03:-

"In a solution, each possible row (column) index must appear exactly once: an index occurring more than once means that two queens are on the same row (column); and the absence of an index means that some other index must occur more than once. Hence, we can specify an arrangement as a permutation of ⍳n , which are the column indices, with the row indices understood to be ⍳n . With this, the number of possibilities is reduced from n!n×n to !n . It remains to eliminate arrangements having two queens on the same diagonal.

If two queens occupy the same diagonal, the line connecting them has slope 1 or ¯1 . Conversely, if the line connecting two queens has slope 1 or ¯1 , the two queens share a diagonal. Therefore, we seek to eliminate all permutations specifying a pair of queens where
((change in y) ÷ (change in x)) ∊ 1 ¯1 , or (|change in y) = (|change in x)"


N-queens problem

Solution:
using static System.Linq.Enumerable;
using static System.Console;

namespace N_Queens
{
    static class Program
    {
        static void Main(string[] args)
        {
            var n = 8;
            var domain = Range(0, n).ToArray();

            var amb = new Amb.Amb();
            var queens = domain.Select(_ => amb.Choose(domain)).ToArray();
            amb.Require(() => n == queens.Select(q=> q.Value).Distinct().Count());
            amb.Require(() => n == domain.Select(i=> i + queens[i].Value).Distinct().Count());
            amb.Require(() => n == domain.Select(i=> i - queens[i].Value).Distinct().Count());

            if (amb.Disambiguate())
            {
                WriteLine("Position is row, value is column:-");
                WriteLine(string.Join(" ", queens.AsEnumerable()));
            }
            else
                WriteLine("amb is angry");
            Read();
        }
    }
}


Narcissist

Quoting from the Esolangs wiki page:

A '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]].

A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.

For concreteness, in this task we shall assume that symbol = character.

The narcissist should be able to cope with any finite input, whatever its length.

Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.

Solution:
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Narcisisst
{
	class Program
	{
		public static void Main(string[] args)
		{
			const string path = @"E:\Narcisisst";
			string[] thisFile = Directory.GetFiles(path , "Program.cs");
			StringBuilder sb = new StringBuilder();

				foreach (string readLine in File.ReadLines(thisFile[0]))
				{
					sb.Append(readLine);
					sb.Append("\n");
				}

			Console.WriteLine(sb);
			string input =String.Empty;
			       	input = Console.ReadLine();
			       	Console.WriteLine((Regex.IsMatch(sb.ToString(),input))?"accept":"reject");
			       	Console.ReadKey();
			 }
	}
}


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:
using System;

namespace Narcissistic
{
    class Narcissistic
    {
        public bool isNarcissistic(int z)
        {
            if (z < 0) return false;
            string n = z.ToString();
            int t = 0, l = n.Length;
            foreach (char c in n)
                t += Convert.ToInt32(Math.Pow(Convert.ToDouble(c - 48), l));

            return t == z;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Narcissistic n = new Narcissistic();
            int c = 0, x = 0;
            while (c < 25)
            {
                if (n.isNarcissistic(x))
                {
                    if (c % 5 == 0) Console.WriteLine();
                    Console.Write("{0,7} ", x);
                    c++;
                }
                x++;
            }
            Console.WriteLine("\n\nPress any key to continue...");
            Console.ReadKey();
        }
    }
}


Narcissistic decimal number

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Numerics;

static class Program
{
    public static void nar(int max, bool only1 = false)
    {
        int n, n1, n2, n3, n4, n5, n6, n7, n8, n9;
        int[] d;                                       // digits tally
        char [] bs;                                    // BigInteger String
        List<BigInteger> res = new List<BigInteger>(); // per n digits results
        BigInteger[,] p = new BigInteger[10, max + 1]; // powers array

        // BigIntegers for intermediate results
        BigInteger x2, x3, x4, x5, x6, x7, x8, x9;

        for (n = only1 ? max : 1; n <= max; n++) // main loop
        {
            for (int i = 1; i <= 9; i++) // init powers array for this n
            {
                p[i, 1] = BigInteger.Pow(i, n);
                for (int j = 2; j <= n; j++) p[i, j] = p[i, 1] * j;
            }
            for (n9 = n; n9 >= 0; n9--) // nested loops...
            {
                x9 = p[9, n9];
                for (n8 = n - n9; n8 >= 0; n8--)
                {
                    x8 = x9 + p[8, n8];
                    for (n7 = n - n9 - n8; n7 >= 0; n7--)
                    {
                        x7 = x8 + p[7, n7];
                        for (n6 = n - n9 - n8 - n7; n6 >= 0; n6--)
                        {
                            x6 = x7 + p[6, n6];
                            for (n5 = n - n9 - n8 - n7 - n6; n5 >= 0; n5--)
                            {
                                x5 = x6 + p[5, n5];
                                for (n4 = n - n9 - n8 - n7 - n6 - n5; n4 >= 0; n4--)
                                {
                                    x4 = x5 + p[4, n4];
                                    for (n3 = n - n9 - n8 - n7 - n6 - n5 - n4; n3 >= 0; n3--)
                                    {
                                        x3 = x4 + p[3, n3];
                                        for (n2 = n - n9 - n8 - n7 - n6 - n5 - n4 - n3; n2 >= 0; n2--)
                                        {
                                            x2 = x3 + p[2, n2];
                                            for (n1 = n - n9 - n8 - n7 - n6 - n5 - n4 - n3 - n2; n1 >= 0; n1--)
                                            {
                                                bs = (x2 + n1).ToString().ToCharArray();
                                                switch (bs.Length.CompareTo(n))
                                                { // Since all the for/next loops step down, when the digit count
                                                  // becomes smaller than n, it's time to try the next n value.
                                                    case -1: { goto Next_n; }
                                                    case 0:
                                                        {
                                                            d = new int[10]; foreach (char c in bs) d[c - 48] += 1;
                                                            if (n9 == d[9] && n8 == d[8] && n7 == d[7] &&
                                                                n6 == d[6] && n5 == d[5] && n4 == d[4] &&
                                                                n3 == d[3] && n2 == d[2] && n1 == d[1] &&
                                                                n - n9 - n8 - n7 - n6 - n5 - n4 - n3 - n2 - n1 == d[0])
                                                                res.Add(BigInteger.Parse(new string(bs)));
                                                            break;
                                                        }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
Next_n:     if (only1) {
                Console.Write("{0} ", n); lock (resu) resu.AddRange(res); return;
            } else {
                res.Sort(); Console.WriteLine("{2,3} {0,3}: {1}",
                Math.Ceiling((DateTime.Now - st).TotalSeconds), string.Join(" ", res), n); res.Clear();
            }
        }
    }

    private static DateTime st = default(DateTime);
    private static List<BigInteger> resu = new List<BigInteger>();
    private static bool para = true; // parallel (default) or sequential calcualtion
    private static int lim = 7;  // this is the number of digits to calcualate, not the nth entry.
                                 // for up to the 25th item, use lim = 7 digits.
                                 // for all 89 items, use lim = 39 digits.
    public static void Main(string[] args)
    {
        if (args.Count() > 0)
        {
            int t = lim; int.TryParse(args[0], out t);
            if (t < 1) t = 1;   // number of digits must be > 0
            if (t > 61) t = 61; // no point when lim * math.pow(9, lim) < math.pow(10, lim - 1)
            lim = t;
            // default is parallel, will do sequential when any 2nd command line parameter is present.
            para = !(args.Count() > 1);
        }
        st = DateTime.Now;
        if (para)
        {
            Console.Write("Calculations in parallel... "); // starts the bigger ones first
            Parallel.ForEach(Enumerable.Range(1, lim).Reverse().ToArray(), n => { nar(n, true); } );
            resu.Sort(); int[] g = Enumerable.Range(1, resu.Count).ToArray();
            var both = g.Zip(resu, (a, b) => a.ToString() + " " + b.ToString());
            Console.WriteLine("\n{0}", string.Join("\n", both));
        }
        else { Console.WriteLine("Sequential calculations:"); nar(lim); }
        Console.WriteLine("Total elasped: {0} seconds", (DateTime.Now - st).TotalSeconds);
        if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();
    }
}


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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NegativeBaseNumbers {
    class Program {
        const string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

        static string EncodeNegativeBase(long n, int b) {
            if (b < -62 || b > -1) {
                throw new ArgumentOutOfRangeException("b");
            }
            if (n == 0) {
                return "0";
            }
            StringBuilder output = new StringBuilder();
            long nn = n;
            while (nn != 0) {
                int rem = (int)(nn % b);
                nn /= b;
                if (rem < 0) {
                    nn++;
                    rem -= b;
                }
                output.Append(DIGITS[rem]);
            }
            return new string(output.ToString().Reverse().ToArray());
        }

        static long DecodeNegativeBase(string ns, int b) {
            if (b < -62 || b > -1) {
                throw new ArgumentOutOfRangeException("b");
            }
            if (ns == "0") {
                return 0;
            }
            long total = 0;
            long bb = 1;
            for (int i = ns.Length - 1; i >= 0; i--) {
                char c = ns[i];
                total += DIGITS.IndexOf(c) * bb;
                bb *= b;
            }
            return total;
        }

        static void Main(string[] args) {
            List<Tuple<long, int>> nbl = new List<Tuple<long, int>>() {
                new Tuple<long, int>(10,-2),
                new Tuple<long, int>(146,-3),
                new Tuple<long, int>(15,-10),
                new Tuple<long, int>(-34025238427,-62),
            };
            foreach (var p in nbl) {
                string ns = EncodeNegativeBase(p.Item1, p.Item2);
                Console.WriteLine("{0,12} encoded in base {1,-3} = {2}", p.Item1, p.Item2, ns);
                long n = DecodeNegativeBase(ns, p.Item2);
                Console.WriteLine("{0,12} decoded in base {1,-3} = {2}", ns, p.Item2, n);
                Console.WriteLine();
            }
        }
    }
}


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:
string MakeList(string separator)
{
    int counter = 1;

    Func<string, string> makeItem = item => counter++ + separator + item + "\n";

    return makeItem("first") + makeItem("second") + makeItem("third");
}

Console.WriteLine(MakeList(". "));


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:
using System;

namespace nimGame
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("There are twelve tokens.\n" +
                    "You can take 1, 2, or 3 on your turn.\n" +
                    "Whoever takes the last token wins.\n");

            int tokens = 12;

            while (tokens > 0)
            {
                Console.WriteLine("There are " + tokens + " remaining.");
                Console.WriteLine("How many do you take?");
                int playertake = Convert.ToInt32(Console.ReadLine());

                if (playertake < 1 | playertake > 3)
                {
                    Console.WriteLine("1, 2, or 3 only.");
                }
                else
                {
                    tokens -= playertake;
                    Console.WriteLine("I take " + (4 - playertake) + ".");
                    tokens -= (4 - playertake);
                }
            }
            Console.WriteLine("I win again.");
            Console.ReadLine();
        }

    }
}


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:
using System;
using System.Linq;
using System.Text;

public static class Nonoblock
{
    public static void Main() {
        Positions(5, 2,1);
        Positions(5);
        Positions(10, 8);
        Positions(15, 2,3,2,3);
        Positions(5, 2,3);
    }

    public static void Positions(int cells, params int[] blocks) {
        if (cells < 0 || blocks == null || blocks.Any(b => b < 1)) throw new ArgumentOutOfRangeException();
        Console.WriteLine($"{cells} cells with [{string.Join(", ", blocks)}]");
        if (blocks.Sum() + blocks.Length - 1 > cells) {
            Console.WriteLine("No solution");
            return;
        }
        var spaces = new int[blocks.Length + 1];
        int total = -1;
        for (int i = 0; i < blocks.Length; i++) {
            total += blocks[i] + 1;
            spaces[i+1] = total;
        }
        spaces[spaces.Length - 1] = cells - 1;
        var sb = new StringBuilder(string.Join(".", blocks.Select(b => new string('#', b))).PadRight(cells, '.'));
        Iterate(sb, spaces, spaces.Length - 1, 0);
        Console.WriteLine();
    }

    private static void Iterate(StringBuilder output, int[] spaces, int index, int offset) {
        Console.WriteLine(output.ToString());
        if (index <= 0) return;
        int count = 0;
        while (output[spaces[index] - offset] != '#') {
            count++;
            output.Remove(spaces[index], 1);
            output.Insert(spaces[index-1], '.');
            spaces[index-1]++;
            Iterate(output, spaces, index - 1, 1);
        }
        if (offset == 0) return;
        spaces[index-1] -= count;
        output.Remove(spaces[index-1], count);
        output.Insert(spaces[index] - count, ".", count);
    }

}


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:
using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;

public static class NonogramSolver
{
    public static void Main2() {
        foreach (var (x, y) in new [] {
            ("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")
            })
        {
            Solve(x, y);
            Console.WriteLine();
        }
    }

    static void Solve(string rowLetters, string columnLetters) {
        var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();
        var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();
        Solve(r, c);
    }

    static void Solve(int[][] rowRuns, int[][] columnRuns) {
        int len = columnRuns.Length;
        var rows = rowRuns.Select(row => Generate(len, row)).ToList();
        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();
        Reduce(rows, columns);
        foreach (var list in rows) {
            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());
            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());
        }
    }

    static List<BitSet> Generate(int length, params int[] runs) {
        var list = new List<BitSet>();
        BitSet initial = BitSet.Empty;
        int[] sums = new int[runs.Length];
        sums[0] = 0;
        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;
        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);
        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);
        return list;
    }

    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {
        if (index == runs.Length) {
            result.Add(current);
            return;
        }
        while (current.Value < max.Value) {
            Generate(result, max, runs, sums, current, index + 1, shift);
            current = current.ShiftLeftAt(sums[index] + shift);
            shift++;
        }
    }

    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {
        for (int count = 1; count > 0; ) {
            foreach (var (rowIndex, row) in rows.WithIndex()) {
                var allOn  = row.Aggregate((a, b) => a & b);
                var allOff = row.Aggregate((a, b) => a | b);
                foreach (var (columnIndex, column) in columns.WithIndex()) {
                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));
                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));
                }
            }
            foreach (var (columnIndex, column) in columns.WithIndex()) {
                var allOn  = column.Aggregate((a, b) => a & b);
                var allOff = column.Aggregate((a, b) => a | b);
                foreach (var (rowIndex, row) in rows.WithIndex()) {
                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));
                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));
                }
            }
        }
    }

    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {
        int i = 0;
        foreach (T element in source) {
            yield return (i++, element);
        }
    }

    static string Reverse(this string s) {
        char[] array = s.ToCharArray();
        Array.Reverse(array);
        return new string(array);
    }

    static string Spaced(this IEnumerable<char> s) => string.Join(" ", s);

    struct BitSet //Unused functionality elided.
    {
        public static BitSet Empty => default;
        private readonly int bits;
        public int Value => bits;

        private BitSet(int bits) => this.bits = bits;

        public BitSet Add(int item) => new BitSet(bits | (1 << item));
        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));
        public bool Contains(int item) => (bits & (1 << item)) != 0;
        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));
        public override string ToString() => Convert.ToString(bits, 2);

        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);
        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);
    }

}


Integer squares are the set of integers multiplied by themselves: 1 x 1 = '''1''', 2 x 2 = '''4''', 3 x 3 = '''9''', etc. ( 1, 4, 9, 16 ... )

Most positive integers can be generated as the sum of 1 or more distinct integer squares.

      '''1''' == 1
      '''5''' == 4 + 1
     '''25''' == 16 + 9
     '''77''' == 36 + 25 + 16
    '''103''' == 49 + 25 + 16 + 9 + 4
Many can be generated in multiple ways:

     '''90''' == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9
    '''130''' == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9

The number of positive integers that '''cannot''' be generated by any combination of distinct squares is in fact finite:

    2, 3, 6, 7, etc.

;Task

Find and show here, on this page, '''every''' positive integer than cannot be generated as the sum of distinct squares.

Do not use magic numbers or pre-determined limits. Justify your answer mathematically.

;See also

* OEIS: A001422 Numbers which are not the sum of distinct squares

Solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Program {

  // recursively permutates the list of squares to seek a matching sum
  static bool soms(int n, IEnumerable<int> f) {
    if (n <= 0) return false;
    if (f.Contains(n)) return true;
    switch(n.CompareTo(f.Sum())) {
      case 1: return false;
      case 0: return true;
      case -1:
        var rf = f.Reverse().Skip(1).ToList();
        return soms(n - f.Last(), rf) || soms(n, rf);
    }
    return false;
  }

  static void Main() {
    var sw = System.Diagnostics.Stopwatch.StartNew();
    int c = 0, r, i, g; var s = new List<int>(); var a = new List<int>();
    var sf = "stopped checking after finding {0} sequential non-gaps after the final gap of {1}";
    for (i = 1, g = 1; g >= (i >> 1); i++) {
      if ((r = (int)Math.Sqrt(i)) * r == i) s.Add(i);
      if (!soms(i, s)) a.Add(g = i);
    }
    sw.Stop();
    Console.WriteLine("Numbers which are not the sum of distinct squares:");
    Console.WriteLine(string.Join(", ", a));
    Console.WriteLine(sf, i - g, g);
    Console.Write("found {0} total in {1} ms",
      a.Count, sw.Elapsed.TotalMilliseconds);
  }
}


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:
using System;
class Program {

  static bool dc8(uint n) {
    uint res = 1, count, p, d;
    for ( ; (n & 1) == 0; n >>= 1) res++;
    for (count = 1; n % 3 == 0; n /= 3) count++;
    for (p = 5, d = 4; p * p <= n; p += d = 6 - d)
        for (res *= count, count = 1; n % p == 0; n /= p) count++;
    return n > 1 ? res * count == 4 : res * count == 8;
  }

  static void Main(string[] args) {
    Console.WriteLine("First 50 numbers which are the cube roots of the products of "
                      + "their proper divisors:");
    for (uint n = 1, count = 0, lmt = 500; count < 5e6; ++n) if (n == 1 || dc8(n))
        if (++count <= 50) Console.Write("{0,3}{1}",n, count % 10 == 0 ? '\n' : ' ');
        else if (count == lmt) Console.Write("{0,16:n0}th: {1:n0}\n", count, n, lmt *= 10);
  }
}


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:
using System;

namespace OldLady
{
    internal class Program
    {
        private const string reason = "She swallowed the {0} to catch the {1}";
        private static readonly string[] creatures = {"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"};

        private static readonly string[] 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"
        };

        private static void Main()
        {
            int max = creatures.Length;
            for (int i = 0; i < max; i++)
            {
                Console.WriteLine("There was an old lady who swallowed a {0}", creatures[i]);
                Console.WriteLine(comments[i]);
                for (int j = i; j > 0 && i < max - 1; j--)
                {
                    Console.WriteLine(reason, creatures[j], creatures[j - 1]);
                    if (j == 1)
                    {
                        Console.WriteLine(comments[j - 1]);
                    }
                }
            }
            Console.Read();
        }
    }
}


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:
class Program
    {
        private static Random rnd = new Random();
        public static int one_of_n(int n)
        {
            int currentChoice = 1;
            for (int i = 2; i <= n; i++)
            {
                double outerLimit = 1D / (double)i;
                if (rnd.NextDouble() < outerLimit)
                    currentChoice = i;
            }
            return currentChoice;
        }

        static void Main(string[] args)
        {
            Dictionary<int, int> results = new Dictionary<int, int>();
            for (int i = 1; i < 11; i++)
                results.Add(i, 0);

            for (int i = 0; i < 1000000; i++)
            {
                int result = one_of_n(10);
                results[result] = results[result] + 1;
            }

            for (int i = 1; i < 11; i++)
                Console.WriteLine("{0}\t{1}", i, results[i]);
            Console.ReadLine();
        }
    }


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: [http://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/ MSDN documentation]


Palindrome dates

Today   ('''2020-02-02''',   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   '''yyyy-mm-dd'''   format but,   unusually,   also for countries which use the   '''dd-mm-yyyy'''   format.

;Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the   '''yyyy-mm-dd'''   format.

Solution:
using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    static void Main()
    {
        foreach (var date in PalindromicDates(2021).Take(15)) WriteLine(date.ToString("yyyy-MM-dd"));
    }

    public static IEnumerable<DateTime> PalindromicDates(int startYear) {
        for (int y = startYear; ; y++) {
            int m = Reverse(y % 100);
            int d = Reverse(y / 100);
            if (IsValidDate(y, m, d, out var date)) yield return date;
        }

        int Reverse(int x) => x % 10 * 10 + x / 10;
        bool IsValidDate(int y, int m, int d, out DateTime date) => DateTime.TryParse($"{y}-{m}-{d}", out date);
    }
}


Pangram checker

A pangram is a sentence that contains all the letters of the English alphabet at least once.

For example:   ''The quick brown fox jumps over the lazy dog''.

;Task:
Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use.

;Related tasks:
:*   determine if a string has all the same characters
:*   determine if a string has all unique characters

Solution:
using System;

namespace PangrammChecker
{
    public class PangrammChecker
    {
        public static bool IsPangram(string str)
        {
            bool[] isUsed = new bool[26];
            int ai = (int)'a';
            int total = 0;
            for (CharEnumerator en = str.ToLower().GetEnumerator(); en.MoveNext(); )
            {
                int d = (int)en.Current - ai;
                if (d >= 0 && d < 26)
                    if (!isUsed[d])
                    {
                        isUsed[d] = true;
                        total++;
                    }
            }
            return (total == 26);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "The quick brown fox jumps over the lazy dog.";
            string str2 = "The qu1ck brown fox jumps over the lazy d0g.";
            Console.WriteLine("{0} is {1}a pangram", str1,
                PangrammChecker.IsPangram(str1)?"":"not ");
            Console.WriteLine("{0} is {1}a pangram", str2,
                PangrammChecker.IsPangram(str2)?"":"not ");
            Console.WriteLine("Press Return to exit");
            Console.ReadLine();
        }
    }
}


Parsing/RPN calculator algorithm

Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed ''as a table''.

* Assume an input of a correct, space separated, string of tokens of an RPN expression
* Test with the RPN expression generated from the   [[Parsing/Shunting-yard algorithm]]   task:
         3 4 2 * 1 5 - 2 3 ^ ^ / +
* Print or display the output here

;Notes:
*    '''^'''    means exponentiation in the expression above.
*    '''/'''    means division.

;See also:
*   [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
*   Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).
*   [[Parsing/RPN to infix conversion]].
*   [[Arithmetic evaluation]].

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Threading;

namespace RPNEvaluator
{
    class RPNEvaluator
    {
        static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            string rpn = "3 4 2 * 1 5 - 2 3 ^ ^ / +";
            Console.WriteLine("{0}\n", rpn);

            decimal result = CalculateRPN(rpn);
            Console.WriteLine("\nResult is {0}", result);
        }

        static decimal CalculateRPN(string rpn)
        {
            string[] rpnTokens = rpn.Split(' ');
            Stack<decimal> stack = new Stack<decimal>();
            decimal number = decimal.Zero;

            foreach (string token in rpnTokens)
            {
                if (decimal.TryParse(token, out number))
                {
                    stack.Push(number);
                }
                else
                {
                    switch (token)
                    {
                        case "^":
                        case "pow":
                            {
                                number = stack.Pop();
                                stack.Push((decimal)Math.Pow((double)stack.Pop(), (double)number));
                                break;
                            }
                        case "ln":
                            {
                                stack.Push((decimal)Math.Log((double)stack.Pop(), Math.E));
                                break;
                            }
                        case "sqrt":
                            {
                                stack.Push((decimal)Math.Sqrt((double)stack.Pop()));
                                break;
                            }
                        case "*":
                            {
                                stack.Push(stack.Pop() * stack.Pop());
                                break;
                            }
                        case "/":
                            {
                                number = stack.Pop();
                                stack.Push(stack.Pop() / number);
                                break;
                            }
                        case "+":
                            {
                                stack.Push(stack.Pop() + stack.Pop());
                                break;
                            }
                        case "-":
                            {
                                number = stack.Pop();
                                stack.Push(stack.Pop() - number);
                                break;
                            }
                        default:
                            Console.WriteLine("Error in CalculateRPN(string) Method!");
                            break;
                    }
                }
                PrintState(stack);
            }

            return stack.Pop();
        }

        static void PrintState(Stack<decimal> stack)
        {
            decimal[] arr = stack.ToArray();

            for (int i = arr.Length - 1; i >= 0; i--)
            {
                Console.Write("{0,-8:F3}", arr[i]);
            }

            Console.WriteLine();
        }
    }
}


Parsing/RPN to infix conversion

Create a program that takes an infix notation.

* Assume an input of a correct, space separated, string of tokens
* Generate a space separated output string representing the same expression in infix notation
* Show how the major datastructure of your algorithm changes with each new token parsed.
* Test with the following input RPN strings then print and display the output here.
:::::{| class="wikitable"
! RPN input !! sample output
|- || align="center"
| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
|- || align="center"
| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
|}

* Operator precedence and operator associativity is given in this table:
::::::::{| class="wikitable"

! operator !! associativity !! operation
|- || align="center"
|                    ^   ||  4  ||  right  ||  exponentiation
|- || align="center"
|                    *   ||  3  ||   left  ||  multiplication
|- || align="center"
|                    /   ||  3  ||   left  ||     division
|- || align="center"
|                    +   ||  2  ||   left  ||     addition
|- || align="center"
|                    -   ||  2  ||   left  ||   subtraction
|}

;See also:
*   [[Parsing/Shunting-yard algorithm]]   for a method of generating an RPN from an infix expression.
*   [[Parsing/RPN calculator algorithm]]   for a method of calculating a final value from this output RPN expression.
*   Postfix to infix   from the RubyQuiz site.

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace PostfixToInfix
{
    class Program
    {
        class Operator
        {
            public Operator(char t, int p, bool i = false)
            {
                Token = t;
                Precedence = p;
                IsRightAssociative = i;
            }

            public char Token { get; private set; }
            public int Precedence { get; private set; }
            public bool IsRightAssociative { get; private set; }
        }

        static IReadOnlyDictionary<char, Operator> operators = new Dictionary<char, Operator>
        {
            { '+', new Operator('+', 2) },
            { '-', new Operator('-', 2) },
            { '/', new Operator('/', 3) },
            { '*', new Operator('*', 3) },
            { '^', new Operator('^', 4, true) }
        };

        class Expression
        {
            public String ex;
            public Operator op;

            public Expression(String e)
            {
                ex = e;
            }

            public Expression(String e1, String e2, Operator o)
            {
                ex = String.Format("{0} {1} {2}", e1, o.Token, e2);
                op = o;
            }
        }

        static String PostfixToInfix(String postfix)
        {
            var stack = new Stack<Expression>();

            foreach (var token in Regex.Split(postfix, @"\s+"))
            {
                char c = token[0];

                var op = operators.FirstOrDefault(kv => kv.Key == c).Value;
                if (op != null && token.Length == 1)
                {
                    Expression rhs = stack.Pop();
                    Expression lhs = stack.Pop();

                    int opPrec = op.Precedence;

                    int lhsPrec = lhs.op != null ? lhs.op.Precedence : int.MaxValue;
                    int rhsPrec = rhs.op != null ? rhs.op.Precedence : int.MaxValue;

                    if ((lhsPrec < opPrec || (lhsPrec == opPrec && c == '^')))
                        lhs.ex = '(' + lhs.ex + ')';

                    if ((rhsPrec < opPrec || (rhsPrec == opPrec && c != '^')))
                        rhs.ex = '(' + rhs.ex + ')';

                    stack.Push(new Expression(lhs.ex, rhs.ex, op));
                }
                else
                {
                    stack.Push(new Expression(token));
                }

                // print intermediate result
                Console.WriteLine("{0} -> [{1}]", token,
                    string.Join(", ", stack.Reverse().Select(e => e.ex)));
            }
            return stack.Peek().ex;
        }

        static void Main(string[] args)
        {
            string[] inputs = { "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^" };
            foreach (var e in inputs)
            {
                Console.WriteLine("Postfix : {0}", e);
                Console.WriteLine("Infix : {0}", PostfixToInfix(e));
                Console.WriteLine(); ;
            }
            Console.ReadLine();
        }
    }
}


Parsing/Shunting-yard algorithm

Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.

* Assume an input of a correct, space separated, string of tokens representing an infix expression
* Generate a space separated output string representing the RPN
* Test with the input string:
::::  3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
* print and display the output here.
* Operator precedence is given in this table:
:{| class="wikitable"

! operator !! associativity !! operation
|- || align="center"
|                     ^   ||  4  ||  right  ||  exponentiation
|- || align="center"
|                     *   ||  3  ||  left   ||  multiplication
|- || align="center"
|                     /   ||  3  ||  left   ||  division
|- || align="center"
|                     +   ||  2  ||  left   ||  addition
|- || align="center"
|                     -   ||  2  ||  left   ||  subtraction
|}

;Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.

;Note
The handling of functions and arguments is not required.

;See also:
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* [[Parsing/RPN to infix conversion]].

Solution:
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main() {
        string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
        Console.WriteLine(infix.ToPostfix());
    }
}

public static class ShuntingYard
{
    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators
        = new (string symbol, int precedence, bool rightAssociative) [] {
            ("^", 4, true),
            ("*", 3, false),
            ("/", 3, false),
            ("+", 2, false),
            ("-", 2, false)
    }.ToDictionary(op => op.symbol);

    public static string ToPostfix(this string infix) {
        string[] tokens = infix.Split(' ');
        var stack = new Stack<string>();
        var output = new List<string>();
        foreach (string token in tokens) {
            if (int.TryParse(token, out _)) {
                output.Add(token);
                Print(token);
            } else if (operators.TryGetValue(token, out var op1)) {
                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {
                    int c = op1.precedence.CompareTo(op2.precedence);
                    if (c < 0 || !op1.rightAssociative && c <= 0) {
                        output.Add(stack.Pop());
                    } else {
                        break;
                    }
                }
                stack.Push(token);
                Print(token);
            } else if (token == "(") {
                stack.Push(token);
                Print(token);
            } else if (token == ")") {
                string top = "";
                while (stack.Count > 0 && (top = stack.Pop()) != "(") {
                    output.Add(top);
                }
                if (top != "(") throw new ArgumentException("No matching left parenthesis.");
                Print(token);
            }
        }
        while (stack.Count > 0) {
            var top = stack.Pop();
            if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis.");
            output.Add(top);
        }
        Print("pop");
        return string.Join(" ", output);

        //Yikes!
        void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}");
        //A little more readable?
        void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]");
    }
}


Pascal's triangle/Puzzle

This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.

           [ 151]
          [  ][  ]
        [40][  ][  ]
      [  ][  ][  ][  ]
    [ X][11][ Y][ 4][ Z]

Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the middle one is the sum of the other two (that is, Y = X + Z).

;Task:
Write a program to find a solution to this puzzle.

Solution:
using System;

namespace Pyramid_of_Numbers
{
        class Program
	{
		public static void Main(string[] args)
		{
			// Set console properties
			Console.Title = " Pyramid of Numbers  /  Pascal's triangle Puzzle";
			Console.SetBufferSize(80,1000);
			Console.SetWindowSize(80,60);
			Console.ForegroundColor = ConsoleColor.Green;

			// Main Program Loop
			ConsoleKeyInfo k = new ConsoleKeyInfo('Y', ConsoleKey.Y,true,true,true);
			while (k.Key == ConsoleKey.Y)
			{
				Console.Clear();

				Console.WriteLine("----------------------------------------------");
				Console.WriteLine(" Pyramid of Numbers / Pascal's triangle Puzzle");
				Console.WriteLine("----------------------------------------------");
				Console.WriteLine();

				//
				// Declare new Pyramid array
				//
				int r = 5;// Number of rows
				int [,] Pyramid = new int[r,r];

				// Set initial Pyramid values
				for (int i = 0; i < r; i++)
				{
					for(int j = 0; j < r; j++)
					{
						Pyramid[i,j] = 0;
					}
				}
				// Show info on created array
				Console.WriteLine(" Pyramid has " + r + " rows");
				Console.WriteLine("--------------------------------------------");

				// Enter Pyramid values
				for(int i = 0; i <= r-1; i++)
				{
					Console.WriteLine(" Enter " + (i+1).ToString() + ". row values:");
					Console.WriteLine("--------------------------------------------");

					for(int j = 0; j < i+1; j++)
					{
						Console.Write(" " + (j+1).ToString() + ". value = ");
						int v = int.Parse(Console.ReadLine());

						Pyramid[i,j] = v;
					}
					Console.WriteLine("--------------------------------------------");
				}

				//
				// Show initial Pyramid values
				//
				Console.WriteLine();
				Console.WriteLine(" Initial Pyramid Values ");
				Console.WriteLine();

				// Show Pyramid values
				for(int i = 0; i <= r-1; i++)
				{
					for(int j = 0; j < i+1; j++)
					{
						Console.Write("{0,4}",Pyramid[i,j]);
					}
					Console.WriteLine();
				}
				Console.WriteLine("--------------------------------------------");

				// Find solution
				Solve_Pyramid(Pyramid);

				Console.WriteLine();
				Console.Write(" Start new calculation <Y/N>  . . . ");
				k = Console.ReadKey(true);
			}
		}

                //
                // Solve Function
                //
		public static void Solve_Pyramid(int [,] Pyramid)
		{
			int r = 5; // Number of rows

			// Calculate Y
			int a = Pyramid[r-1,1];
			int b = Pyramid[r-1,3];
			int c = Pyramid[0,0];

			int y =  (c - (4*a) - (4*b))/7;
			Pyramid[r-1,2] = y;

			// Create copy of Pyramid
			int [,] Pyramid_Copy = new int[r,r];
			Array.Copy(Pyramid,Pyramid_Copy,r*r);

			int n = 0; // solution counter
			for(int x = 0; x < y + 1; x++)
			{
				for(int z = 0; z < y + 1; z++)
				{
					if( (x+z) == y)
					{
						Pyramid[r-1,0]   = x;
						Pyramid[r-1,r-1] = z;

						// Recalculate Pyramid values
						for(int i = r-1; i > 0; i--)
						{
							for(int j = 0; j < i; j++)
							{
								Pyramid[i-1,j] = Pyramid[i,j]+Pyramid[i,j+1];
							}
						}

						// Compare Pyramid values
						bool solved = true;
						for(int i = 0; i < r-1; i++)
						{
							for(int j = 0; j < i+1; j++)
							{
								if(Pyramid_Copy[i,j]>0)
								{
									if(Pyramid[i,j] != Pyramid_Copy[i,j])
									{
										solved = false;
										i = r;
										break;
									}
								}
							}
						}

						if(solved)
						{
							n++;
							Console.WriteLine();
							Console.WriteLine(" Solved Pyramid Values no." + n);
							Console.WriteLine();

							// Show Pyramid values
							for(int i = 0; i <= r-1; i++)
							{
								for(int j = 0; j < i+1; j++)
								{
									Console.Write("{0,4}",Pyramid[i,j]);
								}
								Console.WriteLine();
							}
							Console.WriteLine();
							Console.WriteLine(" X = " + Pyramid[r-1,0] + "   " +
							                  " Y = " + Pyramid[r-1,2] + "   " +
							                  " Z = " + Pyramid[r-1,4]);
							Console.WriteLine();
							Console.WriteLine("--------------------------------------------");
						}

						Array.Copy(Pyramid_Copy,Pyramid,r*r);
					}
				}
			}

			if(n == 0)
			{
				Console.WriteLine();
				Console.WriteLine(" Pyramid has no solution ");
				Console.WriteLine();
			}
		}

	}
}


Pascal matrix generation

A pascal matrix is a two-dimensional square matrix holding numbers from   binomial coefficients   and which can be shown as    nCr.

Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4.

A Pascal upper-triangular matrix that is populated with   jCi:

[[1, 1, 1, 1, 1],
 [0, 1, 2, 3, 4],
 [0, 0, 1, 3, 6],
 [0, 0, 0, 1, 4],
 [0, 0, 0, 0, 1]]

A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix):

[[1, 0, 0, 0, 0],
 [1, 1, 0, 0, 0],
 [1, 2, 1, 0, 0],
 [1, 3, 3, 1, 0],
 [1, 4, 6, 4, 1]]

A Pascal symmetric matrix that is populated with   i+jCi:

[[1, 1, 1, 1, 1],
 [1, 2, 3, 4, 5],
 [1, 3, 6, 10, 15],
 [1, 4, 10, 20, 35],
 [1, 5, 15, 35, 70]]

;Task:
Write functions capable of generating each of the three forms of   n-by-n   matrices.

Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page.

The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows).

;Note:
The   [[Cholesky decomposition]]   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.

Solution:
using System;

public static class PascalMatrixGeneration
{
    public static void Main() {
        Print(GenerateUpper(5));
        Console.WriteLine();
        Print(GenerateLower(5));
        Console.WriteLine();
        Print(GenerateSymmetric(5));
    }

    static int[,] GenerateUpper(int size) {
        int[,] m = new int[size, size];
        for (int c = 0; c < size; c++) m[0, c] = 1;
        for (int r = 1; r < size; r++) {
            for (int c = r; c < size; c++) {
                m[r, c] = m[r-1, c-1] + m[r, c-1];
            }
        }
        return m;
    }

    static int[,] GenerateLower(int size) {
        int[,] m = new int[size, size];
        for (int r = 0; r < size; r++) m[r, 0] = 1;
        for (int c = 1; c < size; c++) {
            for (int r = c; r < size; r++) {
                m[r, c] = m[r-1, c-1] + m[r-1, c];
            }
        }
        return m;
    }

    static int[,] GenerateSymmetric(int size) {
        int[,] m = new int[size, size];
        for (int i = 0; i < size; i++) m[0, i] = m[i, 0] = 1;
        for (int r = 1; r < size; r++) {
            for (int c = 1; c < size; c++) {
                m[r, c] = m[r-1, c] + m[r, c-1];
            }
        }
        return m;
    }

    static void Print(int[,] matrix) {
        string[,] m = ToString(matrix);
        int width = m.Cast<string>().Select(s => s.Length).Max();
        int rows = matrix.GetLength(0), columns = matrix.GetLength(1);
        for (int row = 0; row < rows; row++) {
            Console.WriteLine("|" + string.Join(" ", Range(0, columns).Select(column => m[row, column].PadLeft(width, ' '))) + "|");
        }
    }

    static string[,] ToString(int[,] matrix) {
        int rows = matrix.GetLength(0), columns = matrix.GetLength(1);
        string[,] m = new string[rows, columns];
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                m[r, c] = matrix[r, c].ToString();
            }
        }
        return m;
    }

}


Password generator

Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
          lower-case letters:  a --> z
          upper-case letters:  A --> Z
                      digits:  0 --> 9
  other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~
  (the above character list excludes white-space, backslash and grave)

The generated password(s) must include   ''at least one''   (of each of the four groups):
    lower-case letter,
    upper-case letter,
    digit  (numeral),   and
    one  "other"  character.

The user must be able to specify the password length and the number of passwords to generate.

The passwords should be displayed or written to a file, one per line.

The randomness should be from a system source or library.

The program should implement a help option or button which should describe the program and options when invoked.

You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.

For example:            Il1     O0     5S     2Z            where the characters are:
::::*   capital eye, lowercase ell, the digit one
::::*   capital oh, the digit zero
::::*   the digit five, capital ess
::::*   the digit two, capital zee

Solution:
using System;
using System.Linq;

class Program
{
    const string Lower = "abcdefghijklmnopqrstuvwxyz";
    const string Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const string Digits = "0123456789";
    const string Symbols = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";
    static readonly string[] Full = {Lower, Upper, Digits, Symbols, Lower + Upper + Digits + Symbols};

    const string Similar = "Il1O05S2Z";
    static readonly string[] Excluded = Full.Select(x => new string(x.Except(Similar).ToArray())).ToArray();

    static Random _rng = new Random();
    static string[] _symbolSet = Full;

    static void Main(string[] args)
    {
        int length = 12, count = 1;
        try
        {
            foreach (var x in args.Select(arg => arg.Split(':')))
            {
                switch (x[0])
                {
                    case "-l": length = int.Parse(x[1]); break;
                    case "-c": count = int.Parse(x[1]); break;
                    case "-s": _rng = new Random(x[1].GetHashCode()); break;
                    case "-x": _symbolSet = bool.Parse(x[1]) ? Excluded : Full; break;
                    default: throw new FormatException("Could not parse arguments");
                }
            }
        }
        catch { ShowUsage(); return; }
        try
        {
            for (int i = 0; i < count; i++)
                Console.WriteLine(GeneratePass(length));
        }
        catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); }
    }

    static void ShowUsage()
    {
        Console.WriteLine("Usage: PASSGEN [-l:length] [-c:count] [-s:seed] [-x:(true|false)]");
        Console.WriteLine("\t-l: the length of the generated passwords");
        Console.WriteLine("\t-c: the number of passwords to generate");
        Console.WriteLine("\t-s: seed for the random number generator");
        Console.WriteLine("\t-x: exclude similar characters: " + Similar);
        Console.WriteLine("Example: PASSGEN -l:10 -c:5 -s:\"Sample Seed\" -x:true");
    }

    static string GeneratePass(int length)
    {
        var minLength = _symbolSet.Length - 1;
        if(length < minLength)
            throw new Exception("password length must be " + minLength + " or greater");

        int[] usesRemaining = Enumerable.Repeat(1, _symbolSet.Length).ToArray();
        usesRemaining[minLength] = length - minLength;
        var password = new char[length];
        for (int ii = 0; ii < length; ii++)
        {
            int set = _rng.Next(0, _symbolSet.Length);
            if (usesRemaining[set] > 0)
            {
                usesRemaining[set]--;
                password[ii] = _symbolSet[set][_rng.Next(0, _symbolSet[set].Length)];
            }
            else ii--;
        }
        return new string(password);
    }
}