Intersecting number wheels

A number wheel has:
* A ''name'' which is an uppercase letter.
* A set of ordered ''values'' which are either ''numbers'' or ''names''.

A ''number'' is generated/yielded from a named wheel by:
:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel":
::1.a If the value is a number, yield it.
::1.b If the value is a name, yield the next value from the named wheel
::1.c Advance the position of this wheel.

Given the wheel
: A: 1 2 3
the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...

'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the
first named wheel is assumed to be the one that values are generated from.

;Examples:
Given the wheels:
    A: 1 B 2
    B: 3 4
The series of numbers generated starts:
    1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...

The intersections of number wheels can be more complex, (and might loop forever),
and wheels may be multiply connected.

'''Note:''' If a named wheel is referenced more than
once by one or many other wheels, then there is only one position of the wheel
that is advanced by each and all references to it.

E.g.
  A:  1 D D
  D:  6 7 8
  Generates:
    1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ...

;Task:
Generate and show the first twenty terms of the sequence of numbers generated
from these groups:

    Intersecting Number Wheel group:
      A:  1 2 3

    Intersecting Number Wheel group:
      A:  1 B 2
      B:  3 4

    Intersecting Number Wheel group:
      A:  1 D D
      D:  6 7 8

    Intersecting Number Wheel group:
      A:  1 B C
      B:  3 4
      C:  5 B

Show your output here, on this page.

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

public static class IntersectingNumberWheels
{
    public static void Main() {
        TurnWheels(('A', "123")).Take(20).Print();
        TurnWheels(('A', "1B2"), ('B', "34")).Take(20).Print();
        TurnWheels(('A', "1DD"), ('D', "678")).Take(20).Print();
        TurnWheels(('A', "1BC"), ('B', "34"), ('C', "5B")).Take(20).Print();
    }

    static IEnumerable<char> TurnWheels(params (char name, string values)[] wheels) {
        var data = wheels.ToDictionary(wheel => wheel.name, wheel => wheel.values.Loop().GetEnumerator());
        var primary = data[wheels[0].name];
        while (true) {
            yield return Turn(primary);
        }

        char Turn(IEnumerator<char> sequence) {
            sequence.MoveNext();
            char c = sequence.Current;
            return char.IsDigit(c) ? c : Turn(data[c]);
        }
    }

    static IEnumerable<T> Loop<T>(this IEnumerable<T> seq) {
        while (true) {
            foreach (T element in seq) yield return element;
        }
    }

    static void Print(this IEnumerable<char> sequence) => Console.WriteLine(string.Join(" ", sequence));
}


Iterated digits squaring

If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1

An example in Python:

>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))
>>> [iterate(x) for x in xrange(1, 20)]
[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]

;Task:
: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.
Or, for much less credit - (showing that your algorithm and/or language is slow):
: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.

This problem derives from the Project Euler problem 92.

For a quick algorithm for this task see the talk page

;Related tasks:
* [[Combinations with repetitions]]
* [[Digital root]]
* [[Digital root/Multiplicative digital root]]

Solution:
using System;
public static class IteratedDigitsSquaring
{
    public static void Main() {
        Console.WriteLine(Count89s(1_000_000));
        Console.WriteLine(Count89s(100_000_000));
    }

    public static int Count89s(int limit) {
        if (limit < 1) return 0;
        int[] end = new int[Math.Min(limit, 9 * 9 * 9 + 2)];
        int result = 0;

        for (int i = 1; i < end.Length; i++) {
            for (end[i] = i; end[i] != 1 && end[i] != 89; end[i] = SquareDigitSum(end[i])) { }
            if (end[i] == 89) result++;
        }
        for (int i = end.Length; i < limit; i++) {
            if (end[SquareDigitSum(i)] == 89) result++;
        }
        return result;

        int SquareDigitSum(int n) {
            int sum = 0;
            while (n > 0) {
                int digit = n % 10;
                sum += digit * digit;
                n /= 10;
            }
            return sum;
        }
    }

}


Iterated digits squaring

Solution:
using System;
using System.Numerics;

class Program {

  const int MaxPow = 301;
  static int [] sq = {1, 4, 9, 16, 25, 36, 49, 64, 81};
  static BigInteger [] sums;

  static bool is89(int x) {
    while (true) {
      int s = 0, t;
      do if ((t = (x % 10) - 1) >= 0) s += sq[t]; while ((x /= 10) > 0);
      if (s == 89) return true;
      if (s == 1) return false;
      x = s;
    }
  }

  static BigInteger count89(int n) {
      BigInteger result = 0;
      for (int i = n * 81; i > 0; i--) {
        foreach (int s in sq) { if(s > i) break; sums[i] += sums[i - s]; }
        if (is89(i)) result += sums[i];
      }
      return result;
  }

  static void Main(string[] args) {
    BigInteger [] t = new BigInteger[2] {1, 0}; sums = new BigInteger[MaxPow * 81]; Array.Copy(t, sums, t.Length);
    DateTime st = DateTime.Now;
    for (int n = 1; n < MaxPow; n++) {
      Console.Write("1->10^{0,-3}: {1}\n", n, count89(n));
      if ((DateTime.Now - st).TotalSeconds > 6) break;
    }
    Console.WriteLine("{0} seconds elapsed.", (DateTime.Now - st).TotalSeconds);
  }
}


JSON

Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.

Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).

Solution:
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

class Program
{
    static void Main()
    {
        var people = new Dictionary<string, object> {{"1", "John"}, {"2", "Susan"}};
        var serializer = new JavaScriptSerializer();

        var json = serializer.Serialize(people);
        Console.WriteLine(json);

        var deserialized = serializer.Deserialize<Dictionary<string, object>>(json);
        Console.WriteLine(deserialized["2"]);

        var jsonObject = serializer.DeserializeObject(@"{ ""foo"": 1, ""bar"": [10, ""apples""] }");
        var data = jsonObject as Dictionary<string, object>;
        var array = data["bar"] as object[];
        Console.WriteLine(array[1]);
    }
}


Jewels and stones

Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.

Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.

The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.

Note that:
:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered.
:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.
:# The parameters do not need to have exactly the same names.
:# Validating the arguments is unnecessary.

So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3.

This task was inspired by this problem.

Solution:
using System;
using System.Linq;

public class Program
{
    public static void Main() {
        Console.WriteLine(Count("aAAbbbb", "Aa"));
        Console.WriteLine(Count("ZZ", "z"));
    }

    private static int Count(string stones, string jewels) {
        var bag = jewels.ToHashSet();
        return stones.Count(bag.Contains);
    }
}


Julia set

Task
Generate and draw a Julia set.

;Related tasks
*   Mandelbrot Set

Solution:
public struct CalculatedPoint
        {
            public int x;
            public int y;
            public int i;
        }

        static void MultiThreaded()
        {
            const int w = 800;
            const int h = 600;
            const int zoom = 1;
            const int maxiter = 255;
            const int moveX = 0;
            const int moveY = 0;
            const double cX = -0.7;
            const double cY = 0.27015;

            // Precalculate a pallette of 256 colors
            var colors = (from c in Enumerable.Range(0, 256)
                          select Color.FromArgb((c >> 5) * 36, (c >> 3 & 7) * 36, (c & 3) * 85)).ToArray();

            // The "AsParallel" below invokes PLINQ, making evaluation parallel using as many cores as
            // are available.
            var calculatedPoints = Enumerable.Range(0, w * h).AsParallel().Select(xy =>
              {
                  double zx, zy, tmp;
                  int x, y;
                  int i = maxiter;
                  y = xy / w;
                  x = xy % w;
                  zx = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX;
                  zy = 1.0 * (y - h / 2) / (0.5 * zoom * h) + moveY;
                  while (zx * zx + zy * zy < 4 && i > 1)
                  {
                      tmp = zx * zx - zy * zy + cX;
                      zy = 2.0 * zx * zy + cY;
                      zx = tmp;
                      i -= 1;
                  }
                  return new CalculatedPoint { x = x, y = y, i = i };
              });

            // Bitmap is not multi-threaded, so main thread needs to read in the results as they
            // come in and plot the pixels.
            var bitmap = new Bitmap(w, h);
            foreach (CalculatedPoint cp in calculatedPoints)
                bitmap.SetPixel(cp.x, cp.y, colors[cp.i]);
            bitmap.Save("julia-set-multi.png");
        }


Jump anywhere

Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range.

This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions!

* Some languages can ''go to'' any global label in a program.
* Some languages can break multiple function calls, also known as ''unwinding the call stack''.
* Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).

These jumps are not all alike.
A simple ''goto'' never touches the call stack.
A continuation saves the call stack, so you can continue a function call after it ends.

;Task:
Use your language to demonstrate the various types of jumps that it supports.

Because the possibilities vary by language, this task is not specific.
You have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].

Solution:
public int M(int n) {
    int result = 0;
    switch (n) {
        case 1:
            cost += 25;
            break;
        case 2:
            cost += 25;
            goto case 1;
        case 3:
            cost += 50;
            goto case 1;
    }
    return result;
}


Kaprekar numbers

A positive integer is a Kaprekar number if:
* It is   '''1'''     (unity)
* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.

;Example Kaprekar numbers:
* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.
* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....

;Example process:
10000 (1002) splitting from left to right:
* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.
* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.

;Task:
Generate and show all Kaprekar numbers less than 10,000.

;Extra credit:
Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.

;Extra extra credit:
The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers);
if you can, show that Kaprekar numbers exist in other bases too.

For this purpose, do the following:
* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);
* Display each of them in base 10 representation;
* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square.

For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225   d4  a52g  a5 + 2g

;Reference:
* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version

;Related task:
*   [[Casting out nines]]

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

public class KaprekarNumbers {

    /// <summary>
    /// The entry point of the program, where the program control starts and ends.
    /// </summary>
    public static void Main() {
        int count = 0;

        foreach ( ulong i in _kaprekarGenerator(999999) ) {
            Console.WriteLine(i);
            count++;
        }

        Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count);
    }

    /// <summary>
    /// Generator function which generates the Kaprekar numbers.
    /// </summary>
    /// <returns>The generator.</returns>
    /// <param name="max">The maximum value of the numbers generated.</param>
    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {

        ulong next = 1;

        // 1 is always a Kaprekar number.
        yield return next;

        for ( next = 2; next <= max; next++ ) {

            ulong square = next * next;

            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {
                // Check the square against each power of 10 from 10^1 to 10^19 (highest which can be
                // represented by a ulong)

                // If the power of 10 to be checked against is greater than or equal to the square, stop checking
                if ( square <= check )
                    break;

                // Given a power of 10 as 10^n, the remainder when dividing the square number by that power
                // of 10 is equal to the last n digits of the number (starting from the right) and the
                // quotient gives the remaining digits.
                // If the last n digits are all zeroes, then the remainder will be zero, which is not
                // accepted.

                ulong r = square % check;
                ulong q = (square - r) / check;

                if ( r != 0 && q + r == next ) {
                    yield return next;
                    break;
                }
            }

        }

    }

}


Kernighans large earthquake problem

Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.

;Problem:
You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.

Example lines from the file would be lines like:
8/27/1883    Krakatoa            8.8
5/18/1980    MountStHelens       7.6
3/13/2009    CostaRica           5.1

;Task:
* Create a program or script invocation to find all the events with magnitude greater than 6
* Assuming an appropriate name e.g. "data.txt" for the file:
:# Either: Show how your program is invoked to process a data file of that name.
:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).

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

public class Program
{
    static void Main() {
        foreach (var earthquake in LargeEarthquakes("data.txt", 6))
            Console.WriteLine(string.Join(" ", earthquake));
    }

    static IEnumerable<string[]> LargeEarthquakes(string filename, double limit) =>
        from line in File.ReadLines(filename)
        let parts = line.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries)
        where double.Parse(parts[2]) > limit
        select parts;

}


Keyboard input/Obtain a Y or N response

Obtain a valid   '''Y'''   or   '''N'''   response from the [[input device::keyboard]].

The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   '''Y'''   or   '''N'''   key-press from being evaluated.

The response should be obtained as soon as   '''Y'''   or   '''N'''   are pressed, and there should be no need to press an   enter   key.

Solution:
using System;

namespace Y_or_N
{
    class Program
    {
        static void Main()
        {
            bool response = GetYorN();
        }

        static bool GetYorN()
        {
            ConsoleKey response; // Creates a variable to hold the user's response.

            do
            {
                while (Console.KeyAvailable) // Flushes the input queue.
                    Console.ReadKey();

                Console.Write("Y or N? "); // Asks the user to answer with 'Y' or 'N'.
                response = Console.ReadKey().Key; // Gets the user's response.
                Console.WriteLine(); // Breaks the line.
            } while (response != ConsoleKey.Y && response != ConsoleKey.N); // If the user did not respond with a 'Y' or an 'N', repeat the loop.

             /*
              * Return true if the user responded with 'Y', otherwise false.
              *
              * We know the response was either 'Y' or 'N', so we can assume
              * the response is 'N' if it is not 'Y'.
              */
            return response == ConsoleKey.Y;
        }
    }
}


Knight's tour

Task
Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square.   Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position.

Input and output may be textual or graphical, according to the conventions of the programming environment.  If textual, squares should be indicated in algebraic notation.  The output should indicate the order in which the knight visits the squares, starting with the initial position.  The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.

Input: starting square

Output: move sequence

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

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

namespace prog
{
	class MainClass
	{
		const int N = 8;

		readonly static int[,] moves = { {+1,-2},{+2,-1},{+2,+1},{+1,+2},
			                         {-1,+2},{-2,+1},{-2,-1},{-1,-2} };
		struct ListMoves
		{
			public int x, y;
			public ListMoves( int _x, int _y ) { x = _x; y = _y; }
		}

		public static void Main (string[] args)
		{
			int[,] board = new int[N,N];
			board.Initialize();

			int x = 0,						// starting position
			    y = 0;

			List<ListMoves> list = new List<ListMoves>(N*N);
			list.Add( new ListMoves(x,y) );

			do
			{
				if ( Move_Possible( board, x, y ) )
				{
					int move = board[x,y];
					board[x,y]++;
					x += moves[move,0];
					y += moves[move,1];
					list.Add( new ListMoves(x,y) );
				}
				else
				{
					if ( board[x,y] >= 8 )
					{
						board[x,y] = 0;
						list.RemoveAt(list.Count-1);
						if ( list.Count == 0 )
						{
							Console.WriteLine( "No solution found." );
							return;
						}
						x = list[list.Count-1].x;
						y = list[list.Count-1].y;
					}
					board[x,y]++;
				}
			}
			while( list.Count < N*N );

			int last_x = list[0].x,
			    last_y = list[0].y;
			string letters = "ABCDEFGH";
			for( int i=1; i<list.Count; i++ )
			{
				Console.WriteLine( string.Format("{0,2}:  ", i) + letters[last_x] + (last_y+1) + " - " + letters[list[i].x] + (list[i].y+1) );

				last_x = list[i].x;
				last_y = list[i].y;
			}
		}

		static bool Move_Possible( int[,] board, int cur_x, int cur_y )
		{
			if ( board[cur_x,cur_y] >= 8 )
				return false;

			int new_x = cur_x + moves[board[cur_x,cur_y],0],
			    new_y = cur_y + moves[board[cur_x,cur_y],1];

			if ( new_x >= 0 && new_x < N && new_y >= 0 && new_y < N && board[new_x,new_y] == 0 )
				return true;

			return false;
		}
	}
}


Kolakoski sequence

The natural numbers, (excluding zero); with the property that:
: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.

;Example:
This is ''not'' a Kolakoski sequence:
1,1,2,2,2,1,2,2,1,2,...
Its sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:

: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...

The above gives the RLE of:
2, 3, 1, 2, 1, ...

The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.

;Creating a Kolakoski sequence:

Lets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....

# We start the sequence s with the first item from the cycle c: 1
# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate.
We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.

We started s with 1 and therefore s[k] states that it should appear only the 1 time.

Increment k
Get the next item from c and append it to the end of sequence s. s will then become: 1, 2
k was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2
Increment k
Append the next item from the cycle to the list: 1, 2,2, 1
k is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1
increment k

...

'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.

;Task:
# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.
# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence  to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.
# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).
# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 20 members of the sequence generated from (2, 1)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)
# Check the sequence againt its RLE.
(There are rules on generating Kolakoski sequences from this method that are broken by the last example)

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

namespace KolakoskiSequence {
    class Crutch {
        public readonly int len;
        public int[] s;
        public int i;

        public Crutch(int len) {
            this.len = len;
            s = new int[len];
            i = 0;
        }

        public void Repeat(int count) {
            for (int j = 0; j < count; j++) {
                if (++i == len) return;
                s[i] = s[i - 1];
            }
        }
    }

    static class Extension {
        public static int NextInCycle(this int[] self, int index) {
            return self[index % self.Length];
        }

        public static int[] Kolakoski(this int[] self, int len) {
            Crutch c = new Crutch(len);

            int k = 0;
            while (c.i < len) {
                c.s[c.i] = self.NextInCycle(k);
                if (c.s[k] > 1) {
                    c.Repeat(c.s[k] - 1);
                }
                if (++c.i == len) return c.s;
                k++;
            }
            return c.s;
        }

        public static bool PossibleKolakoski(this int[] self) {
            int[] rle = new int[self.Length];
            int prev = self[0];
            int count = 1;
            int pos = 0;
            for (int i = 1; i < self.Length; i++) {
                if (self[i] == prev) {
                    count++;
                }
                else {
                    rle[pos++] = count;
                    count = 1;
                    prev = self[i];
                }
            }
            // no point adding final 'count' to rle as we're not going to compare it anyway
            for (int i = 0; i < pos; i++) {
                if (rle[i] != self[i]) {
                    return false;
                }
            }
            return true;
        }

        public static string AsString(this int[] self) {
            StringBuilder sb = new StringBuilder("[");
            int count = 0;
            foreach (var item in self) {
                if (count > 0) {
                    sb.Append(", ");
                }
                sb.Append(item);
                count++;
            }
            return sb.Append("]").ToString();
        }
    }

    class Program {
        static void Main(string[] args) {
            int[][] ias = {
                new int[]{1, 2},
                new int[]{2, 1},
                new int[]{1, 3, 1, 2},
                new int[]{1, 3, 2, 1}
            };
            int[] lens = { 20, 20, 30, 30 };

            for (int i = 0; i < ias.Length; i++) {
                int len = lens[i];
                int[] kol = ias[i].Kolakoski(len);

                Console.WriteLine("First {0} members of the sequence by {1}: ", len, ias[i].AsString());
                Console.WriteLine(kol.AsString());
                Console.WriteLine("Possible Kolakoski sequence? {0}", kol.PossibleKolakoski());
                Console.WriteLine();
            }
        }
    }
}


Kosaraju

{{wikipedia|Graph}}

Kosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.

For this task consider the directed graph with these connections:
  0 -> 1
  1 -> 2
  2 -> 0
  3 -> 1,  3 -> 2,  3 -> 4
  4 -> 3,  4 -> 5
  5 -> 2,  5 -> 6
  6 -> 5
  7 -> 4, 7  -> 6, 7 -> 7

And report the kosaraju strongly connected component for each node.

;References:
* The article on Wikipedia.

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

class Node
{
	public enum Colors
	{
		Black, White, Gray
	}

	public Colors color { get; set; }
	public int N { get; }

	public Node(int n)
	{
		N = n;
		color = Colors.White;
	}
}

class Graph
{
	public HashSet<Node> V { get; }
	public Dictionary<Node, HashSet<Node>> Adj { get; }

	/// <summary>
	/// Kosaraju's strongly connected components algorithm
	/// </summary>
	public void Kosaraju()
	{
		var L = new HashSet<Node>();

		Action<Node> Visit = null;
		Visit = (u) =>
		{
			if (u.color == Node.Colors.White)
			{
				u.color = Node.Colors.Gray;

				foreach (var v in Adj[u])
					Visit(v);

				L.Add(u);
			}
		};

		Action<Node, Node> Assign = null;
		Assign = (u, root) =>
		{
			if (u.color != Node.Colors.Black)
			{
				if (u == root)
					Console.Write("SCC: ");

				Console.Write(u.N + " ");
				u.color = Node.Colors.Black;

				foreach (var v in Adj[u])
					Assign(v, root);

				if (u == root)
					Console.WriteLine();
			}
		};

		foreach (var u in V)
			Visit(u);

		foreach (var u in L)
			Assign(u, u);
	}
}


Lah numbers

Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.

Unsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets.

Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.

Lah numbers obey the identities and relations:
   L(n, 0), L(0, k) = 0   # for n, k > 0
   L(n, n) = 1
   L(n, 1) = n!
   L(n, k) =           ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)!      # For unsigned Lah numbers
      ''or''
   L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)!      # For   signed Lah numbers

;Task:
:* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.

:* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n).

:* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''.

;See also:

:* '''Wikipedia - Lah number'''
:* '''OEIS:A105278 - Unsigned Lah numbers'''
:* '''OEIS:A008297 - Signed Lah numbers'''

;Related Tasks:

:* '''Stirling numbers of the first kind'''
:* '''Stirling numbers of the second kind'''
:* '''Bell numbers'''

Solution:
using System;
using System.Linq;
using System.Numerics;

namespace LahNumbers {
    class Program {
        static BigInteger Factorial(BigInteger n) {
            if (n == 0) return 1;
            BigInteger res = 1;
            while (n > 0) {
                res *= n--;
            }
            return res;
        }

        static BigInteger Lah(BigInteger n, BigInteger k) {
            if (k == 1) return Factorial(n);
            if (k == n) return 1;
            if (k > n) return 0;
            if (k < 1 || n < 1) return 0;
            return (Factorial(n) * Factorial(n - 1)) / (Factorial(k) * Factorial(k - 1)) / Factorial(n - k);
        }

        static void Main() {
            Console.WriteLine("Unsigned Lah numbers: L(n, k):");
            Console.Write("n/k ");
            foreach (var i in Enumerable.Range(0, 13)) {
                Console.Write("{0,10} ", i);
            }
            Console.WriteLine();
            foreach (var row in Enumerable.Range(0, 13)) {
                Console.Write("{0,-3}", row);
                foreach (var i in Enumerable.Range(0, row + 1)) {
                    var l = Lah(row, i);
                    Console.Write("{0,11}", l);
                }
                Console.WriteLine();
            }
            Console.WriteLine("\nMaximum value from the L(100, *) row:");
            var maxVal = Enumerable.Range(0, 100).Select(a => Lah(100, a)).Max();
            Console.WriteLine(maxVal);
        }
    }
}


Largest int from concatenated ints

Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.

Use the following two sets of integers as tests   and   show your program output here.

:::::*   {1, 34, 3, 98, 9, 76, 45, 4}
:::::*   {54, 546, 548, 60}

;Possible algorithms:
# A solution could be found by trying all combinations and return the best.
# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.
# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.

;See also:
*   Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?
*   Constructing the largest number possible by rearranging a list

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

class Program
{
    static void Main(string[] args)
    {
        var source1 = new int[] { 1, 34, 3, 98, 9, 76, 45, 4 };
        var source2 = new int[] { 54, 546, 548, 60 };

        var largest1 = LargestPossibleSequence(source1);
        var largest2 = LargestPossibleSequence(source2);

        Console.WriteLine("The largest possible integer from set 1 is: {0}", largest1);
        Console.WriteLine("The largest possible integer from set 2 is: {0}", largest2);
    }

    static long LargestPossibleSequence(int[] ints)
    {
        return long.Parse(string.Join("", ints.OrderBy(i => i, new IntConcatenationComparer()).Reverse()));
    }
}

class IntConcatenationComparer : IComparer<int>
{
    public int Compare(int x, int y)
    {
        var xy = int.Parse(x.ToString() + y.ToString());
        var yx = int.Parse(y.ToString() + x.ToString());

        return xy - yx;
    }
}


Largest number divisible by its digits

Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits.

These numbers are also known as   '''Lynch-Bell numbers''',   numbers   '''n'''   such that the
(base ten) digits are all different (and do not include zero)   and   '''n'''   is divisible by each of its individual digits.

;Example:
'''135'''   is evenly divisible by   '''1''',   '''3''',   and   '''5'''.

Note that the digit zero (0) can not be in the number as integer division by zero is undefined.

The digits must all be unique so a base ten number will have at most '''9''' digits.

Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)

;Stretch goal:
Do the same thing for hexadecimal.

;Related tasks:
:*   gapful numbers.
:*   palindromic gapful numbers.

;Also see:
:*   The OEIS sequence:   A115569: Lynch-Bell numbers.

Solution:
using System;

class Program {
    static int gcd(int a, int b) { return b > 0 ? gcd(b, a % b) : a; }

    // returns least common multiple of digits of x in base b
    static int lcmd(long x, int b) {
      int r = (int)(x % b), a; x /= b; while (x > 0) {
        r = (r * (a = (int)(x % b))) / gcd(r, a); x /= b; } return r; }

    static void Main(string[] args) {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        long mx = 987654321; // all digits except zero
             mx = 98764321; // omitting 5 because even numbers are lost
             mx /= 10;     // 7 digs because 8 digs won't divide by 3
        long skip = lcmd(mx, 10), i; bool nDup;
        for (i = mx - mx % skip; ; i -= skip) {
            var s = i.ToString().ToCharArray(); Array.Sort(s);
            if (s[0] == '0') continue; // no zeros
            nDup = true; // checking for duplicate digits or digit five
            for (int j = 0, k = 1; k < s.Length; j = k++)
                if (s[j] == s[k] || s[k] == '5') { nDup = false; break; }
            if (nDup) break; } sw.Stop(); // found it
        Console.Write("base 10 = {0} in {1} μs\n", i,
          1000 * sw.Elapsed.TotalMilliseconds);
        sw.Restart();
        mx = 0xfedcba987654321;    // all 15 digits used, no zero
        skip = lcmd(mx >> 4, 16); // digit one implied, so omit it
        for (i = mx - mx % skip; ; i -= skip) {
            var s = i.ToString("x").ToCharArray(); Array.Sort(s);
            if (s[0] == '0') continue; // no zeros
            nDup = true; // checking for duplicate digits
            for (int j = 0, k = 1; k < s.Length; j = k++)
                if (s[j] == s[k]) { nDup = false; break; }
            if (nDup) break; } sw.Stop(); // found it
        Console.Write("base 16 = {0} in {1} ms", i.ToString("x"),
          sw.Elapsed.TotalMilliseconds); } }


Last Friday of each month

Write a program or a script that returns the date of the last Fridays of each month of a given year.

The year may be given through any simple input method in your language (command line, std in, etc).

Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28

;Related tasks
* [[Five weekends]]
* [[Day of the week]]
* [[Find the last Sunday of each month]]

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

namespace RosettaCode.LastFridaysOfYear
{
    internal static class Program
    {
        private static IEnumerable<DateTime> LastFridaysOfYear(int year)
        {
            for (var month = 1; month <= 12; month++)
            {
                var date = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
                while (date.DayOfWeek != DayOfWeek.Friday)
                {
                    date = date.AddDays(-1);
                }
                yield return date;
            }
        }

        private static void Main(string[] arguments)
        {
            int year;
            var argument = arguments.FirstOrDefault();
            if (string.IsNullOrEmpty(argument) || !int.TryParse(argument, out year))
            {
                year = DateTime.Today.Year;
            }

            foreach (var date in LastFridaysOfYear(year))
            {
                Console.WriteLine(date.ToString("d", CultureInfo.InvariantCulture));
            }
        }
    }
}


Last letter-first letter

A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the game.

For example, with   "animals"   as the category,

Child 1: dog
Child 2: goldfish
Child 1: hippopotamus
Child 2: snake
...

;Task:
Take the following selection of 70 English Pokemon names   (extracted from   Wikipedia's list of Pokemon)   and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name.

No Pokemon name is to be repeated.

audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask

Extra brownie points for dealing with the full list of   646   names.

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string pokemon_names = @"audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask";

            string[] pokemon = pokemon_names.Split(new char[]{' ','\n'});
            List<string> chain = new List<string>(pokemon.Length);

            for (int i = 0; i < pokemon.Length; i++)
            {
                swap(ref pokemon[0], ref pokemon[i]);
                Search( pokemon, chain, 1 );
                swap(ref pokemon[0], ref pokemon[i]);
            }

            foreach (string s in chain)
                Console.WriteLine(s);

            Console.ReadKey();
        }

        static void Search(string[] pokemon, List<string> longest_chain, int len )
        {
            if (len > longest_chain.Count)
            {
                longest_chain.Clear();
                for (int i = 0; i < len; i++)
                    longest_chain.Add(pokemon[i]);
            }

            char lastchar = pokemon[len - 1][pokemon[len-1].Length - 1];
            for (int i = len; i < pokemon.Length; i++)
            {
                if (pokemon[i][0] == lastchar)
                {
                    swap(ref pokemon[i], ref pokemon[len]);
                    Search(pokemon, longest_chain, len + 1);
                    swap(ref pokemon[i], ref pokemon[len]);
                }
            }
        }

        static void swap(ref string s1, ref string s2)
        {
            string tmp = s1;
            s1 = s2;
            s2 = tmp;
        }
    }
}


Latin Squares in reduced form

A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained.

For a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row.

Demonstrate by:
* displaying the four reduced Latin Squares of order 4.
* for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.

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

namespace LatinSquares {
    using matrix = List<List<int>>;

    class Program {
        static void Swap<T>(ref T a, ref T b) {
            var t = a;
            a = b;
            b = t;
        }

        static matrix DList(int n, int start) {
            start--; // use 0 basing
            var a = Enumerable.Range(0, n).ToArray();
            a[start] = a[0];
            a[0] = start;
            Array.Sort(a, 1, a.Length - 1);
            var first = a[1];
            // recursive closure permutes a[1:]
            matrix r = new matrix();
            void recurse(int last) {
                if (last == first) {
                    // bottom of recursion. you get here once for each permutation.
                    // test if permutation is deranged.
                    for (int j = 1; j < a.Length; j++) {
                        var v = a[j];
                        if (j == v) {
                            return; //no, ignore it
                        }
                    }
                    // yes, save a copy with 1 based indexing
                    var b = a.Select(v => v + 1).ToArray();
                    r.Add(b.ToList());
                    return;
                }
                for (int i = last; i >= 1; i--) {
                    Swap(ref a[i], ref a[last]);
                    recurse(last - 1);
                    Swap(ref a[i], ref a[last]);
                }
            }
            recurse(n - 1);
            return r;
        }

        static ulong ReducedLatinSquares(int n, bool echo) {
            if (n <= 0) {
                if (echo) {
                    Console.WriteLine("[]\n");
                }
                return 0;
            } else if (n == 1) {
                if (echo) {
                    Console.WriteLine("[1]\n");
                }
                return 1;
            }

            matrix rlatin = new matrix();
            for (int i = 0; i < n; i++) {
                rlatin.Add(new List<int>());
                for (int j = 0; j < n; j++) {
                    rlatin[i].Add(0);
                }
            }
            // first row
            for (int j = 0; j < n; j++) {
                rlatin[0][j] = j + 1;
            }

            ulong count = 0;
            void recurse(int i) {
                var rows = DList(n, i);

                for (int r = 0; r < rows.Count; r++) {
                    rlatin[i - 1] = rows[r];
                    for (int k = 0; k < i - 1; k++) {
                        for (int j = 1; j < n; j++) {
                            if (rlatin[k][j] == rlatin[i - 1][j]) {
                                if (r < rows.Count - 1) {
                                    goto outer;
                                }
                                if (i > 2) {
                                    return;
                                }
                            }
                        }
                    }
                    if (i < n) {
                        recurse(i + 1);
                    } else {
                        count++;
                        if (echo) {
                            PrintSquare(rlatin, n);
                        }
                    }
                outer: { }
                }
            }

            //remaing rows
            recurse(2);
            return count;
        }

        static void PrintSquare(matrix latin, int n) {
            foreach (var row in latin) {
                var it = row.GetEnumerator();
                Console.Write("[");
                if (it.MoveNext()) {
                    Console.Write(it.Current);
                }
                while (it.MoveNext()) {
                    Console.Write(", {0}", it.Current);
                }
                Console.WriteLine("]");
            }
            Console.WriteLine();
        }

        static ulong Factorial(ulong n) {
            if (n <= 0) {
                return 1;
            }
            ulong prod = 1;
            for (ulong i = 2; i < n + 1; i++) {
                prod *= i;
            }
            return prod;
        }

        static void Main() {
            Console.WriteLine("The four reduced latin squares of order 4 are:\n");
            ReducedLatinSquares(4, true);

            Console.WriteLine("The size of the set of reduced latin squares for the following orders");
            Console.WriteLine("and hence the total number of latin squares of these orders are:\n");
            for (int n = 1; n < 7; n++) {
                ulong nu = (ulong)n;

                var size = ReducedLatinSquares(n, false);
                var f = Factorial(nu - 1);
                f *= f * nu * size;
                Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f);
            }
        }
    }
}


Law of cosines - triples

The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
           A2 + B2 - 2ABcos(g) = C2

;Specific angles:
For an angle of of   '''90o'''   this becomes the more familiar "Pythagoras equation":
           A2 + B2  =  C2

For an angle of   '''60o'''   this becomes the less familiar  equation:
           A2 + B2 - AB  =  C2

And finally for an angle of   '''120o'''   this becomes the equation:
           A2 + B2 + AB  =  C2

;Task:
*   Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.
*   Restrain all sides to the integers   '''1..13'''   inclusive.
*   Show how many results there are for each of the three angles mentioned above.
*   Display results on this page.

Note: Triangles with the same length sides but different order are to be treated as the same.

;Optional Extra credit:
* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.

;Related Task
* [[Pythagorean triples]]

;See also:
* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video

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

public static class LawOfCosinesTriples
{
    public static void Main2() {
        PrintTriples(60, 13);
        PrintTriples(90, 13);
        PrintTriples(120, 13);
        PrintTriples(60, 10_000, true, false);
    }

    private static void PrintTriples(int degrees, int maxSideLength, bool notAllTheSameLength = false, bool print = true) {
        string s = $"{degrees} degree triangles in range 1..{maxSideLength}";
        if (notAllTheSameLength) s += " where not all sides are the same";
        Console.WriteLine(s);
        int count = 0;
        var triples = FindTriples(degrees, maxSideLength);
        if (notAllTheSameLength) triples = triples.Where(NotAllTheSameLength);
        foreach (var triple in triples) {
            count++;
            if (print) Console.WriteLine(triple);
        }
        Console.WriteLine($"{count} solutions");
    }

    private static IEnumerable<(int a, int b, int c)> FindTriples(int degrees, int maxSideLength) {
        double radians = degrees * Math.PI / 180;
        int coefficient = (int)Math.Round(Math.Cos(radians) * -2, MidpointRounding.AwayFromZero);
        int maxSideLengthSquared = maxSideLength * maxSideLength;
        return
            from a in Range(1, maxSideLength)
            from b in Range(1, a)
            let cc = a * a + b * b + a * b * coefficient
            where cc <= maxSideLengthSquared
            let c = (int)Math.Sqrt(cc)
            where c * c == cc
            select (a, b, c);
    }

    private static bool NotAllTheSameLength((int a, int b, int c) triple) => triple.a != triple.b || triple.a != triple.c;
}


Least common multiple

Compute the   least common multiple   (LCM)   of two integers.

Given   ''m''   and   ''n'',   the least common multiple is the smallest positive integer that has both   ''m''   and   ''n''   as factors.

;Example:
The least common multiple of   '''12'''   and   '''18'''   is   '''36''',       because:
:*   '''12'''   is a factor     ('''12''' x '''3''' = '''36'''),     and
:*   '''18'''   is a factor     ('''18''' x '''2''' = '''36'''),     and
:*   there is no positive integer less than   '''36'''   that has both factors.

As a special case,   if either   ''m''   or   ''n''   is zero,   then the least common multiple is zero.

One way to calculate the least common multiple is to iterate all the multiples of   ''m'',   until you find one that is also a multiple of   ''n''.

If you already have   ''gcd''   for [[greatest common divisor]],   then this formula calculates   ''lcm''.

:::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)}

One can also find   ''lcm''   by merging the [[prime decomposition]]s of both   ''m''   and   ''n''.

;Related task
:*   greatest common divisor.

;See also:
*   MathWorld entry:   Least Common Multiple.
*   Wikipedia entry:   Least common multiple.

Solution:
Using System;
class Program
{
    static int gcd(int m, int n)
    {
        return n == 0 ? Math.Abs(m) : gcd(n, n % m);
    }
    static int lcm(int m, int n)
    {
        return Math.Abs(m * n) / gcd(m, n);
    }
    static void Main()
    {
        Console.WriteLine("lcm(12,18)=" + lcm(12,18));
    }
}


Left factorials

'''Left factorials''',   !n,   may refer to either   ''subfactorials''   or to   ''factorial sums'';
the same notation can be confusingly seen being used for the two different definitions.

Sometimes,   ''subfactorials''   (also known as ''derangements'')   may use any of the notations:
:::::::*     !''n''`
:::::::*     !''n''
:::::::*     ''n''!

(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)

This Rosetta Code task will be using this formula   (''factorial sums'')   for   '''left factorial''':

:::::    !n = \sum_{k=0}^{n-1} k!

:::: where

:::::   !0 = 0

;Task
Display the left factorials for:
*   zero      through        ten     (inclusive)
*   20   through   110          (inclusive)   by tens

Display the length (in decimal digits) of the left factorials for:
*   1,000   through   10,000   (inclusive), by thousands.

;Also see:
*   The OEIS entry: A003422 left factorials
*   The MathWorld entry: left factorial
*   The MathWorld entry: factorial sums
*   The MathWorld entry: subfactorial

;Related task:
*   permutations/derangements (subfactorials)

Solution:
using System;
using System.Numerics;

namespace LeftFactorial
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i)));
            }

            for (int j = 20; j <= 110; j += 10)
            {
                Console.WriteLine(string.Format("!{0} = {1}", j, LeftFactorial(j)));
            }

            for (int k = 1000; k <= 10000; k += 1000)
            {
                Console.WriteLine(string.Format("!{0} has {1} digits", k, LeftFactorial(k).ToString().Length));
            }

            Console.ReadKey();
        }

        private static BigInteger Factorial(int number)
        {
            BigInteger accumulator = 1;

            for (int factor = 1; factor <= number; factor++)
            {
                accumulator *= factor;
            }

            return accumulator;
        }

        private static BigInteger LeftFactorial(int n)
        {
            BigInteger result = 0;

            for (int i = 0; i < n; i++)
            {
                result += Factorial(i);
            }

            return result;
        }
    }
}


Levenshtein distance

{{Wikipedia}}

In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.

;Example:
The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
::#   '''k'''itten    '''s'''itten       (substitution of 'k' with 's')
::#   sitt'''e'''n    sitt'''i'''n       (substitution of 'e' with 'i')
::#   sittin          sittin'''g'''      (insert 'g' at the end).

''The Levenshtein distance between   "'''rosettacode'''",   "'''raisethysword'''"   is   '''8'''.

''The distance between two strings is same as that when both strings are reversed.''

;Task:
Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between   "kitten"   and   "sitting".

;Related task:
*   [[Longest common subsequence]]

Solution:
using System;

namespace LevenshteinDistance
{
    class Program
    {
        static int LevenshteinDistance(string s, string t)
        {
            int n = s.Length;
            int m = t.Length;
            int[,] d = new int[n + 1, m + 1];

	    if (n == 0)
	    {
		return m;
	    }

	    if (m == 0)
	    {
		return n;
	    }

            for (int i = 0; i <= n; i++)
                d[i, 0] = i;
            for (int j = 0; j <= m; j++)
                d[0, j] = j;

            for (int j = 1; j <= m; j++)
                for (int i = 1; i <= n; i++)
                    if (s[i - 1] == t[j - 1])
                        d[i, j] = d[i - 1, j - 1];  //no operation
                    else
                        d[i, j] = Math.Min(Math.Min(
                            d[i - 1, j] + 1,    //a deletion
                            d[i, j - 1] + 1),   //an insertion
                            d[i - 1, j - 1] + 1 //a substitution
                            );
            return d[n, m];
        }

        static void Main(string[] args)
        {
            if (args.Length == 2)
                Console.WriteLine("{0} -> {1} = {2}",
                    args[0], args[1], LevenshteinDistance(args[0], args[1]));
            else
                Console.WriteLine("Usage:-\n\nLevenshteinDistance <string1> <string2>");
        }
    }
}


Long year

Most years have 52 weeks, some have 53, according to ISO8601.

;Task:
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.

Solution:
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;

public static class Program
{
    public static void Main()
    {
        WriteLine("Long years in the 21st century:");
        WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));
    }

    public static IEnumerable<int> To(this int start, int end) {
        for (int i = start; i < end; i++) yield return i;
    }

}


Longest common subsequence

'''Introduction'''

Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.

The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.

Let ''A''  ''A''[0]... ''A''[m - 1] and ''B''  ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.

An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.

The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j)  '''M'''.

Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2.  We define (>=) similarly.

We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds.  If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.

Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2.  We define (>) similarly.

A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2.  An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.

A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].

Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''.  Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.

According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed.  Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.

'''Background'''

Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth.  This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.

The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n'').  However, this approach requires O(''m*n'') time even in the best case.

This quadratic time dependency may become prohibitive, given very long input strings.  Thus, heuristics are often favored over optimal Dynamic Programming solutions.

In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS.  In this case the number of matches reduces to linear, O(''n'') growth.

A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m'').  Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').

'''Note'''

[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').

'''Legend'''

 A, B are input strings of lengths m, n respectively
 p is the length of the LCS
 M is the set of matches (i, j) such that A[i] = B[j]
 r is the magnitude of M
 s is the magnitude of the alphabet S of distinct symbols in A + B

'''References'''

[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]

[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]

[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]

[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41

[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]

[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, ''pp.'' 275-281]

'''Examples'''

The sequences "1234" and "1224533324" have an LCS of "1234":
 '''1234'''
 '''12'''245'''3'''332'''4'''

For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
 '''t'''hi'''si'''sa'''test'''
 '''t'''e'''s'''t'''i'''ng123'''test'''ing

In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.

For more information on this problem please see Wikipedia.

Solution:
using System;

namespace LCS
{
    class Program
    {
        static void Main(string[] args)
        {
            string word1 = "thisisatest";
            string word2 = "testing123testing";

            Console.WriteLine(lcsBack(word1, word2));
            Console.ReadKey();
        }

        public static string lcsBack(string a, string b)
        {
            string aSub = a.Substring(0, (a.Length - 1 < 0) ? 0 : a.Length - 1);
            string bSub = b.Substring(0, (b.Length - 1 < 0) ? 0 : b.Length - 1);

            if (a.Length == 0 || b.Length == 0)
                return "";
            else if (a[a.Length - 1] == b[b.Length - 1])
                return lcsBack(aSub, bSub) + a[a.Length - 1];
            else
            {
                string x = lcsBack(a, bSub);
                string y = lcsBack(aSub, b);
                return (x.Length > y.Length) ? x : y;
            }
        }
    }
}


Longest common substring

Write a function that returns the longest common substring of two strings.

Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".

Note that substrings are consecutive characters within a string.   This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.

Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test".

;References:
*Generalize Suffix Tree
*[[Ukkonen's Suffix Tree Construction]]

Solution:
using System;

namespace LongestCommonSubstring
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(lcs("thisisatest", "testing123testing"));
            Console.ReadKey(true);
        }

        public static string lcs(string a, string b)
        {
            var lengths = new int[a.Length, b.Length];
            int greatestLength = 0;
            string output = "";
            for (int i = 0; i < a.Length; i++)
            {
                for (int j = 0; j < b.Length; j++)
                {
                    if (a[i] == b[j])
                    {
                        lengths[i, j] = i == 0 || j == 0 ? 1 : lengths[i - 1, j - 1] + 1;
                        if (lengths[i, j] > greatestLength)
                        {
                            greatestLength = lengths[i, j];
                            output = a.Substring(i - greatestLength + 1, greatestLength);
                        }
                    }
                    else
                    {
                        lengths[i, j] = 0;
                    }
                }
            }
            return output;
        }
    }
}


Longest common substring

Solution:
//C# program tests the LCSUBSTR (Longest Common Substring) subroutine.
using System;
namespace LongestCommonSubstring
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = args.Length >= 1 ? args[0] : "";                                             /*get two arguments (strings).   */
            string b = args.Length == 2 ? args[1] : "";
            if (a == "") a = "thisisatest";                                                         /*use this string for a default. */
            if (b == "") b = "testing123testing";                                                   /* "    "     "    "  "    "     */
            Console.WriteLine("string A = {0}", a);                                                 /*echo string  A  to screen.     */
            Console.WriteLine("string B = {0}", b);                                                 /*echo string  B  to screen.     */
            Console.WriteLine("LCsubstr = {0}", LCsubstr(a, b));                                    /*tell Longest Common Substring. */
            Console.ReadKey(true);
        }                                                                                /*stick a fork in it, we're done.*/

        /*─────────────────────────────────LCSUBSTR subroutine─────────────────────────────────*/
        public static string LCsubstr(string x, string y)                                           /*Longest Common Substring.      */
        {
            string output = "";
            int lenx = x.Length;                                                                    /*shortcut for using the X length*/
            for (int j = 0; j < lenx; j++)                                                          /*step through start points in X.*/
            {
                for (int k = lenx - j; k > -1; k--)                                                 /*step through string lengths.   */
                {
                    string common = x.Substring(j, k);                                              /*extract a common substring.    */
                    if (y.IndexOf(common) > -1 && common.Length > output.Length) output = common;   /*longest?*/
                }                                                                                /*k*/
            }                                                                                /*j*/
            return output;                                                                          /*$  is "" if no common string.  */
        }
    }
}


Longest common substring

Solution:
//C# program tests the LCS (Longest Common Substring) subroutine.
using System;
namespace LongestCommonSubstring
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = args.Length >= 1 ? args[0] : "";                                             /*get two arguments (strings).   */
            string b = args.Length == 2 ? args[1] : "";
            if (a == "") a = "thisisatest";                                                         /*use this string for a default. */
            if (b == "") b = "testing123testing";                                                   /* "    "     "    "  "    "     */
            Console.WriteLine("string A = {0}", a);                                                 /*echo string  A  to screen.     */
            Console.WriteLine("string B = {0}", b);                                                 /*echo string  B  to screen.     */
            Console.WriteLine("LCS = {0}", lcs(a, b));                                              /*tell Longest Common Substring. */
            Console.ReadKey(true);
        }                                                                                /*stick a fork in it, we're done.*/

        /*─────────────────────────────────LCS subroutine─────────────────────────────────*/
        private static string lcs(string a, string b)
        {
           if(b.Length<a.Length){ string t=a; a=b; b=t; }
           for (int n = a.Length; n > 0; n--)
           {
              for (int m = a.Length-n; m <= a.Length-n; m++)
              {
                  string s=a.Substring(m,n);
                  if(b.Contains(s)) return(s);
              }
           }
           return "";
        }
    }


Longest increasing subsequence

Calculate and show here a longest increasing subsequence of the list:
:\{3, 2, 6, 4, 5, 1\}
And of the list:
:\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\}

Note that a list may have more than one subsequence that is of the maximum length.

;Ref:
# Dynamic Programming #1: Longest Increasing Subsequence on YouTube
# An efficient solution can be based on Patience sorting.

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

public static class LIS
{
    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>
        values == null ? throw new ArgumentNullException() :
            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();

    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {
        if (index == values.Count) return current;
        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)
            return FindRecImpl(values, current, index + 1, comparer);
        return Max(
            FindRecImpl(values, current, index + 1, comparer),
            FindRecImpl(values, current + values[index], index + 1, comparer)
        );
    }

    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;

    class Sequence<T> : IEnumerable<T>
    {
        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);

        public Sequence(T value, Sequence<T> tail)
        {
            Value = value;
            Tail = tail;
            Length = tail == null ? 0 : tail.Length + 1;
        }

        public T Value { get; }
        public Sequence<T> Tail { get; }
        public int Length { get; }

        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);

        public IEnumerator<T> GetEnumerator()
        {
            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;
        }

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }
}


Longest increasing subsequence

Solution:
public static class LIS
{
    public static T[] Find<T>(IList<T> values, IComparer<T> comparer = null) {
        if (values == null) throw new ArgumentNullException();
        if (comparer == null) comparer = Comparer<T>.Default;
        var pileTops = new List<T>();
        var pileAssignments = new int[values.Count];
        for (int i = 0; i < values.Count; i++) {
            T element = values[i];
            int pile = pileTops.BinarySearch(element, comparer);
            if (pile < 0) pile = ~pile;
            if (pile == pileTops.Count) pileTops.Add(element);
            else pileTops[pile] = element;
            pileAssignments[i] = pile;
        }
        T[] result = new T[pileTops.Count];
        for (int i = pileAssignments.Length - 1, p = pileTops.Count - 1; p >= 0; i--) {
            if (pileAssignments[i] == p) result[p--] = values[i];
        }
        return result;
    }

    public static void Main() {
        Console.WriteLine(string.Join(",", LIS.Find(new [] { 3, 2, 6, 4, 5, 1 })));
        Console.WriteLine(string.Join(",", LIS.Find(new [] { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 })));
    }
}


MAC vendor lookup

Every connected device around the world comes with a unique Media Access Control address, or a   MAC address.

A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.

;Task:
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.

A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result.

Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.

'''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''

Solution:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task<string> LookupMac(string MacAddress)
    {
        var uri = new Uri("http://api.macvendors.com/" + WebUtility.UrlEncode(MacAddress));
        using (var wc = new HttpClient())
            return await wc.GetStringAsync(uri);
    }
    static void Main(string[] args)
    {
        foreach (var mac in new string[] { "88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D" })
            Console.WriteLine(mac + "\t" + LookupMac(mac).Result);
        Console.ReadLine();
    }
}


MD4

Find the MD4 message digest of a string of [[octet]]s.
Use the ASCII encoded string "Rosetta Code" (without quotes).
You may either call an MD4 library, or implement MD4 in your language.

'''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.

RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
static class Md4
{
    public static string Md4Hash(this string input)
    {
        // get padded uints from bytes
        List<byte> bytes = Encoding.ASCII.GetBytes(input).ToList();
        uint bitCount = (uint)(bytes.Count) * 8;
        bytes.Add(128);
        while (bytes.Count % 64 != 56) bytes.Add(0);
        var uints = new List<uint>();
        for (int i = 0; i + 3 < bytes.Count; i += 4)
            uints.Add(bytes[i] | (uint)bytes[i + 1] << 8 | (uint)bytes[i + 2] << 16 | (uint)bytes[i + 3] << 24);
        uints.Add(bitCount);
        uints.Add(0);

        // run rounds
        uint a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476;
        Func<uint, uint, uint> rol = (x, y) => x << (int)y | x >> 32 - (int)y;
        for (int q = 0; q + 15 < uints.Count; q += 16)
        {
            var chunk = uints.GetRange(q, 16);
            uint aa = a, bb = b, cc = c, dd = d;
            Action<Func<uint, uint, uint, uint>, uint[]> round = (f, y) =>
            {
                foreach (uint i in new[] { y[0], y[1], y[2], y[3] })
                {
                    a = rol(a + f(b, c, d) + chunk[(int)(i + y[4])] + y[12], y[8]);
                    d = rol(d + f(a, b, c) + chunk[(int)(i + y[5])] + y[12], y[9]);
                    c = rol(c + f(d, a, b) + chunk[(int)(i + y[6])] + y[12], y[10]);
                    b = rol(b + f(c, d, a) + chunk[(int)(i + y[7])] + y[12], y[11]);
                }
            };
            round((x, y, z) => (x & y) | (~x & z), new uint[] { 0, 4, 8, 12, 0, 1, 2, 3, 3, 7, 11, 19, 0 });
            round((x, y, z) => (x & y) | (x & z) | (y & z), new uint[] { 0, 1, 2, 3, 0, 4, 8, 12, 3, 5, 9, 13, 0x5a827999 });
            round((x, y, z) => x ^ y ^ z, new uint[] { 0, 2, 1, 3, 0, 8, 4, 12, 3, 9, 11, 15, 0x6ed9eba1 });
            a += aa; b += bb; c += cc; d += dd;
        }

        // return hex encoded string
        byte[] outBytes = new[] { a, b, c, d }.SelectMany(BitConverter.GetBytes).ToArray();
        return BitConverter.ToString(outBytes).Replace("-", "").ToLower();
    }
    static void Main() { Console.WriteLine("Rosetta Code".Md4Hash()); }
}


Mad Libs

{{wikipedia}}

Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.

;Task;
Write a program to create a Mad Libs like story.

The program should read an arbitrary multiline story from input.

The story will be terminated with a blank line.

Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.

Stop when there are none left and print the final story.

The input should be an arbitrary story in the form:

 went for a walk in the park.
found a .  decided to take it home.

Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).

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

namespace MadLibs_RosettaCode
{
	class Program
	{
		static void Main(string[] args)
		{
			string madLibs =
@"Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story,
ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name,
a he or she and a noun (<name> gets replaced both times with the same value).";

			StringBuilder sb = new StringBuilder();
			Regex pattern = new Regex(@"\<(.*?)\>");
			string storyLine;
			string replacement;

			Console.WriteLine(madLibs + Environment.NewLine + Environment.NewLine);
			Console.WriteLine("Enter a story: ");

			// Continue to get input while empty line hasn't been entered.
			do
			{
				storyLine = Console.ReadLine();
				sb.Append(storyLine + Environment.NewLine);
			} while (!string.IsNullOrEmpty(storyLine) && !string.IsNullOrWhiteSpace(storyLine));

			// Retrieve only the unique regex matches from the user entered story.
			Match nameMatch = pattern.Matches(sb.ToString()).OfType<Match>().Where(x => x.Value.Equals("<name>")).Select(x => x.Value).Distinct() as Match;
			if(nameMatch != null)
			{
				do
				{
					Console.WriteLine("Enter value for: " + nameMatch.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));
				sb.Replace(nameMatch.Value, replacement);
			}

			foreach (Match match in pattern.Matches(sb.ToString()))
			{
				replacement = string.Empty;
				// Guarantee we get a non-whitespace value for the replacement
				do
				{
					Console.WriteLine("Enter value for: " + match.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));

				int location = sb.ToString().IndexOf(match.Value);
				sb.Remove(location, match.Value.Length).Insert(location, replacement);
			}

			Console.WriteLine(Environment.NewLine + Environment.NewLine + "--[ Here's your story! ]--");
			Console.WriteLine(sb.ToString());
		}
	}
}


Magic 8-ball

Create Magic 8-Ball.

See details at:   Magic 8-Ball.

Solution:
using System;

namespace newProg
{

    class Program
    {
        static void Main(string[] args)
        {
            string[] answers =
            {
                "It is certain.",
                "It is decidedly so.",
                "Without a doubt.",
                "Yes – definitely.",
                "You may rely on it.",
                "As I see it, yes.",
                "Most likely.",
                "Outlook good.",
                "Yes.",
                "Signs point to yes.",
                "Reply hazy, try again.",
                "Ask again later",
                "Better not tell you now.",
                "Cannot predict now.",
                "Concentrate and ask again.",
                "Don't count on it.",
                "My reply is no.",
                "My sources say no.",
                "Outlook not so good.",
                "Very doubtful."
            };

            while (true)
            {
                Random rnd = new Random();
                int result = rnd.Next(0, 19);

                Console.WriteLine("Magic 8 Ball! Ask question and hit a key for the answer!");

                string inp = Console.ReadLine();

                Console.WriteLine(answers[result]);

            }
        }
    }
}


Magic squares of doubly even order

Solution:
using System;

namespace MagicSquareDoublyEven
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 8;
            var result = MagicSquareDoublyEven(n);
            for (int i = 0; i < result.GetLength(0); i++)
            {
                for (int j = 0; j < result.GetLength(1); j++)
                    Console.Write("{0,2} ", result[i, j]);
                Console.WriteLine();
            }
            Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2);
            Console.ReadLine();
        }

        private static int[,] MagicSquareDoublyEven(int n)
        {
            if (n < 4 || n % 4 != 0)
                throw new ArgumentException("base must be a positive "
                        + "multiple of 4");

            // pattern of count-up vs count-down zones
            int bits = 0b1001_0110_0110_1001;
            int size = n * n;
            int mult = n / 4;  // how many multiples of 4

            int[,] result = new int[n, n];

            for (int r = 0, i = 0; r < n; r++)
            {
                for (int c = 0; c < n; c++, i++)
                {
                    int bitPos = c / mult + (r / mult) * 4;
                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
                }
            }
            return result;
        }
    }
}


Map range

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

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

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

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

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

Solution:
using System;
using System.Linq;

public class MapRange
{
    public static void Main() {
        foreach (int i in Enumerable.Range(0, 11))
            Console.WriteLine($"{i} maps to {Map(0, 10, -1, 0, i)}");
    }

    static double Map(double a1, double a2, double b1, double b2, double s) => b1 + (s - a1) * (b2 - b1) / (a2 - a1);
}


Maximum triangle path sum

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

                          55
                        94 48
                       95 30 96
                     77 71 26 67

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

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

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

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

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

This task is derived from the Euler Problem #18.

Solution:
using System;

namespace RosetaCode
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			int[,] list = new int[18,19];
			string input = @"55
	                        94 48
	                       95 30 96
	                     77 71 26 67
	                    97 13 76 38 45
	                  07 36 79 16 37 68
	                 48 07 09 18 70 26 06
	               18 72 79 46 59 79 29 90
	              20 76 87 11 32 07 07 49 18
	            27 83 58 35 71 11 25 57 29 85
	           14 64 36 96 27 11 58 56 92 18 55
	         02 90 03 60 48 49 41 46 33 36 47 23
	        92 50 48 02 36 59 42 79 72 20 82 77 42
	      56 78 38 80 39 75 02 71 66 66 01 03 55 72
	     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
	   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
	  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
	27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93";
			var charArray = input.Split ('\n');

			for (int i=0; i < charArray.Length; i++) {
				var numArr = charArray[i].Trim().Split(' ');

				for (int j = 0; j<numArr.Length; j++)
				{
					int number = Convert.ToInt32 (numArr[j]);
					list [i, j] = number;
				}
			}

			for (int i = 16; i >= 0; i--) {
				for (int j = 0; j < 18; j++) {
					list[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);
				}
			}
			Console.WriteLine (string.Format("Maximum total: {0}", list [0, 0]));
		}
	}
}


McNuggets problem

From Wikipedia:
 The McNuggets version of the coin problem was introduced by Henri Picciotto,
 who included it in his algebra textbook co-authored with Anita Wah. Picciotto
 thought of the application in the 1980s while dining with his son at
 McDonald's, working the problem out on a napkin. A McNugget number is
 the total number of McDonald's Chicken McNuggets in any number of boxes.
 In the United Kingdom, the original boxes (prior to the introduction of
 the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.

;Task:
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''
where ''x'', ''y'' and ''z'' are natural numbers).

Solution:
using System;

public class McNuggets
{
   public static void Main()
   {
      bool[] isMcNuggetNumber = new bool[101];

      for (int x = 0; x <= 100/6; x++)
      {
         for (int y = 0; y <= 100/9; y++)
         {
            for (int z = 0; z <= 100/20; z++)
            {
               int mcNuggetNumber = x*6 + y*9 + z*20;
               if (mcNuggetNumber <= 100)
               {
                  isMcNuggetNumber[mcNuggetNumber] = true;
               }
            }
         }
      }

      for (int mnnCheck = isMcNuggetNumber.Length-1; mnnCheck >= 0; mnnCheck--)
      {
         if (!isMcNuggetNumber[mnnCheck])
         {
            Console.WriteLine("Largest non-McNuggett Number less than 100: " + mnnCheck.ToString());
            break;
         }
      }
   }
}


Metaprogramming

{{omit from|BBC BASIC}}
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.

For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.

Solution: Metaprogramming in C# can be achieved using the [https://msdn.microsoft.com/en-us/library/bb126445.aspx Text Template Transformation Toolkit]. It is a textual preprocessor embedded in Visual Studio (it can also be executed from the command-line, e.g. in build scripts). It is language-agnostic, and therefore can generate code for C#, Visual Basic or other languages. This also means that it has no features which help manipulating the underlying language: it is purely textual, and does '''not''' include a C# parser to transform existing C# files (so you will need to roll your own or use [https://roslyn.codeplex.com/ Roslyn]), and does '''not''' include utilities which would help with combining pieces of code.


Mian-Chowla sequence

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

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

The sequence starts with:

::a1 = 1

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

::ai + aj

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

;The Task:

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

Demonstrating working through the first few terms longhand:

::a1 = 1

::1 + 1 = 2

Speculatively try a2 = 2

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

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

Speculatively try a3 = 3

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

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

Speculatively try a3 = 4

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

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

And so on...

;See also:

:* OEIS:A005282 Mian-Chowla sequence

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

static class Program {
    static int[] MianChowla(int n) {
        int[] mc = new int[n - 1 + 1];
        HashSet<int> sums = new HashSet<int>(), ts = new HashSet<int>();
        int sum; mc[0] = 1; sums.Add(2);
        for (int i = 1; i <= n - 1; i++) {
            for (int j = mc[i - 1] + 1; ; j++) {
                mc[i] = j;
                for (int k = 0; k <= i; k++) {
                    sum = mc[k] + j;
                    if (sums.Contains(sum)) { ts.Clear(); break; }
                    ts.Add(sum);
                }
                if (ts.Count > 0) { sums.UnionWith(ts); break; }
            }
        }
        return mc;
    }

    static void Main(string[] args)
    {
        const int n = 100; Stopwatch sw = new Stopwatch();
        string str = " of the Mian-Chowla sequence are:\n";
        sw.Start(); int[] mc = MianChowla(n); sw.Stop();
        Console.Write("The first 30 terms{1}{2}{0}{0}Terms 91 to 100{1}{3}{0}{0}" +
            "Computation time was {4}ms.{0}", '\n', str, string.Join(" ", mc.Take(30)),
            string.Join(" ", mc.Skip(n - 10)), sw.ElapsedMilliseconds);
    }
}