import std.algorithm, std.array;

alias encode = group;

auto decode(Group!("a == b", string) enc) {
    return enc.map!(t => [t[0]].replicate(t[1])).join;
}

void main() {
    immutable s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWW" ~
                  "WWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
    assert(s.encode.decode.equal(s));
}

import std.stdio, std.array, std.conv;

// Similar to the 'look and say' function.
string encode(in string input) pure nothrow @safe {
    if (input.empty)
        return input;
    char last = input[$ - 1];
    string output;
    int count;

    foreach_reverse (immutable c; input) {
        if (c == last) {
            count++;
        } else {
            output = count.text ~ last ~ output;
            count = 1;
            last = c;
        }
    }

    return count.text ~ last ~ output;
}

string decode(in string input) pure /*@safe*/ {
    string i, result;

    foreach (immutable c; input)
        switch (c) {
            case '0': .. case '9':
                i ~= c;
                break;
            case 'A': .. case 'Z':
                if (i.empty)
                    throw new Exception("Can not repeat a letter " ~
                        "without a number of repetitions");
                result ~= [c].replicate(i.to!int);
                i.length = 0;
                break;
            default:
                throw new Exception("'" ~ c ~ "' is not alphanumeric");
        }

    return result;
}

void main() {
    immutable txt = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWW" ~
                    "WWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
    writeln("Input: ", txt);
    immutable encoded = txt.encode;
    writeln("Encoded: ", encoded);
    assert(txt == encoded.decode);
}

implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated sequences of the same character by storing the length of the sequence. It also provides a function to reverse the compression. The system can handle UTF-encoded strings and uses a Variable-length Quantity module. It also handles digits by escaping them with a '#'.


import std.stdio;

void main() {
    string s = "hello";
    writeln(s ~ " world");
    auto s2 = s ~ " world";
    writeln(s2);
}

Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


import std.stdio, std.uri;

void main() {
    writeln(encodeComponent("http://foo bar/"));
}

http%3A%2F%2Ffoo%20bar%2F

provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, "http://foo bar/" is encoded as "http%3A%2F%2Ffoo%20bar%2F".


import std.stdio, std.algorithm, std.string;

struct Item {
    string name;
    real amount, value;

    @property real valuePerKG() @safe const pure nothrow @nogc {
        return value / amount;
    }

    string toString() const pure /*nothrow*/ @safe {
        return format("%10s %7.2f %7.2f %7.2f",
                      name, amount, value, valuePerKG);
    }
}

real sumBy(string field)(in Item[] items) @safe pure nothrow @nogc {
    return reduce!("a + b." ~ field)(0.0L, items);
}

void main() /*@safe*/ {
    const items = [Item("beef",    3.8, 36.0),
                   Item("pork",    5.4, 43.0),
                   Item("ham",     3.6, 90.0),
                   Item("greaves", 2.4, 45.0),
                   Item("flitch",  4.0, 30.0),
                   Item("brawn",   2.5, 56.0),
                   Item("welt",    3.7, 67.0),
                   Item("salami",  3.0, 95.0),
                   Item("sausage", 5.9, 98.0)]
                  .schwartzSort!(it => -it.valuePerKG)
                  .release;

    immutable(Item)[] chosen;
    real space = 15.0;
    foreach (const item; items)
        if (item.amount < space) {
            chosen ~= item;
            space -= item.amount;
        } else {
            chosen ~= Item(item.name, space, item.valuePerKG * space);
            break;
        }

    writefln("%10s %7s %7s %7s", "ITEM", "AMOUNT", "VALUE", "$/unit");
    writefln("%(%s\n%)", chosen);
    Item("TOTAL", chosen.sumBy!"amount", chosen.sumBy!"value").writeln;
}

determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.


import std.stdio, std.algorithm, std.string, std.exception, std.file;

void main() {
    string[][ubyte[]] an;
    foreach (w; "unixdict.txt".readText.splitLines)
        an[w.dup.representation.sort().release.assumeUnique] ~= w;
    immutable m = an.byValue.map!q{ a.length }.reduce!max;
    writefln("%(%s\n%)", an.byValue.filter!(ws => ws.length == m));
}

find the sets of words from the provided URL that are anagrams of each other, with a focus on the sets that contain the most words. The code has two versions with different runtimes, 0.07 and 0.06 seconds, both producing the same output.


import std.stdio, std.string, std.algorithm, std.array;

auto sierpinskiCarpet(in int n) pure nothrow @safe {
    auto r = ["#"];
    foreach (immutable _; 0 .. n) {
        const p = r.map!q{a ~ a ~ a}.array;
        r = p ~ r.map!q{a ~ a.replace("#", " ") ~ a}.array ~ p;
    }
    return r.join('\n');
}

void main() {
    3.sierpinskiCarpet.writeln;
}

import std.stdio, std.algorithm, std.range, std.functional;

auto nextCarpet(in string[] c) pure nothrow {
    /*immutable*/ const b = c.map!q{a ~ a ~ a}.array;
    return b ~ c.map!q{a ~ a.replace("#", " ") ~ a}.array ~ b;
}

void main() {
    ["#"]
    .recurrence!((a, n) => a[n - 1].nextCarpet)
    .dropExactly(3)
    .front
    .binaryReverseArgs!writefln("%-(%s\n%)");
}

import std.stdio, std.array;

char[][] sierpinskiCarpet(in size_t n) pure nothrow @safe {
    auto mat = uninitializedArray!(typeof(return))(3 ^^ n, 3 ^^ n);

    foreach (immutable r, row; mat) {
        row[] = '#';
        foreach (immutable c, ref cell; row) {
            size_t r2 = r, c2 = c;
            while (r2 && c2) {
                if (r2 % 3 == 1 && c2 % 3 == 1) {
                    cell = ' ';
                    break;
                }
                r2 /= 3;
                c2 /= 3;
            }
        }
    }

    return mat;
}

void main() {
    writefln("%-(%s\n%)", 3.sierpinskiCarpet);
    7.sierpinskiCarpet.length.writeln;
}

generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order, N. The representation uses specific placement of whitespace and non-whitespace characters.


import std.stdio, std.algorithm, std.typecons, std.container, std.array;

auto encode(alias eq, R)(Group!(eq, R) sf) /*pure nothrow @safe*/ {
    auto heap = sf.map!(s => tuple(s[1], [tuple(s[0], "")]))
                .array.heapify!q{b < a};

    while (heap.length > 1) {
        auto lo = heap.front; heap.removeFront;
        auto hi = heap.front; heap.removeFront;
        lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]);
        hi[1].each!((ref pair) => pair[1] = '1' ~ pair[1]);
        heap.insert(tuple(lo[0] + hi[0], lo[1] ~ hi[1]));
    }
    return heap.front[1].schwartzSort!q{ tuple(a[1].length, a[0]) };
}

void main() /*@safe*/ {
    immutable s = "this is an example for huffman encoding"d;
    foreach (const p; s.dup.sort().group.encode)
        writefln("'%s'  %s", p[]);
}

The code generates a Huffman encoding for each character in the given string "this is an example for huffman encoding". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.


Works with: D version 1
Library: DFL
module winapp ;
import dfl.all ;
import std.string ;

class MainForm: Form {
  Label label ;
  Button button ;
  this() {
    width = 240 ;
    with(label = new Label) {
      text = "There have been no clicks yet" ;
      dock = DockStyle.TOP ;
      parent = this ;
    }
    with(button = new Button) {
      dock = DockStyle.BOTTOM ;
      text = "Click Me" ;
      parent = this ;
      click ~= &onClickButton ;
    }
    height = label.height + button.height + 36 ;
  }
  private void onClickButton(Object sender, EventArgs ea) {
    static int count = 0 ;
    label.text = "You had been clicked me " ~ std.string.toString(++count) ~ " times." ;
  }
}

void main() {
    Application.run(new MainForm);
}

Works with: D version 1
Library: Hybrid

import "themes/default.cfg"

new FramedTopLevelWindow main {
	frame.text = "Simple Window";

	new Label label {
		text = "There have been no clicks yet";
	}

	new Button button {
		text = "Click me";
		size = 201 20;
	}
}

module SimpleWindow;
import tango.text.convert.Integer;
import tango.core.Thread; // For Thread.yield

import xf.hybrid.Hybrid; //For widgets and general API
import xf.hybrid.backend.GL; // For OpenGL Renderer

void main() {
	//load config file
	scope cfg = loadHybridConfig(`./SimpleWindow.cfg`);
	scope renderer = new Renderer;
	auto counter = 0;

	bool programRunning = true;
	while (programRunning) {
		// Tell Hybrid what config to use
		gui.begin(cfg);
		// Exit program if user clicks the Close button
		if (gui().getProperty!(bool)("main.frame.closeClicked")) {
			programRunning = false;
		}
		// Update text on the label
		if (counter != 0)
			Label("main.label").text = toString(counter);
		// Increment counter if the button has been clicked
		if (Button("main.button").clicked) {
			counter++;
		}
		// Finalize. Prepare to render
		gui.end();
		// Render window using OpenGL Renderer
		gui.render(renderer);

		Thread.yield();
	}
}

The code creates a simple windowed application with a label and a button. Initially, the label displays "There have been no clicks yet". When the button labeled "click me" is clicked, the label updates to show the number of times the button has been clicked. The GUI layout is described using Hybrid's config files, SimpleWindow.cfg and SimpleWindow.d.


import std.stdio: writeln;

void main() {
    for (int i = 10; i >= 0; --i)
        writeln(i);
    writeln();

    foreach_reverse (i ; 0 .. 10 + 1)
        writeln(i);
}

The code performs a countdown from 10 to 0 using a downward for loop.


import std.stdio, std.string;

string encrypt(in string txt, in string key) pure @safe
in {
    assert(key.removechars("^A-Z") == key);
} body {
    string res;
    foreach (immutable i, immutable c; txt.toUpper.removechars("^A-Z"))
        res ~= (c + key[i % $] - 2 * 'A') % 26 + 'A';
    return res;
}

string decrypt(in string txt, in string key) pure @safe
in {
    assert(key.removechars("^A-Z") == key);
} body {
    string res;
    foreach (immutable i, immutable c; txt.toUpper.removechars("^A-Z"))
       res ~= (c - key[i % $] + 26) % 26 + 'A';
    return res;
}

void main() {
    immutable key = "VIGENERECIPHER";
    immutable original = "Beware the Jabberwock, my son!" ~
                         " The jaws that bite, the claws that catch!";
    immutable encoded = original.encrypt(key);
    writeln(encoded, "\n", encoded.decrypt(key));
}

Implement both encryption and decryption of a Vigenère cipher. The code handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.


import std.stdio, std.range;

void main() {
    // Print odd numbers up to 9.
    for (int i = 1; i < 10; i += 2)
        writeln(i);

    // Alternative way.
    foreach (i; iota(1, 10, 2))
        writeln(i);
}

demonstrate a for-loop with a step-value greater than one.


double sum(ref int i, in int lo, in int hi, lazy double term)
pure @safe /*nothrow @nogc*/ {
    double result = 0.0;
    for (i = lo; i <= hi; i++)
        result += term();
    return result;
}

void main() {
    import std.stdio;

    int i;
    sum(i, 1, 100, 1.0/i).writeln;
}

The code is an implementation of Jensen's Device, a programming technique devised by Jørn Jensen. It uses call by name to compute the 100th harmonic number. The technique relies on the re-evaluation of an expression passed as an actual parameter in the caller's context whenever the corresponding formal parameter's value is required. The first parameter to the sum function, representing the "bound" variable of the summation, must also be passed by name or by reference to ensure changes to it are visible in the caller's context. The global variable doesn't need to use the same identifier as the formal parameter.


void main() {
    import std.stdio;

    enum width = 512, height = 512;

    auto f = File("xor_pattern.ppm", "wb");
    f.writefln("P6\n%d %d\n255", width, height);
    foreach (immutable y; 0 .. height)
        foreach (immutable x; 0 .. width) {
            immutable c = (x ^ y) & ubyte.max;
            immutable ubyte[3] u3 = [255 - c, c / 2, c];
            f.rawWrite(u3);
        }
}

generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.


void main() @safe {
    import std.stdio, std.algorithm, std.range, std.random;

    enum uint w = 14, h = 10;
    auto vis = new bool[][](h, w),
         hor = iota(h + 1).map!(_ => ["+---"].replicate(w)).array,
         ver = h.iota.map!(_ => ["|   "].replicate(w) ~ "|").array;

    void walk(in uint x, in uint y) /*nothrow*/ @safe /*@nogc*/ {
        vis[y][x] = true;
        //foreach (immutable p; [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover) {
        foreach (const p; [[x-1, y], [x, y+1], [x+1, y], [x, y-1]].randomCover) {
            if (p[0] >= w || p[1] >= h || vis[p[1]][p[0]]) continue;
            if (p[0] == x) hor[max(y, p[1])][x] = "+   ";
            if (p[1] == y) ver[y][max(x, p[0])] = "    ";
            walk(p[0], p[1]);
        }
    }
    walk(uniform(0, w), uniform(0, h));
    foreach (const a, const b; hor.zip(ver ~ []))
        join(a ~ "+\n" ~ b).writeln;
}

generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.


import std.stdio, std.conv, std.string;

struct PiDigits {
    immutable uint nDigits;

    int opApply(int delegate(ref string /*chunk of pi digit*/) dg){
        // Maximum width for correct output, for type ulong.
        enum size_t width = 9;

        enum ulong scale = 10UL ^^ width;
        enum ulong initDigit = 2UL * 10UL ^^ (width - 1);
        enum string formatString = "%0" ~ text(width) ~ "d";

        immutable size_t len = 10 * nDigits / 3;
        auto arr = new ulong[len];
        arr[] = initDigit;
        ulong carry;

        foreach (i; 0 .. nDigits / width) {
            ulong sum;
            foreach_reverse (j; 0 .. len) {
                auto quo = sum * (j + 1) + scale * arr[j];
                arr[j] = quo % (j*2 + 1);
                sum = quo / (j*2 + 1);
            }
            auto yield = format(formatString, carry + sum/scale);
            if (dg(yield))
                break;
            carry = sum % scale;
        }
        return 0;
    }
}

void main() {
    foreach (d; PiDigits(100))
        writeln(d);
}

continuously calculate and print the next decimal digit of Pi, starting from 3.14159265. The process continues indefinitely until manually stopped by the user. The calculation is based on a modified Spigot algorithm, which has a limitation in terms of memory usage as it increases with the number of digits to be printed.


"Function to compare two numerical lists lexicographically and return true if the first list should be ordered before the second, false otherwise."


ulong ackermann(in ulong m, in ulong n) pure nothrow @nogc {
    if (m == 0)
        return n + 1;
    if (n == 0)
        return ackermann(m - 1, 1);
    return ackermann(m - 1, ackermann(m, n - 1));
}

void main() {
    assert(ackermann(2, 4) == 11);
}
import std.stdio, std.bigint, std.conv;

BigInt ipow(BigInt base, BigInt exp) pure nothrow {
    auto result = 1.BigInt;
    while (exp) {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        base *= base;
    }

    return result;
}

BigInt ackermann(in uint m, in uint n) pure nothrow
out(result) {
    assert(result >= 0);
} body {
    static BigInt ack(in uint m, in BigInt n) pure nothrow {
        switch (m) {
            case 0: return n + 1;
            case 1: return n + 2;
            case 2: return 3 + 2 * n;
            //case 3: return 5 + 8 * (2 ^^ n - 1);
            case 3: return 5 + 8 * (ipow(2.BigInt, n) - 1);
            default: return (n == 0) ?
                        ack(m - 1, 1.BigInt) :
                        ack(m - 1, ack(m, n - 1));
        }
    }

    return ack(m, n.BigInt);
}

void main() {
    foreach (immutable m; 1 .. 4)
        foreach (immutable n; 1 .. 9)
            writefln("ackermann(%d, %d): %s", m, n, ackermann(m, n));
    writefln("ackermann(4, 1): %s", ackermann(4, 1));

    immutable a = ackermann(4, 2).text;
    writefln("ackermann(4, 2)) (%d digits):\n%s...\n%s",
             a.length, a[0 .. 94], a[$ - 96 .. $]);
}

Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.


implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in/library function if available. The Gamma function is computed through numerical integration.


void main() {
    import std.stdio, std.algorithm, std.range, permutations2;

    enum n = 8;
    n.iota.array.permutations.filter!(p =>
        n.iota.map!(i => p[i] + i).array.sort().uniq.count == n &&
        n.iota.map!(i => p[i] - i).array.sort().uniq.count == n)
    .count.writeln;
}

The code solves the N-queens puzzle, which can be extended to a board of size NxN. It uses the second solution of the Permutations task to display all possible solutions. The code's runtime for a board size of 17 is approximately 49.5 seconds when compiled with ldc2.


import std.stdio: writeln;

void main() {
    int[] a = [1, 2];
    int[] b = [4, 5, 6];

    writeln(a, " ~ ", b, " = ", a ~ b);
}

demonstrate how to concatenate two arrays.


import std.stdio, std.algorithm, std.typecons, std.array, std.range;

struct Item { string name; int weight, value; }

Item[] knapsack01DinamicProgramming(immutable Item[] items, in int limit)
pure nothrow @safe {
    auto tab = new int[][](items.length + 1, limit + 1);

    foreach (immutable i, immutable it; items)
        foreach (immutable w; 1 .. limit + 1)
            tab[i + 1][w] = (it.weight > w) ? tab[i][w] :
                max(tab[i][w], tab[i][w - it.weight] + it.value);

    typeof(return) result;
    int w = limit;
    foreach_reverse (immutable i, immutable it; items)
        if (tab[i + 1][w] != tab[i][w]) {
            w -= it.weight;
            result ~= it;
        }

    return result;
}

void main() @safe {
    enum int limit = 400;
    immutable Item[] items = [
        {"apple",      39,  40}, {"banana",        27,  60},
        {"beer",       52,  10}, {"book",          30,  10},
        {"camera",     32,  30}, {"cheese",        23,  30},
        {"compass",    13,  35}, {"glucose",       15,  60},
        {"map",         9, 150}, {"note-case",     22,  80},
        {"sandwich",   50, 160}, {"socks",          4,  50},
        {"sunglasses",  7,  20}, {"suntan cream",  11,  70},
        {"t-shirt",    24,  15}, {"tin",           68,  45},
        {"towel",      18,  12}, {"trousers",      48,  10},
        {"umbrella",   73,  40}, {"water",        153, 200},
        {"waterproof overclothes", 43, 75},
        {"waterproof trousers",    42, 70}];

    immutable bag = knapsack01DinamicProgramming(items, limit);
    writefln("Items:\n%-(  %s\n%)", bag.map!q{ a.name }.retro);
    const t = reduce!q{ a[] += [b.weight, b.value] }([0, 0], bag);
    writeln("\nTotal weight and value: ", t[0] <= limit ? t : [0, 0]);
}

The code determines the optimal combination of items, with individual weights not exceeding 4kg in total, that a tourist can carry in his knapsack to maximize the total value. The items are selected from a predefined list, with each item having a specific weight and value. Only one of each item is available and items cannot be divided. The solution is obtained in approximately 0.04 to 0.09 seconds.


import std.stdio, std.array, std.algorithm, std.string;

string[string] matchmaker(string[][string] guyPrefers,
                          string[][string] girlPrefers) /*@safe*/ {
    string[string] engagedTo;
    string[] freeGuys = guyPrefers.keys;

    while (freeGuys.length) {
        const string thisGuy = freeGuys[0];
        freeGuys.popFront();
        const auto thisGuyPrefers = guyPrefers[thisGuy];
        foreach (girl; thisGuyPrefers) {
            if (girl !in engagedTo) { // girl is free
                engagedTo[girl] = thisGuy;
                break;
            } else {
                string otherGuy = engagedTo[girl];
                string[] thisGirlPrefers = girlPrefers[girl];
                if (thisGirlPrefers.countUntil(thisGuy) <
                    thisGirlPrefers.countUntil(otherGuy)) {
                    // this girl prefers this guy to
                    // the guy she's engagedTo to.
                    engagedTo[girl] = thisGuy;
                    freeGuys ~= otherGuy;
                    break;
                }
                // else no change, keep looking for this guy
            }
        }
    }

    return engagedTo;
}

bool check(bool doPrint=false)(string[string] engagedTo,
                               string[][string] guyPrefers,
                               string[][string] galPrefers) @safe {
    enum MSG = "%s likes %s better than %s and %s " ~
               "likes %s better than their current partner";
    string[string] inverseEngaged;
    foreach (k, v; engagedTo)
        inverseEngaged[v] = k;

    foreach (she, he; engagedTo) {
        auto sheLikes = galPrefers[she];
        auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)];
        auto heLikes = guyPrefers[he];
        auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)];
        foreach (guy; sheLikesBetter) {
            auto guysGirl = inverseEngaged[guy];
            auto guyLikes = guyPrefers[guy];

            if (guyLikes.countUntil(guysGirl) >
                guyLikes.countUntil(she)) {
                static if (doPrint)
                    writefln(MSG, she, guy, he, guy, she);
                return false;
            }
        }

        foreach (gal; heLikesBetter) {
            auto girlsGuy = engagedTo[gal];
            auto galLikes = galPrefers[gal];

            if (galLikes.countUntil(girlsGuy) >
                galLikes.countUntil(he)) {
                static if (doPrint)
                    writefln(MSG, he, gal, she, gal, he);
                return false;
            }
        }
    }

    return true;
}

void main() /*@safe*/ {
    auto guyData = "abe  abi eve cath ivy jan dee fay bea hope gay
                    bob  cath hope abi dee eve fay bea jan ivy gay
                    col  hope eve abi dee bea fay ivy gay cath jan
                    dan  ivy fay dee gay hope eve jan bea cath abi
                    ed   jan dee bea cath fay eve abi ivy hope gay
                    fred bea abi dee gay eve ivy cath jan hope fay
                    gav  gay eve ivy bea cath abi dee hope jan fay
                    hal  abi eve hope fay ivy cath jan bea gay dee
                    ian  hope cath dee gay bea abi fay ivy jan eve
                    jon  abi fay jan gay eve bea dee cath ivy hope";

    auto galData = "abi  bob fred jon gav ian abe dan ed col hal
                    bea  bob abe col fred gav dan ian ed jon hal
                    cath fred bob ed gav hal col ian abe dan jon
                    dee  fred jon col abe ian hal gav dan bob ed
                    eve  jon hal fred dan abe gav col ed ian bob
                    fay  bob abe ed ian jon dan fred gav col hal
                    gay  jon gav hal fred bob abe col ed dan ian
                    hope gav jon bob abe ian dan hal ed col fred
                    ivy  ian col hal gav fred bob abe ed jon dan
                    jan  ed hal gav abe bob jon col ian fred dan";

    string[][string] guyPrefers, galPrefers;
    foreach (line; guyData.splitLines())
        guyPrefers[split(line)[0]] = split(line)[1..$];
    foreach (line; galData.splitLines())
        galPrefers[split(line)[0]] = split(line)[1..$];

    writeln("Engagements:");
    auto engagedTo = matchmaker(guyPrefers, galPrefers);

    writeln("\nCouples:");
    string[] parts;
    foreach (k; engagedTo.keys.sort())
        writefln("%s is engagedTo to %s", k, engagedTo[k]);
    writeln();

    bool c = check!(true)(engagedTo, guyPrefers, galPrefers);
    writeln("Marriages are ", c ? "stable" : "unstable");

    writeln("\n\nSwapping two fiances to introduce an error");
    auto gals = galPrefers.keys.sort();
    swap(engagedTo[gals[0]], engagedTo[gals[1]]);
    foreach (gal; gals[0 .. 2])
        writefln("  %s is now engagedTo to %s", gal, engagedTo[gal]);
    writeln();

    c = check!(true)(engagedTo, guyPrefers, galPrefers);
    writeln("Marriages are ", c ? "stable" : "unstable");
}

The code implements the Gale/Shapley algorithm to solve the Stable Marriage Problem. It takes as input a list of ten males and ten females along with their ranked preferences for potential partners. The code finds a stable set of engagements where no individual prefers someone else over their current partner. It then perturbs this set to create an unstable set of engagements and checks this new set for stability.


import std.stdio, std.algorithm;

T a(T)(T answer) {
    writefln("  # Called function a(%s) -> %s", answer, answer);
    return answer;
}

T b(T)(T answer) {
    writefln("  # Called function b(%s) -> %s", answer, answer);
    return answer;
}

void main() {
    foreach (immutable x, immutable y;
             [false, true].cartesianProduct([false, true])) {
        writeln("\nCalculating: r1 = a(x) && b(y)");
        immutable r1 = a(x) && b(y);
        writeln("Calculating: r2 = a(x) || b(y)");
        immutable r2 = a(x) || b(y);
    }
}

create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.


<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. </output>


import std.stdio, std.algorithm, std.string;

bool canMakeWord(in string word, in string[] blocks) pure /*nothrow*/ @safe {
    auto bs = blocks.dup;
    outer: foreach (immutable ch; word.toUpper) {
        foreach (immutable block; bs)
            if (block.canFind(ch)) {
                bs = bs.remove(bs.countUntil(block));
                continue outer;
            }
        return false;
    }
    return true;
}

void main() @safe {
    immutable blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI
                        AN OB ER FS LY PC ZM".split;

    foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split)
        writefln(`"%s" %s`, word, canMakeWord(word, blocks));
}

The code implements a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive. It uses a simple greedy algorithm and avoids heap allocations for efficiency. It can handle ASCII inputs and doesn't shuffle the input blocks. It also includes test cases for seven different words.


void main() {
    import std.stdio, std.digest.md;

    auto txt = "The quick brown fox jumped over the lazy dog's back";
    writefln("%-(%02x%)", txt.md5Of);
}

encode a string using the MD5 algorithm, validate the implementation using test values from IETF RFC (1321), and provide a warning about the known weaknesses of MD5. If a library solution is used, refer to MD5/Implementation for a scratch implementation.


module socket ;
import std.stdio ;
import std.socket ;
version(Win32) {
  // For Win32 systems, need to link with ws2_32.lib.
  pragma(lib, "ws2_32.lib") ;
}
void main() {
  long res;
  auto socket = new Socket(AddressFamily.INET, SocketType.STREAM) ;
  socket.connect(new InternetAddress("localhost",256)) ;
  res = socket.send(cast(void[])"hello socket world") ;
  writefln("Socket %d bytes sent.", res) ;
  socket.close() ;
}

opens a socket to localhost on port 256, sends the message "hello socket world", and then closes the socket.


void main() {
    import std.net.curl;

    auto s = SMTP("smtps://smtp.gmail.com");
    s.setAuthentication("someuser@gmail.com", "somepassword");
    s.mailTo = ["<friend@example.com>"];
    s.mailFrom = "<someuser@gmail.com>";
    s.message = "Subject:test\n\nExample Message";
    s.perform;
}

The code is a function for sending an email, allowing parameters to set From, To, Cc addresses, Subject, and message text, with optional fields for server name and login details. It uses the libcurl library and provides notifications for any issues or success. The code is designed to be portable across different operating systems. Sensitive data used in examples is obfuscated.


void main() {
    import std.stdio;

    ubyte i;
    do writefln("%o", i++);
    while(i);
}

generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.


import std.algorithm: swap; // from Phobos standard library

// The D solution uses templates and it's similar to the C++ one:
void mySwap(T)(ref T left, ref T right) {
    auto temp = left;
    left = right;
    right = temp;
}

void main() {
    import std.stdio;

    int[] a = [10, 20];
    writeln(a);

    // The std.algorithm standard library module
    // contains a generic swap:
    swap(a[0], a[1]);
    writeln(a);

    // Using mySwap:
    mySwap(a[0], a[1]);
    writeln(a);
}

implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.


import std.traits, std.algorithm;

bool isPalindrome1(C)(in C[] s) pure /*nothrow*/
if (isSomeChar!C) {
    auto s2 = s.dup;
    s2.reverse(); // works on Unicode too, not nothrow.
    return s == s2;
}

void main() {
    alias pali = isPalindrome1;
    assert(pali(""));
    assert(pali("z"));
    assert(pali("aha"));
    assert(pali("sees"));
    assert(!pali("oofoe"));
    assert(pali("deified"));
    assert(!pali("Deified"));
    assert(pali("amanaplanacanalpanama"));
    assert(pali("ingirumimusnocteetconsumimurigni"));
    assert(pali("salÃ las"));
}

import std.traits;

bool isPalindrome2(C)(in C[] s) pure if (isSomeChar!C) {
    dchar[] dstr;
    foreach (dchar c; s) // not nothrow
        dstr ~= c;

    for (int i; i < dstr.length / 2; i++)
        if (dstr[i] != dstr[$ - i - 1])
            return false;
    return true;
}

void main() {
    alias isPalindrome2 pali;
    assert(pali(""));
    assert(pali("z"));
    assert(pali("aha"));
    assert(pali("sees"));
    assert(!pali("oofoe"));
    assert(pali("deified"));
    assert(!pali("Deified"));
    assert(pali("amanaplanacanalpanama"));
    assert(pali("ingirumimusnocteetconsumimurigni"));
    assert(pali("salÃ las"));
}

import std.stdio, core.exception, std.traits;

// assume alloca() to be pure for this program
extern(C) pure nothrow void* alloca(in size_t size);

bool isPalindrome3(C)(in C[] s) pure if (isSomeChar!C) {
    auto p = cast(dchar*)alloca(s.length * 4);
    if (p == null)
        // no fallback heap allocation used
        throw new OutOfMemoryError();
    dchar[] dstr = p[0 .. s.length];

    // use std.utf.stride for an even lower level version
    int i = 0;
    foreach (dchar c; s) { // not nothrow
        dstr[i] = c;
        i++;
    }
    dstr = dstr[0 .. i];

    foreach (j; 0 .. dstr.length / 2)
        if (dstr[j] != dstr[$ - j - 1])
            return false;
    return true;
}

void main() {
    alias isPalindrome3 pali;
    assert(pali(""));
    assert(pali("z"));
    assert(pali("aha"));
    assert(pali("sees"));
    assert(!pali("oofoe"));
    assert(pali("deified"));
    assert(!pali("Deified"));
    assert(pali("amanaplanacanalpanama"));
    assert(pali("ingirumimusnocteetconsumimurigni"));
    assert(pali("salÃ las"));
}

bool isPalindrome4(in string str) pure nothrow {
    if (str.length == 0) return true;
    immutable(char)* s = str.ptr;
    immutable(char)* t = &(str[$ - 1]);
    while (s < t)
        if (*s++ != *t--) // ugly
            return false;
    return true;
}

void main() {
    alias isPalindrome4 pali;
    assert(pali(""));
    assert(pali("z"));
    assert(pali("aha"));
    assert(pali("sees"));
    assert(!pali("oofoe"));
    assert(pali("deified"));
    assert(!pali("Deified"));
    assert(pali("amanaplanacanalpanama"));
    assert(pali("ingirumimusnocteetconsumimurigni"));
    //assert(pali("salÃ las"));
}

implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.


Library: phobos
import std.stdio, std.process;

void main() {
    auto home = getenv("HOME");
}

Library: tango
import tango.sys.Environment;

void main() {
    auto home = Environment("HOME");
}

"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system."


// Non-Generic Stack
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek(); // Peek without Popping.
top = stack.Pop();

// Generic Stack
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek(); // Peek without Popping.
top = stack.Pop();

implement a stack data structure with basic operations such as push (to add elements), pop (to remove and return the last added element), and empty (to check if the stack is empty). This stack follows a Last-In-First-Out (LIFO) access policy.


public static ulong Fib(uint n) {
    return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}

Tail-public static ulong Fib(uint n) {
    return Fib(0, 1, n);
}

private static ulong Fib(ulong a, ulong b, uint n) {
    return (n < 1)? a :(n == 1)?  b : Fib(b, a + b, n - 1);
}

public static ulong Fib(uint x) {
    if (x == 0) return 0;

    ulong prev = 0;
    ulong next = 1;
    for (int i = 1; i < x; i++)
    {
        ulong sum = prev + next;
        prev = next;
        next = sum;
    }
    return next;
}

using System; using System.Text; // FIBRUS.cs Russia
namespace Fibrus { class Program { static void Main()
{ long fi1=1; long fi2=1; long fi3=1; int da; int i; int d;
for (da=1; da<=78; da++) // rextester.com/MNGUV70257
    { d = 20-Convert.ToInt32((Convert.ToString(fi3)).Length);
    for (i=1; i<d; i++) Console.Write(".");
Console.Write(fi3); Console.Write(" "); Console.WriteLine(da);
    fi3 = fi2 + fi1;
    fi1 = fi2;
    fi2 = fi3;
}}}}

The code defines a function to generate the nth Fibonacci number, either iteratively or recursively. It optionally supports negative numbers by using the inverse of the positive definition. The function is accurate up to the 71st Fibonacci number due to custom rounding. It uses System.Windows.Media.Matrix or a similar Matrix class for calculations, and can efficiently calculate large Fibonacci numbers. Additionally, it includes a routine to return an array of Fibonacci numbers.


Works with: .NET version 1.1
ArrayList array = new ArrayList( new int[] { 1, 2, 3, 4, 5 } );
ArrayList evens = new ArrayList();
foreach( int i in array )
{
        if( (i%2) == 0 )
                evens.Add( i );
}
foreach( int i in evens )
       System.Console.WriteLine( i.ToString() );

Works with: .NET version 2.0
List<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );
List<int> evens = array.FindAll( delegate( int i ) { return (i%2)==0; } );
foreach( int i in evens )
       System.Console.WriteLine( i.ToString() );

Works with: .NET version 3.5
IEnumerable<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );
IEnumerable<int> evens = array.Where( delegate( int i ) { return (i%2)==0; } );
foreach( int i in evens )
       System.Console.WriteLine( i.ToString() );

int[] array = { 1, 2, 3, 4, 5 };
int[] evens = array.Where(i => (i % 2) == 0).ToArray();

foreach (int i in evens)
    Console.WriteLine(i);

select specific elements from an array into a new array, specifically even numbers. Optionally, it also provides a destructive filtering method that modifies the original array instead of creating a new one. The code also demonstrates the replacement of a delegate with a lambda expression for conciseness.


using System;
namespace SubString
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "0123456789";
            const int n = 3;
            const int m = 2;
            const char c = '3';
            const string z = "345";

            // A: starting from n characters in and of m length;
            Console.WriteLine(s.Substring(n, m));
            // B: starting from n characters in, up to the end of the string;
            Console.WriteLine(s.Substring(n, s.Length - n));
            // C: whole string minus the last character;
            Console.WriteLine(s.Substring(0, s.Length - 1));
            // D: starting from a known character within the string and of m length;
            Console.WriteLine(s.Substring(s.IndexOf(c), m));
            // E: starting from a known substring within the string and of m length.
            Console.WriteLine(s.Substring(s.IndexOf(z), m));
        }
    }
}

// B: starting from n characters in, up to the end of the string;
Console.WriteLine(s[n..]);
// C: whole string minus the last character;
Console.WriteLine(s[..^1]);

- Display a substring from a specific position and of a certain length.
- Display a substring from a specific position to the end of the string.
- Display the entire string except the last character.
- Display a substring starting from a known character within the string and of a certain length.
- Display a substring starting from a known substring within the string and of a certain length.
- The program supports any valid Unicode code point in UTF-8 or UTF-16.
- The program references logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
- The program does not necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.
- Utilizes the Range syntax in C# 8 for more succinct code in certain cases.


static string ReverseString(string input)
{
    char[] inputChars = input.ToCharArray();
    Array.Reverse(inputChars);
    return new string(inputChars);
}

using System.Linq;

// ...

return new string(input.Reverse().ToArray());

// ...

public string ReverseElements(string s)
{
    // In .NET, a text element is series of code units that is displayed as one character, and so reversing the text
    // elements of the string correctly handles combining character sequences and surrogate pairs.
    var elements = System.Globalization.StringInfo.GetTextElementEnumerator(s);
    return string.Concat(AsEnumerable(elements).OfType<string>().Reverse());
}

// Wraps an IEnumerator, allowing it to be used as an IEnumerable.
public IEnumerable AsEnumerable(IEnumerator enumerator)
{
    while (enumerator.MoveNext())
        yield return enumerator.Current;
}

implement a function to reverse a string, preserving Unicode combining characters. The function converts the string to a character array, reverses it, and returns a new string from the reversed array. It uses .Net 3.5 LINQ-to-objects Reverse() extension method and ToArray extension method. It also supports combining characters by separating a string into individual graphemes using System.Globalization.StringInfo.


Works with: C sharp version 7
using static System.Linq.Enumerable;
using static System.String;
using static System.Console;
using System.Collections.Generic;
using System;
using EdgeList = System.Collections.Generic.List<(int node, double weight)>;

public static class Dijkstra
{
    public static void Main() {
        Graph graph = new Graph(6);
        Func<char, int> id = c => c - 'a';
        Func<int , char> name = i => (char)(i + 'a');
        foreach (var (start, end, cost) in new [] {
            ('a', 'b', 7),
            ('a', 'c', 9),
            ('a', 'f', 14),
            ('b', 'c', 10),
            ('b', 'd', 15),
            ('c', 'd', 11),
            ('c', 'f', 2),
            ('d', 'e', 6),
            ('e', 'f', 9),
        }) {
            graph.AddEdge(id(start), id(end), cost);
        }

        var path = graph.FindPath(id('a'));
        for (int d = id('b'); d <= id('f'); d++) {
            WriteLine(Join(" -> ", Path(id('a'), d).Select(p => $"{name(p.node)}({p.distance})").Reverse()));
        }

        IEnumerable<(double distance, int node)> Path(int start, int destination) {
            yield return (path[destination].distance, destination);
            for (int i = destination; i != start; i = path[i].prev) {
                yield return (path[path[i].prev].distance, path[i].prev);
            }
        }
    }

}

sealed class Graph
{
    private readonly List<EdgeList> adjacency;

    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();

    public int Count => adjacency.Count;
    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);
    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;

    public bool AddEdge(int s, int e, double weight) {
        if (HasEdge(s, e)) return false;
        adjacency[s].Add((e, weight));
        return true;
    }

    public (double distance, int prev)[] FindPath(int start) {
        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();
        info[start].distance = 0;
        var visited = new System.Collections.BitArray(adjacency.Count);

        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));
        heap.Push((start, 0));
        while (heap.Count > 0) {
            var current = heap.Pop();
            if (visited[current.node]) continue;
            var edges = adjacency[current.node];
            for (int n = 0; n < edges.Count; n++) {
                int v = edges[n].node;
                if (visited[v]) continue;
                double alt = info[current.node].distance + edges[n].weight;
                if (alt < info[v].distance) {
                    info[v] = (alt, current.node);
                    heap.Push((v, alt));
                }
            }
            visited[current.node] = true;
        }
        return info;
    }

}

sealed class Heap<T>
{
    private readonly IComparer<T> comparer;
    private readonly List<T> list = new List<T> { default };

    public Heap() : this(default(IComparer<T>)) { }

    public Heap(IComparer<T> comparer) {
        this.comparer = comparer ?? Comparer<T>.Default;
    }

    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }

    public int Count => list.Count - 1;

    public void Push(T element) {
        list.Add(element);
        SiftUp(list.Count - 1);
    }

    public T Pop() {
        T result = list[1];
        list[1] = list[list.Count - 1];
        list.RemoveAt(list.Count - 1);
        SiftDown(1);
        return result;
    }

    private static int Parent(int i) => i / 2;
    private static int Left(int i) => i * 2;
    private static int Right(int i) => i * 2 + 1;

    private void SiftUp(int i) {
        while (i > 1) {
            int parent = Parent(i);
            if (comparer.Compare(list[i], list[parent]) > 0) return;
            (list[parent], list[i]) = (list[i], list[parent]);
            i = parent;
        }
    }

    private void SiftDown(int i) {
        for (int left = Left(i); left < list.Count; left = Left(i)) {
            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;
            int right = Right(i);
            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;
            if (smallest == i) return;
            (list[i], list[smallest]) = (list[smallest], list[i]);
            i = smallest;
        }
    }

}

Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node. The program also interprets the output to display the shortest path from the source node to specific nodes.


using System;
using System.Collections.Generic;

public enum Direction { FromLeft, FromRight };

public enum State { Header, LeftHigh, Balanced, RightHigh };

public enum SetOperation
{
    Union,
    Intersection,
    SymmetricDifference,
    Difference,
    Equality,
    Inequality,
    Subset,
    Superset
}

public class Node
{
    public Node Left;
    public Node Right;
    public Node Parent;
    public State Balance;

    public Node()
    {
        Left = this;
        Right = this;
        Parent = null;
        Balance = State.Header;
    }

    public Node(Node p)
    {
        Left = null;
        Right = null;
        Parent = p;
        Balance = State.Balanced;
    }

    public bool IsHeader
    { get { return Balance == State.Header; } }
}

public class SetNode<T> : Node
{
    public T Data;

    public SetNode() { }

    public SetNode(T dataType, Node Parent) : base(Parent)
    {
        Data = dataType;
    }

    public override int GetHashCode()
    {
        return Data.GetHashCode();
    }
}

class Utility // Nongeneric Tree Balancing
{
    static void RotateLeft(ref Node Root)
    {
        Node Parent = Root.Parent;
        Node x = Root.Right;

        Root.Parent = x;
        x.Parent = Parent;
        if (x.Left != null) x.Left.Parent = Root;

        Root.Right = x.Left;
        x.Left = Root;
        Root = x;
    }

    static void RotateRight(ref Node Root)
    {
        Node Parent = Root.Parent;
        Node x = Root.Left;

        Root.Parent = x;
        x.Parent = Parent;
        if (x.Right != null) x.Right.Parent = Root;

        Root.Left = x.Right;
        x.Right = Root;
        Root = x;
    }

    static void BalanceLeft(ref Node Root)
    {
        Node Left = Root.Left;

        switch (Left.Balance)
        {
            case State.LeftHigh:
                Root.Balance = State.Balanced;
                Left.Balance = State.Balanced;
                RotateRight(ref Root);
                break;

            case State.RightHigh:
                {
                    Node subRight = Left.Right;
                    switch (subRight.Balance)
                    {
                        case State.Balanced:
                            Root.Balance = State.Balanced;
                            Left.Balance = State.Balanced;
                            break;

                        case State.RightHigh:
                            Root.Balance = State.Balanced;
                            Left.Balance = State.LeftHigh;
                            break;

                        case State.LeftHigh:
                            Root.Balance = State.RightHigh;
                            Left.Balance = State.Balanced;
                            break;
                    }
                    subRight.Balance = State.Balanced;
                    RotateLeft(ref Left);
                    Root.Left = Left;
                    RotateRight(ref Root);
                }
                break;

            case State.Balanced:
                Root.Balance = State.LeftHigh;
                Left.Balance = State.RightHigh;
                RotateRight(ref Root);
                break;
        }
    }

    static void BalanceRight(ref Node Root)
    {
        Node Right = Root.Right;

        switch (Right.Balance)
        {
            case State.RightHigh:
                Root.Balance = State.Balanced;
                Right.Balance = State.Balanced;
                RotateLeft(ref Root);
                break;

            case State.LeftHigh:
                {
                    Node subLeft = Right.Left; // Left Subtree of Right
                    switch (subLeft.Balance)
                    {
                        case State.Balanced:
                            Root.Balance = State.Balanced;
                            Right.Balance = State.Balanced;
                            break;

                        case State.LeftHigh:
                            Root.Balance = State.Balanced;
                            Right.Balance = State.RightHigh;
                            break;

                        case State.RightHigh:
                            Root.Balance = State.LeftHigh;
                            Right.Balance = State.Balanced;
                            break;
                    }
                    subLeft.Balance = State.Balanced;
                    RotateRight(ref Right);
                    Root.Right = Right;
                    RotateLeft(ref Root);
                }
                break;

            case State.Balanced:
                Root.Balance = State.RightHigh;
                Right.Balance = State.LeftHigh;
                RotateLeft(ref Root);
                break;
        }
    }

    public static void BalanceSet(Node Root, Direction From)
    {
        bool Taller = true;

        while (Taller)
        {
            Node Parent = Root.Parent;
            Direction NextFrom = (Parent.Left == Root) ? Direction.FromLeft : Direction.FromRight;

            if (From == Direction.FromLeft)
            {
                switch (Root.Balance)
                {
                    case State.LeftHigh:
                        if (Parent.IsHeader)
                            BalanceLeft(ref Parent.Parent);
                        else if (Parent.Left == Root)
                            BalanceLeft(ref Parent.Left);
                        else
                            BalanceLeft(ref Parent.Right);
                        Taller = false;
                        break;

                    case State.Balanced:
                        Root.Balance = State.LeftHigh;
                        Taller = true;
                        break;

                    case State.RightHigh:
                        Root.Balance = State.Balanced;
                        Taller = false;
                        break;
                }
            }
            else
            {
                switch (Root.Balance)
                {
                    case State.LeftHigh:
                        Root.Balance = State.Balanced;
                        Taller = false;
                        break;

                    case State.Balanced:
                        Root.Balance = State.RightHigh;
                        Taller = true;
                        break;

                    case State.RightHigh:
                        if (Parent.IsHeader)
                            BalanceRight(ref Parent.Parent);
                        else if (Parent.Left == Root)
                            BalanceRight(ref Parent.Left);
                        else
                            BalanceRight(ref Parent.Right);
                        Taller = false;
                        break;
                }
            }

            if (Taller) // skip up a level
            {
                if (Parent.IsHeader)
                    Taller = false;
                else
                {
                    Root = Parent;
                    From = NextFrom;
                }
            }
        }
    }

    public static void BalanceSetRemove(Node Root, Direction From)
    {
        if (Root.IsHeader) return;

        bool Shorter = true;

        while (Shorter)
        {
            Node Parent = Root.Parent;
            Direction NextFrom = (Parent.Left == Root) ? Direction.FromLeft : Direction.FromRight;

            if (From == Direction.FromLeft)
            {
                switch (Root.Balance)
                {
                    case State.LeftHigh:
                        Root.Balance = State.Balanced;
                        Shorter = true;
                        break;

                    case State.Balanced:
                        Root.Balance = State.RightHigh;
                        Shorter = false;
                        break;

                    case State.RightHigh:
                        if (Root.Right.Balance == State.Balanced)
                            Shorter = false;
                        else
                            Shorter = true;
                        if (Parent.IsHeader)
                            BalanceRight(ref Parent.Parent);
                        else if (Parent.Left == Root)
                            BalanceRight(ref Parent.Left);
                        else
                            BalanceRight(ref Parent.Right);
                        break;
                }
            }
            else
            {
                switch (Root.Balance)
                {
                    case State.RightHigh:
                        Root.Balance = State.Balanced;
                        Shorter = true;
                        break;

                    case State.Balanced:
                        Root.Balance = State.LeftHigh;
                        Shorter = false;
                        break;

                    case State.LeftHigh:
                        if (Root.Left.Balance == State.Balanced)
                            Shorter = false;
                        else
                            Shorter = true;
                        if (Parent.IsHeader)
                            BalanceLeft(ref Parent.Parent);
                        else if (Parent.Left == Root)
                            BalanceLeft(ref Parent.Left);
                        else
                            BalanceLeft(ref Parent.Right);
                        break;
                }
            }

            if (Shorter)
            {
                if (Parent.IsHeader)
                    Shorter = false;
                else
                {
                    From = NextFrom;
                    Root = Parent;
                }
            }
        }
    }

    public static Node PreviousItem(Node Node)
    {
        if (Node.IsHeader) { return Node.Right; }

        if (Node.Left != null)
        {
            Node = Node.Left;
            while (Node.Right != null) Node = Node.Right;
        }
        else
        {
            Node y = Node.Parent;
            if (y.IsHeader) return y;
            while (Node == y.Left) { Node = y; y = y.Parent; }
            Node = y;
        }
        return Node;
    }

    public static Node NextItem(Node Node)
    {
        if (Node.IsHeader) return Node.Left;

        if (Node.Right != null)
        {
            Node = Node.Right;
            while (Node.Left != null) Node = Node.Left;
        }
        else
        {
            Node y = Node.Parent;
            if (y.IsHeader) return y;
            while (Node == y.Right) { Node = y; y = y.Parent; }
            Node = y;
        }
        return Node;
    }

    public static ulong Depth(Node Root)
    {
        if (Root != null)
        {
            ulong Left = Root.Left != null ? Depth(Root.Left) : 0;
            ulong Right = Root.Right != null ? Depth(Root.Right) : 0;
            return Left < Right ? Right + 1 : Left + 1;
        }
        else
            return 0;
    }

    static void SwapNodeReference(ref Node First,
                                  ref Node Second)
    { Node Temporary = First; First = Second; Second = Temporary; }

    public static void SwapNodes(Node A, Node B)
    {
        if (B == A.Left)
        {
            if (B.Left != null) B.Left.Parent = A;
            if (B.Right != null) B.Right.Parent = A;

            if (A.Right != null) A.Right.Parent = B;

            if (!A.Parent.IsHeader)
            {
                if (A.Parent.Left == A)
                    A.Parent.Left = B;
                else
                    A.Parent.Right = B;
            }
            else A.Parent.Parent = B;

            B.Parent = A.Parent;
            A.Parent = B;

            A.Left = B.Left;
            B.Left = A;

            SwapNodeReference(ref A.Right, ref B.Right);
        }
        else if (B == A.Right)
        {
            if (B.Right != null) B.Right.Parent = A;
            if (B.Left != null) B.Left.Parent = A;

            if (A.Left != null) A.Left.Parent = B;

            if (!A.Parent.IsHeader)
            {
                if (A.Parent.Left == A)
                    A.Parent.Left = B;
                else
                    A.Parent.Right = B;
            }
            else A.Parent.Parent = B;

            B.Parent = A.Parent;
            A.Parent = B;

            A.Right = B.Right;
            B.Right = A;

            SwapNodeReference(ref A.Left, ref B.Left);
        }
        else if (A == B.Left)
        {
            if (A.Left != null) A.Left.Parent = B;
            if (A.Right != null) A.Right.Parent = B;

            if (B.Right != null) B.Right.Parent = A;

            if (!B.Parent.IsHeader)
            {
                if (B.Parent.Left == B)
                    B.Parent.Left = A;
                else
                    B.Parent.Right = A;
            }
            else B.Parent.Parent = A;

            A.Parent = B.Parent;
            B.Parent = A;

            B.Left = A.Left;
            A.Left = B;

            SwapNodeReference(ref A.Right, ref B.Right);
        }
        else if (A == B.Right)
        {
            if (A.Right != null) A.Right.Parent = B;
            if (A.Left != null) A.Left.Parent = B;

            if (B.Left != null) B.Left.Parent = A;

            if (!B.Parent.IsHeader)
            {
                if (B.Parent.Left == B)
                    B.Parent.Left = A;
                else
                    B.Parent.Right = A;
            }
            else B.Parent.Parent = A;

            A.Parent = B.Parent;
            B.Parent = A;

            B.Right = A.Right;
            A.Right = B;

            SwapNodeReference(ref A.Left, ref B.Left);
        }
        else
        {
            if (A.Parent == B.Parent)
                SwapNodeReference(ref A.Parent.Left, ref A.Parent.Right);
            else
            {
                if (!A.Parent.IsHeader)
                {
                    if (A.Parent.Left == A)
                        A.Parent.Left = B;
                    else
                        A.Parent.Right = B;
                }
                else A.Parent.Parent = B;

                if (!B.Parent.IsHeader)
                {
                    if (B.Parent.Left == B)
                        B.Parent.Left = A;
                    else
                        B.Parent.Right = A;
                }
                else B.Parent.Parent = A;
            }

            if (B.Left != null) B.Left.Parent = A;
            if (B.Right != null) B.Right.Parent = A;

            if (A.Left != null) A.Left.Parent = B;
            if (A.Right != null) A.Right.Parent = B;

            SwapNodeReference(ref A.Left, ref B.Left);
            SwapNodeReference(ref A.Right, ref B.Right);
            SwapNodeReference(ref A.Parent, ref B.Parent);
        }

        State Balance = A.Balance;
        A.Balance = B.Balance;
        B.Balance = Balance;
    }
}

public struct SetEntry<T> : IEnumerator<T>
{
    public SetEntry(Node N) { _Node = N; }

    public T Value
    {
        get
        {
            return ((SetNode<T>)_Node).Data;
        }
    }

    public bool IsEnd { get { return _Node.IsHeader; } }

    public bool MoveNext()
    {
        _Node = Utility.NextItem(_Node);
        return _Node.IsHeader ? false : true;
    }

    public bool MovePrevious()
    {
        _Node = Utility.PreviousItem(_Node);
        return _Node.IsHeader ? false : true;
    }

    public static SetEntry<T> operator ++(SetEntry<T> entry)
    {
        entry._Node = Utility.NextItem(entry._Node);
        return entry;
    }

    public static SetEntry<T> operator --(SetEntry<T> entry)
    {
        entry._Node = Utility.PreviousItem(entry._Node);
        return entry;
    }

    public void Reset()
    {
        while (!MoveNext()) ;
    }

    object System.Collections.IEnumerator.Current
    { get { return ((SetNode<T>)_Node).Data; } }

    T IEnumerator<T>.Current
    { get { return ((SetNode<T>)_Node).Data; } }

    public static bool operator ==(SetEntry<T> x, SetEntry<T> y) { return x._Node == y._Node; }
    public static bool operator !=(SetEntry<T> x, SetEntry<T> y) { return x._Node != y._Node; }

    public override bool Equals(object o) { return _Node == ((SetEntry<T>)o)._Node; }

    public override int GetHashCode() { return _Node.GetHashCode(); }

    public static SetEntry<T> operator +(SetEntry<T> C, ulong Increment)
    {
        SetEntry<T> Result = new SetEntry<T>(C._Node);
        for (ulong i = 0; i < Increment; i++) ++Result;
        return Result;
    }

    public static SetEntry<T> operator +(ulong Increment, SetEntry<T> C)
    {
        SetEntry<T> Result = new SetEntry<T>(C._Node);
        for (ulong i = 0; i < Increment; i++) ++Result;
        return Result;
    }

    public static SetEntry<T> operator -(SetEntry<T> C, ulong Decrement)
    {
        SetEntry<T> Result = new SetEntry<T>(C._Node);
        for (ulong i = 0; i < Decrement; i++) --Result;
        return Result;
    }

    public override string ToString()
    {
        return Value.ToString();
    }

    public void Dispose() { }

    public Node _Node;
}

class Set<T> : IEnumerable<T>
{
    IComparer<T> Comparer;
    Node Header;
    ulong Nodes;

    //*** Constructors ***

    public Set()
    {
        Comparer = Comparer<T>.Default;
        Header = new Node();
        Nodes = 0;
    }

    public Set(IComparer<T> c)
    {
        Comparer = c;
        Header = new Node();
        Nodes = 0;
    }

    //*** Properties ***

    SetNode<T> Root
    {
        get { return (SetNode<T>)Header.Parent; }
        set { Header.Parent = value; }
    }

    Node LeftMost
    {
        get { return Header.Left; }
        set { Header.Left = value; }
    }

    Node RightMost
    {
        get { return Header.Right; }
        set { Header.Right = value; }
    }

    public SetEntry<T> Begin
    { get { return new SetEntry<T>(Header.Left); } }

    public SetEntry<T> End
    { get { return new SetEntry<T>(Header); } }

    public ulong Length { get { return Nodes; } }

    public ulong Depth { get { return Utility.Depth(Root); } }

    //*** Operators ***

    public bool this[T key] { get { return Search(key); } }

    public static Set<T> operator +(Set<T> set, T t)
    {
        set.Add(t); return set;
    }

    public static Set<T> operator -(Set<T> set, T t)
    {
        set.Remove(t); return set;
    }

    public static Set<T> operator |(Set<T> A, Set<T> B)
    {
        Set<T> U = new Set<T>(A.Comparer);
        CombineSets(A, B, U, SetOperation.Union);
        return U;
    }

    public static Set<T> operator &(Set<T> A, Set<T> B)
    {
        Set<T> I = new Set<T>(A.Comparer);
        CombineSets(A, B, I, SetOperation.Intersection);
        return I;
    }

    public static Set<T> operator ^(Set<T> A, Set<T> B)
    {
        Set<T> S = new Set<T>(A.Comparer);
        CombineSets(A, B, S, SetOperation.SymmetricDifference);
        return S;
    }

    public static Set<T> operator -(Set<T> A, Set<T> B)
    {
        Set<T> S = new Set<T>(A.Comparer);
        CombineSets(A, B, S, SetOperation.Difference);
        return S;
    }

    public static bool operator ==(Set<T> A, Set<T> B)
    {
        return CheckSets(A, B, SetOperation.Equality);
    }

    public static bool operator !=(Set<T> A, Set<T> B)
    {
        return CheckSets(A, B, SetOperation.Inequality);
    }

    public override bool Equals(object o)
    {
        return CheckSets(this, (Set<T>)o, SetOperation.Equality);
    }

    //*** Methods ***

    public void Add(T key)
    {
        if (Root == null)
        {
            Root = new SetNode<T>(key, Header);
            LeftMost = RightMost = Root;
        }
        else
        {
            SetNode<T> Search = Root;
            for (; ; )
            {
                int Compare = Comparer.Compare(key, Search.Data);

                if (Compare == 0) // Item Exists
                    throw new EntryAlreadyExistsException();

                else if (Compare < 0)
                {
                    if (Search.Left != null)
                        Search = (SetNode<T>)Search.Left;
                    else
                    {
                        Search.Left = new SetNode<T>(key, Search);
                        if (LeftMost == Search) LeftMost = (SetNode<T>)Search.Left;
                        Utility.BalanceSet(Search, Direction.FromLeft);
                        Nodes++;
                        break;
                    }
                }

                else
                {
                    if (Search.Right != null)
                        Search = (SetNode<T>)Search.Right;
                    else
                    {
                        Search.Right = new SetNode<T>(key, Search);
                        if (RightMost == Search) RightMost = (SetNode<T>)Search.Right;
                        Utility.BalanceSet(Search, Direction.FromRight);
                        Nodes++;
                        break;
                    }
                }
            }
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    { return new SetEntry<T>(Header); }

    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    { return new SetEntry<T>(Header); }

    public override int GetHashCode()
    {
        return GetHashCode((SetNode<T>)Header.Parent);
    }

    int GetHashCode(SetNode<T> Root)
    {
        if (Root != null)
        {
            int HashCode = Root.GetHashCode();

            if (Root.Left != null)
                HashCode += GetHashCode((SetNode<T>)Root.Left);

            if (Root.Right != null)
                HashCode += GetHashCode((SetNode<T>)Root.Right);

            return HashCode;
        }

        return 0;
    }

    public void Remove(T key)
    {
        SetNode<T> root = Root;

        for (; ; )
        {
            if (root == null)
                throw new EntryNotFoundException();

            int Compare = Comparer.Compare(key, root.Data);

            if (Compare < 0)
                root = (SetNode<T>)root.Left;

            else if (Compare > 0)
                root = (SetNode<T>)root.Right;

            else // Item is found
            {
                if (root.Left != null && root.Right != null)
                {
                    SetNode<T> replace = (SetNode<T>)root.Left;
                    while (replace.Right != null) replace = (SetNode<T>)replace.Right;
                    Utility.SwapNodes(root, replace);
                }

                SetNode<T> Parent = (SetNode<T>)root.Parent;

                Direction From = (Parent.Left == root) ? Direction.FromLeft : Direction.FromRight;

                if (LeftMost == root)
                {
                    SetEntry<T> e = new SetEntry<T>(root); e.MoveNext();

                    if (e._Node.IsHeader)
                    { LeftMost = Header; RightMost = Header; }
                    else
                        LeftMost = e._Node;
                }
                else if (RightMost == root)
                {
                    SetEntry<T> e = new SetEntry<T>(root); e.MovePrevious();

                    if (e._Node.IsHeader)
                    { LeftMost = Header; RightMost = Header; }
                    else
                        RightMost = e._Node;
                }

                if (root.Left == null)
                {
                    if (Parent == Header)
                        Header.Parent = root.Right;
                    else if (Parent.Left == root)
                        Parent.Left = root.Right;
                    else
                        Parent.Right = root.Right;

                    if (root.Right != null) root.Right.Parent = Parent;
                }
                else
                {
                    if (Parent == Header)
                        Header.Parent = root.Left;
                    else if (Parent.Left == root)
                        Parent.Left = root.Left;
                    else
                        Parent.Right = root.Left;

                    if (root.Left != null) root.Left.Parent = Parent;
                }

                Utility.BalanceSetRemove(Parent, From);
                Nodes--;
                break;
            }
        }
    }

    public bool Search(T key)
    {
        if (Root == null)
            return false;
        else
        {
            SetNode<T> Search = Root;

            do
            {
                int Result = Comparer.Compare(key, Search.Data);

                if (Result < 0) Search = (SetNode<T>)Search.Left;

                else if (Result > 0) Search = (SetNode<T>)Search.Right;

                else break;

            } while (Search != null);

            if (Search == null)
                return false;
            else
                return true;
        }
    }

    public override string ToString()
    {
        string StringOut = "{";

        SetEntry<T> start = Begin;
        SetEntry<T> end = End;
        SetEntry<T> last = End - 1;

        while (start != end)
        {
            string new_StringOut = start.Value.ToString();
            if (start != last) new_StringOut = new_StringOut + ",";
            StringOut = StringOut + new_StringOut;
            ++start;
        }

        StringOut = StringOut + "}";
        return StringOut;
    }

    public void Validate()
    {
        if (Nodes == 0 || Root == null)
        {
            if (Nodes != 0) { throw new InvalidEmptyTreeException(); }
            if (Root != null) { throw new InvalidEmptyTreeException(); }
            if (LeftMost != Header) { throw new InvalidEndItemException(); }
            if (RightMost != Header) { throw new InvalidEndItemException(); }
        }

        Validate(Root);

        if (Root != null)
        {
            SetNode<T> x = Root;
            while (x.Left != null) x = (SetNode<T>)x.Left;

            if (LeftMost != x) throw new InvalidEndItemException();

            SetNode<T> y = Root;
            while (y.Right != null) y = (SetNode<T>)y.Right;

            if (RightMost != y) throw new InvalidEndItemException();
        }
    }

    void Validate(SetNode<T> root)
    {
        if (root == null) return;

        if (root.Left != null)
        {
            SetNode<T> Left = (SetNode<T>)root.Left;

            if (Comparer.Compare(Left.Data, root.Data) >= 0)
                throw new OutOfKeyOrderException();

            if (Left.Parent != root)
                throw new TreeInvalidParentException();

            Validate((SetNode<T>)root.Left);
        }

        if (root.Right != null)
        {
            SetNode<T> Right = (SetNode<T>)root.Right;

            if (Comparer.Compare(Right.Data, root.Data) <= 0)
                throw new OutOfKeyOrderException();

            if (Right.Parent != root)
                throw new TreeInvalidParentException();

            Validate((SetNode<T>)root.Right);
        }

        ulong depth_Left = root.Left != null ? Utility.Depth(root.Left) : 0;
        ulong depth_Right = root.Right != null ? Utility.Depth(root.Right) : 0;

        if (depth_Left > depth_Right && depth_Left - depth_Right > 2)
            throw new TreeOutOfBalanceException();

        if (depth_Left < depth_Right && depth_Right - depth_Left > 2)
            throw new TreeOutOfBalanceException();
    }

    public static void CombineSets(Set<T> A,
                                   Set<T> B,
                                   Set<T> R,
                                   SetOperation operation)
    {
        IComparer<T> TComparer = R.Comparer;
        SetEntry<T> First1 = A.Begin;
        SetEntry<T> Last1 = A.End;
        SetEntry<T> First2 = B.Begin;
        SetEntry<T> Last2 = B.End;

        switch (operation)
        {
            case SetOperation.Union:
                while (First1 != Last1 && First2 != Last2)
                {
                    int Order = TComparer.Compare(First1.Value, First2.Value);

                    if (Order < 0)
                    {
                        R.Add(First1.Value);
                        First1.MoveNext();
                    }

                    else if (Order > 0)
                    {
                        R.Add(First2.Value);
                        First2.MoveNext();
                    }

                    else
                    {
                        R.Add(First1.Value);
                        First1.MoveNext();
                        First2.MoveNext();
                    }
                }
                while (First1 != Last1)
                {
                    R.Add(First1.Value);
                    First1.MoveNext();
                }
                while (First2 != Last2)
                {
                    R.Add(First2.Value);
                    First2.MoveNext();
                }
                return;

            case SetOperation.Intersection:
                while (First1 != Last1 && First2 != Last2)
                {
                    int Order = TComparer.Compare(First1.Value, First2.Value);

                    if (Order < 0)
                        First1.MoveNext();

                    else if (Order > 0)
                        First2.MoveNext();

                    else
                    {
                        R.Add(First1.Value);
                        First1.MoveNext();
                        First2.MoveNext();
                    }
                }
                return;

            case SetOperation.SymmetricDifference:
                while (First1 != Last1 && First2 != Last2)
                {
                    int Order = TComparer.Compare(First1.Value, First2.Value);

                    if (Order < 0)
                    {
                        R.Add(First1.Value);
                        First1.MoveNext();
                    }

                    else if (Order > 0)
                    {
                        R.Add(First2.Value);
                        First2.MoveNext();
                    }

                    else
                    { First1.MoveNext(); First2.MoveNext(); }
                }

                while (First1 != Last1)
                {
                    R.Add(First1.Value);
                    First1.MoveNext();
                }

                while (First2 != Last2)
                {
                    R.Add(First2.Value);
                    First2.MoveNext();
                }
                return;

            case SetOperation.Difference:
                while (First1 != Last1 && First2 != Last2)
                {
                    int Order = TComparer.Compare(First1.Value, First2.Value);

                    if (Order < 0)
                    {
                        R.Add(First1.Value);
                        First1.MoveNext();
                    }

                    else if (Order > 0)
                    {
                        R.Add(First1.Value);
                        First1.MoveNext();
                        First2.MoveNext();
                    }

                    else
                    { First1.MoveNext(); First2.MoveNext(); }
                }

                while (First1 != Last1)
                {
                    R.Add(First1.Value);
                    First1.MoveNext();
                }
                return;
        }

        throw new InvalidSetOperationException();
    }

    public static bool CheckSets(Set<T> A,
                                 Set<T> B,
                                 SetOperation operation)
    {
        IComparer<T> TComparer = A.Comparer;
        SetEntry<T> First1 = A.Begin;
        SetEntry<T> Last1 = A.End;
        SetEntry<T> First2 = B.Begin;
        SetEntry<T> Last2 = B.End;

        switch (operation)
        {
            case SetOperation.Equality:
            case SetOperation.Inequality:
                {
                    bool Equals = true;

                    while (First1 != Last1 && First2 != Last2)
                    {
                        if (TComparer.Compare(First1.Value, First2.Value) == 0)
                        { First1.MoveNext(); First2.MoveNext(); }
                        else
                        { Equals = false; break; }
                    }

                    if (Equals)
                    {
                        if (First1 != Last1) Equals = false;
                        if (First2 != Last2) Equals = false;
                    }

                    if (operation == SetOperation.Equality)
                        return Equals;
                    else
                        return !Equals;
                }

            case SetOperation.Subset:
            case SetOperation.Superset:
                {
                    bool Subset = true;

                    while (First1 != Last1 && First2 != Last2)
                    {
                        int Order = TComparer.Compare(First1.Value, First2.Value);

                        if (Order < 0)
                        { Subset = false; break; }

                        else if (Order > 0)
                            First2.MoveNext();

                        else
                        { First1.MoveNext(); First2.MoveNext(); }
                    }

                    if (Subset)
                        if (First1 != Last1) Subset = false;

                    if (operation == SetOperation.Subset)
                        return Subset;
                    else
                        return !Subset;
                }
        }

        throw new InvalidSetOperationException();
    }
}

public class EntryNotFoundException : Exception
{
    static String message = "The requested entry could not be located in the specified collection.";

    public EntryNotFoundException() : base(message) { }
}

public class EntryAlreadyExistsException : Exception
{
    static String message = "The requested entry already resides in the collection.";

    public EntryAlreadyExistsException() : base(message) { }
}

public class InvalidEndItemException : Exception
{
    static String message = "The validation routines detected that the end item of a tree is invalid.";

    public InvalidEndItemException() : base(message) { }
}

public class InvalidEmptyTreeException : Exception
{
    static String message = "The validation routines detected that an empty tree is invalid.";

    public InvalidEmptyTreeException() : base(message) { }
}

public class OutOfKeyOrderException : Exception
{
    static String message = "A trees was found to be out of key order.";

    public OutOfKeyOrderException() : base(message) { }
}

public class TreeInvalidParentException : Exception
{
    static String message = "The validation routines detected that the Parent structure of a tree is invalid.";

    public TreeInvalidParentException() : base(message) { }
}

public class TreeOutOfBalanceException : Exception
{
    static String message = "The validation routines detected that the tree is out of State.";

    public TreeOutOfBalanceException() : base(message) { }
}

public class InvalidSetOperationException : Exception
{
    static String message = "An invalid set operation was requested.";

    public InvalidSetOperationException() : base(message) { }
}

class Program
{
    static void Main()
    {
        Set<string> s = new Set<string>() {"S0","S1","S2","S3","S4",
                                           "S5","S6","S7","S8","S9"};

        Console.WriteLine("Depth = {0}", s.Depth);

        s.Validate();

        for (int i = 0; i < 10; i += 2)
            s.Remove("S" + i.ToString());

        Console.WriteLine("Depth = {0}", s.Depth);

        s.Validate();

        Console.WriteLine("{0}", s);

        Set<int> A = new Set<int>() { 1, 3, 5, 7 };
        Set<int> B = new Set<int>() { 2, 4, 6, 8 };

        Set<int> U = A | B;

        Console.WriteLine("{0} | {1} == {2}", A, B, U);
    }
}

implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures that lookup, insertion, and deletion operations take O(log n) time in both average and worst cases. The tree is rebalanced after insertions and deletions through one or more tree rotations. Duplicate node keys are not allowed. The AVL tree is compared with red-black trees in terms of operations and time complexity.


Works with: C sharp version 6
using System;
public class CirclesOfGivenRadiusThroughTwoPoints
{
    public static void Main()
    {
        double[][] values = new double[][] {
            new [] { 0.1234, 0.9876, 0.8765, 0.2345,   2 },
            new [] { 0.0,       2.0,    0.0,    0.0,   1 },
            new [] { 0.1234, 0.9876, 0.1234, 0.9876,   2 },
            new [] { 0.1234, 0.9876, 0.8765, 0.2345, 0.5 },
            new [] { 0.1234, 0.9876, 0.1234, 0.9876,   0 }
        };

        foreach (var a in values) {
            var p = new Point(a[0], a[1]);
            var q = new Point(a[2], a[3]);
            Console.WriteLine($"Points {p} and {q} with radius {a[4]}:");
            try {
                var centers = FindCircles(p, q, a[4]);
                Console.WriteLine("\t" + string.Join(" and ", centers));
            } catch (Exception ex) {
                Console.WriteLine("\t" + ex.Message);
            }
        }
    }

    static Point[] FindCircles(Point p, Point q, double radius) {
        if(radius < 0) throw new ArgumentException("Negative radius.");
        if(radius == 0) {
            if(p == q) return new [] { p };
            else throw new InvalidOperationException("No circles.");
        }
        if (p == q) throw new InvalidOperationException("Infinite number of circles.");

        double sqDistance = Point.SquaredDistance(p, q);
        double sqDiameter = 4 * radius * radius;
        if (sqDistance > sqDiameter) throw new InvalidOperationException("Points are too far apart.");

        Point midPoint = new Point((p.X + q.X) / 2, (p.Y + q.Y) / 2);
        if (sqDistance == sqDiameter) return new [] { midPoint };

        double d = Math.Sqrt(radius * radius - sqDistance / 4);
        double distance = Math.Sqrt(sqDistance);
        double ox = d * (q.X - p.X) / distance, oy = d * (q.Y - p.Y) / distance;
        return new [] {
            new Point(midPoint.X - oy, midPoint.Y + ox),
            new Point(midPoint.X + oy, midPoint.Y - ox)
        };
    }

    public struct Point
    {
        public Point(double x, double y) : this() {
            X = x;
            Y = y;
        }

        public double X { get; }
        public double Y { get; }

        public static bool operator ==(Point p, Point q) => p.X == q.X && p.Y == q.Y;
        public static bool operator !=(Point p, Point q) => p.X != q.X || p.Y != q.Y;

        public static double SquaredDistance(Point p, Point q) {
            double dx = q.X - p.X, dy = q.Y - p.Y;
            return dx * dx + dy * dy;
        }

        public override string ToString() => $"({X}, {Y})";

    }
}

"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned."


class Program
{
    static void Main(string[] args)
    {
        Random random = new Random();
        while (true)
        {
            int a = random.Next(20);
            Console.WriteLine(a);
            if (a == 10)
                break;
            int b = random.Next(20)
            Console.WriteLine(b);
        }

        Console.ReadLine();
    }
}

generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.


using System;

namespace prog
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			int q = 929;
			if ( !isPrime(q) ) return;
			int r = q;
			while( r > 0 )
				r <<= 1;
			int d = 2 * q + 1;
			do
			{
				int i = 1;
				for( int p=r; p!=0; p<<=1 )
				{
					i = (i*i) % d;
					if (p < 0) i *= 2;
					if (i > d) i -= d;
				}
				if (i != 1) d += 2 * q; else break;
			}
			while(true);

			Console.WriteLine("2^"+q+"-1 = 0 (mod "+d+")");
		}

		static bool isPrime(int n)
		{
			if ( n % 2 == 0 ) return n == 2;
			if ( n % 3 == 0 ) return n == 3;
			int d = 5;
			while( d*d <= n )
			{
				if ( n % d == 0 ) return false;
				d += 2;
				if ( n % d == 0 ) return false;
				d += 4;
			}
			return true;
		}
	}
}

implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.


XmlReader XReader;

// Either read the xml from a string ...
XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>"));

// ... or read it from the file system.
XReader = XmlReader.Create("xmlfile.xml");

// Create a XPathDocument object (which implements the IXPathNavigable interface)
// which is optimized for XPath operation. (very fast).
IXPathNavigable XDocument = new XPathDocument(XReader);

// Create a Navigator to navigate through the document.
XPathNavigator Nav = XDocument.CreateNavigator();
Nav = Nav.SelectSingleNode("//item");

// Move to the first element of the selection. (if available).
if(Nav.MoveToFirst())
{
  Console.WriteLine(Nav.OuterXml); // The outer xml of the first item element.
}

// Get an iterator to loop over multiple selected nodes.
XPathNodeIterator Iterator = XDocument.CreateNavigator().Select("//price");

while (Iterator.MoveNext())
{
  Console.WriteLine(Iterator.Current.Value);
}

Iterator = XDocument.CreateNavigator().Select("//name");

// Use a generic list.
List<string> NodesValues = new List<string>();

while (Iterator.MoveNext())
{
  NodesValues.Add(Iterator.Current.Value);
}

// Convert the generic list to an array and output the count of items.
Console.WriteLine(NodesValues.ToArray().Length);

1. Retrieves the first "item" element from the XML document.
2. Prints out each "price" element from the XML document.
3. Gets an array of all the "name" elements from the XML document.


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

class Program
{
    static void PrintCollection(IEnumerable<int> x)
    {
        Console.WriteLine(string.Join(" ", x));
    }
    static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.UTF8;
        Console.WriteLine("Set creation");
        var A = new HashSet<int> { 4, 12, 14, 17, 18, 19, 20 };
        var B = new HashSet<int> { 2, 5, 8, 11, 12, 13, 17, 18, 20 };

        PrintCollection(A);
        PrintCollection(B);

        Console.WriteLine("Test m ∈ S -- \"m is an element in set S\"");
        Console.WriteLine("14 is an element in set A: {0}", A.Contains(14));
        Console.WriteLine("15 is an element in set A: {0}", A.Contains(15));

        Console.WriteLine("A ∪ B -- union; a set of all elements either in set A or in set B.");
        var aUb = A.Union(B);
        PrintCollection(aUb);

        Console.WriteLine("A ∖ B -- difference; a set of all elements in set A, except those in set B.");
        var aDb = A.Except(B);
        PrintCollection(aDb);

        Console.WriteLine("A ⊆ B -- subset; true if every element in set A is also in set B.");
        Console.WriteLine(A.IsSubsetOf(B));
        var C = new HashSet<int> { 14, 17, 18 };
        Console.WriteLine(C.IsSubsetOf(A));

        Console.WriteLine("A = B -- equality; true if every element of set A is in set B and vice versa.");
        Console.WriteLine(A.SetEquals(B));
        var D = new HashSet<int> { 4, 12, 14, 17, 18, 19, 20 };
        Console.WriteLine(A.SetEquals(D));

        Console.WriteLine("If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B");
        Console.WriteLine(A.IsProperSubsetOf(B));
        Console.WriteLine(C.IsProperSubsetOf(A));

        Console.WriteLine("Modify a mutable set.  (Add 10 to A; remove 12 from B).");
        A.Add(10);
        B.Remove(12);
        PrintCollection(A);
        PrintCollection(B);

        Console.ReadKey();
    }
}

demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.


using System;

class Program
{
    static void Main(string[] args)
    {
        for (int i = 2008; i <= 2121; i++)
        {
            DateTime date = new DateTime(i, 12, 25);
            if (date.DayOfWeek == DayOfWeek.Sunday)
            {
                Console.WriteLine(date.ToString("dd MMM yyyy"));
            }
        }
    }
}

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        string[] days = Enumerable.Range(2008, 2121 - 2007)
            .Select(year => new DateTime(year, 12, 25))
            .Where(day => day.DayOfWeek == DayOfWeek.Sunday)
            .Select(day => day.ToString("dd MMM yyyy")).ToArray();

        foreach (string day in days) Console.WriteLine(day);
    }
}
Lambda expressions FTW:
using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        Enumerable.Range(2008, 113).ToList()
        .ConvertAll(ent => new DateTime(ent, 12, 25))
        .Where(ent => ent.DayOfWeek.Equals(DayOfWeek.Sunday)).ToList()
        .ForEach(ent => Console.WriteLine(ent.ToString("dd MMM yyyy")));
    }
}

The code calculates the years between 2008 and 2121 when Christmas (25th December) falls on a Sunday using standard date handling libraries. It also compares the results with outputs from other programming languages to identify any anomalies in date/time representation, possibly due to issues similar to the Y2K problem. The code uses LINQ for this task.


Library: Math.Net
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;

class Program
{

    static void Main(string[] args)
    {
        Matrix<double> A = DenseMatrix.OfArray(new double[,]
        {
                {  12,  -51,    4 },
                {   6,  167,  -68 },
                {  -4,   24,  -41 }
        });
        Console.WriteLine("A:");
        Console.WriteLine(A);
        var qr = A.QR();
        Console.WriteLine();
        Console.WriteLine("Q:");
        Console.WriteLine(qr.Q);
        Console.WriteLine();
        Console.WriteLine("R:");
        Console.WriteLine(qr.R);
    }
}

The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.


Works with: C# version 2+
int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
    if (!unique.Contains(n))
        unique.Add(n);

Works with: C# version 3+
int[] nums = {1, 1, 2, 3, 4, 4};
int[] unique = nums.Distinct().ToArray();

implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.