Translation of: Python
import std.stdio, std.typecons, std.math;

class ValueException : Exception {
    this(string msg_) pure { super(msg_); }
}

struct V2 { double x, y; }
struct Circle { double x, y, r; }

/**Following explanation at:
http://mathforum.org/library/drmath/view/53027.html
*/
Tuple!(Circle, Circle)
circlesFromTwoPointsAndRadius(in V2 p1, in V2 p2, in double r)
pure in {
    assert(r >= 0, "radius can't be negative");
} body {
    enum nBits = 40;

    if (r.abs < (1.0 / (2.0 ^^ nBits)))
        throw new ValueException("radius of zero");

    if (feqrel(p1.x, p2.x) >= nBits &&
        feqrel(p1.y, p2.y) >= nBits)
        throw new ValueException("coincident points give" ~
                                 " infinite number of Circles");

    // Delta between points.
    immutable d = V2(p2.x - p1.x, p2.y - p1.y);

    // Distance between points.
    immutable q = sqrt(d.x ^^ 2 + d.y ^^ 2);
    if (q > 2.0 * r)
        throw new ValueException("separation of points > diameter");

    // Halfway point.
    immutable h = V2((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);

    // Distance along the mirror line.
    immutable dm = sqrt(r ^^ 2 - (q / 2) ^^ 2);

    return typeof(return)(
        Circle(h.x - dm * d.y / q, h.y + dm * d.x / q, r.abs),
        Circle(h.x + dm * d.y / q, h.y - dm * d.x / q, r.abs));
}

void main() {
    foreach (immutable t; [
                 tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0),
                 tuple(V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0),
                 tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0),
                 tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5),
                 tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0)]) {
        writefln("Through points:\n  %s   %s  and radius %f\n" ~
                 "You can construct the following circles:", t[]);
        try {
            writefln("  %s\n  %s\n",
                     circlesFromTwoPointsAndRadius(t[])[]);
        } catch (ValueException v)
            writefln("  ERROR: %s\n", v.msg);
    }
}

"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."


Translation of: C
Translation of: Go
import std.stdio, std.range, std.algorithm;

/// Rotate uint left.
uint rol(in uint x, in uint nBits) @safe pure nothrow @nogc {
    return (x << nBits) | (x >> (32 - nBits));
}

alias Nibble = ubyte; // 4 bits used.
alias SBox = immutable Nibble[16][8];

private bool _validateSBox(in SBox data) @safe pure nothrow @nogc {
    foreach (const ref row; data)
        foreach (ub; row)
            if (ub >= 16) // Verify it's a nibble.
                return false;
    return true;
}

struct GOST(s...) if (s.length == 1 && s[0]._validateSBox) {
    private static generate(ubyte k)() @safe pure nothrow {
        return k87.length.iota
               .map!(i=> (s[0][k][i >> 4] << 4) | s[0][k - 1][i & 0xF])
               .array;
    }

    private uint[2] buffer;
    private static immutable ubyte[256] k87 = generate!7,
                                        k65 = generate!5,
                                        k43 = generate!3,
                                        k21 = generate!1;

    // Endianess problems?
    private static uint f(in uint x) pure nothrow @nogc @safe {
        immutable uint y = (k87[(x >> 24) & 0xFF] << 24) |
                           (k65[(x >> 16) & 0xFF] << 16) |
                           (k43[(x >>  8) & 0xFF] <<  8) |
                            k21[ x        & 0xFF];
        return rol(y, 11);
    }

    // This performs only a step of the encoding.
    public void mainStep(in uint[2] input, in uint key)
    pure nothrow @nogc @safe {
        buffer[0] = f(key + input[0]) ^ input[1];
        buffer[1] = input[0];
    }
}

void main() {
    // S-boxes used by the Central Bank of Russian Federation:
    // http://en.wikipedia.org/wiki/GOST_28147-89
    // (This is a matrix of nibbles).
    enum SBox cbrf = [
      [ 4, 10,  9,  2, 13,  8,  0, 14,  6, 11,  1, 12,  7, 15,  5,  3],
      [14, 11,  4, 12,  6, 13, 15, 10,  2,  3,  8,  1,  0,  7,  5,  9],
      [ 5,  8,  1, 13, 10,  3,  4,  2, 14, 15, 12,  7,  6,  0,  9, 11],
      [ 7, 13, 10,  1,  0,  8,  9, 15, 14,  4,  6, 12, 11,  2,  5,  3],
      [ 6, 12,  7,  1,  5, 15, 13,  8,  4, 10,  9, 14,  0,  3, 11,  2],
      [ 4, 11, 10,  0,  7,  2,  1, 13,  3,  6,  8,  5,  9, 12, 15, 14],
      [13, 11,  4,  1,  3, 15,  5,  9,  0, 10, 14,  7,  6,  8,  2, 12],
      [ 1, 15, 13,  0,  5,  7, 10,  4,  9,  2,  3, 14,  6, 11,  8, 12]];

    GOST!cbrf g;

    // Example from the talk page (bytes swapped for endianess):
    immutable uint[2] input = [0x_04_3B_04_21, 0x_04_32_04_30];
    immutable uint key = 0x_E2_C1_04_F9;

    g.mainStep(input, key);
    writefln("%(%08X %)", g.buffer);
}

Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.


import std.stdio, std.random;

void main() {
    while (true) {
        int r = uniform(0, 20);
        write(r, " ");
        if (r == 10)
            break;
        write(uniform(0, 20), " ");
    }
}

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.


import std.stdio, std.math, std.traits;

ulong mersenneFactor(in ulong p) pure nothrow @nogc {
    static bool isPrime(T)(in T n) pure nothrow @nogc {
        if (n < 2 || n % 2 == 0)
            return n == 2;
        for (Unqual!T i = 3; i ^^ 2 <= n; i += 2)
            if (n % i == 0)
                return false;
        return true;
    }

    static ulong modPow(in ulong cb, in ulong ce,in ulong m)
    pure nothrow @nogc {
        ulong b = cb;
        ulong result = 1;
        for (ulong e = ce; e > 0; e >>= 1) {
            if ((e & 1) == 1)
                result = (result * b) % m;
            b = (b ^^ 2) % m;
        }
        return result;
    }

    immutable ulong limit = p <= 64 ? cast(ulong)(real(2.0) ^^ p - 1).sqrt : uint.max; // prevents silent overflows
    for (ulong k = 1; (2 * p * k + 1) < limit; k++) {
        immutable ulong q = 2 * p * k + 1;
        if ((q % 8 == 1 || q % 8 == 7) && isPrime(q) &&
            modPow(2, p, q) == 1)
            return q;
    }
    return 1; // returns a sensible smallest factor
}

void main() {
    writefln("Factor of M929: %d", 929.mersenneFactor);
}

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.


Library: KXML
import kxml.xml;
char[]xmlinput =
"<inventory title=\"OmniCorp Store #45x10^3\">

    <item upc=\"123456789\" stock=\"12\">
      <name>Invisibility Cream</name>
      <price>14.50</price>
      <description>Makes you invisible</description>
    </item>
    <item upc=\"445322344\" stock=\"18\">
      <name>Levitation Salve</name>
      <price>23.99</price>
      <description>Levitate yourself for up to 3 hours per application</description>
    </item>

    <item upc=\"485672034\" stock=\"653\">
      <name>Blork and Freen Instameal</name>
      <price>4.95</price>
      <description>A tasty meal in a tablet; just add water</description>
    </item>
    <item upc=\"132957764\" stock=\"44\">
      <name>Grob winglets</name>
      <price>3.56</price>
      <description>Tender winglets of Grob. Just add water</description>
    </item>

</inventory>
";
void main() {
        auto root = readDocument(xmlinput);
        auto firstitem = root.parseXPath("inventory/section/item")[0];
        foreach(price;root.parseXPath("inventory/section/item/price")) {
                std.stdio.writefln("%s",price.getCData);
        }
        auto namearray = root.parseXPath("inventory/section/item/name");
}

The code retrieves the first "item" element, prints out each "price" element, and creates an array of all the "name" elements from an XML document representing an inventory of OmniCorp Store. Note that the KXML library used for this task has limited XPath support.


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

    // Not true sets, items can be repeated, but must be sorted.
    auto s1 = [1, 2, 3, 4, 5, 6].assumeSorted;
    auto s2 = [2, 5, 6, 3, 4, 8].sort(); // [2,3,4,5,6,8].
    auto s3 = [1, 2, 5].assumeSorted;

    assert(s1.canFind(4)); // Linear search.
    assert(s1.contains(4)); // Binary search.
    assert(s1.setUnion(s2).equal([1,2,2,3,3,4,4,5,5,6,6,8]));
    assert(s1.setIntersection(s2).equal([2, 3, 4, 5, 6]));
    assert(s1.setDifference(s2).equal([1]));
    assert(s1.setSymmetricDifference(s2).equal([1, 8]));
    assert(s3.setDifference(s1).empty); // It's a subset.
    assert(!s1.equal(s2));

    auto s4 = [[1, 4, 7, 8], [1, 7], [1, 7, 8], [4], [7]];
    const s5 = [1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8];
    assert(s4.nWayUnion.equal(s5));
}
 ==D==
module set;
import std.typecons : Tuple, tuple;
struct Set(V) { // Limited set of V-type elements                                        // here 'this' is named A, s is B, v V-type item

protected V[] array;

	this(const Set s) {                                                              // construct A by copy of B
		array = s.array.dup;
	}

	this(V[] arg...){                                                                // construct A with items
		foreach(v; arg) if (v.isNotIn(array)) array ~= v;
	}

	enum : Set { empty = Set() }                                                     // ∅

	ref Set opAssign()(const Set s) {                                                // A = B
		array = s.array.dup;
		return this;
	}

	bool opBinaryRight(string op : "in")(const V v) const {                          // v ∈ A
		return v.isIn(array);
	}

	ref Set opOpAssign(string op)(const V v) if (op == "+" || op == "|") {           // A += {v}          // + = ∪ = |
		if (v.isIn(array)) return this;
		array ~= v;
		return this;
	}

	ref Set opOpAssign(string op)(const Set s) if (op == "+" || op == "|") {         // A += B
		foreach(x; s.array) if (x.isNotIn(array)) array ~= x;
		return this;
	}

	Set opBinary(string op)(const V v) const if (op == "+" || op == "|"){            // A + {v}
		Set result = this;
		result += v;
		return result;
	}

	Set opBinaryRight(string op)(const V v) const if (op == "+" || op == "|") {      // {v} + A
		Set result = this;
		result += v;
		return result;
	}

	Set opBinary(string op)(const Set s) const if (op == "+" || op == "|") {         // A + B
		Set result = this;
		result += s;
		return result;
	}

	Set opBinary(string op : "&")(const Set s) const{                                // A ∩ B               // ∩ = &
		Set result;
		foreach(x; array) if(x.isIn(s.array)) result += x;
		return result;
	}

	ref Set opOpAssign(string op : "&")(const Set s) {                               // A ∩= B
		return this(this & s);
	}

	Set opBinary(string op : "^")(const Set s) const {                               // (A ∪ B) - (A ∩ B)    //  = A ^ B
		Set result;
		foreach(x; array) if (x.isNotIn(s.array)) result += x;
		foreach(x; s.array) if(x.isNotIn(array)) result += x;
		return result;
	}

	ref opOpAssign(string op : "^")(const Set s) {
		return this = this ^ s;
	}

	Set opBinary(string op : "-")(const Set s) const {                                // A - B
		Set r;
		foreach(x; array) if(x.isNot(s.array)) r += x;
		return r;
	}

	ref Set opOpAssign(string op : "-")(const Set s) {                                // A -= B
		return this = this - s;
	}

	Set!(Tuple!(V,U)) opBinary(U, string op : "*")(const Set!U s) const {             // A × B = { (x, y) | ∀x ∈ A ∧ ∀y ∈ B }
		Set!(Tuple!(V, U)) r;
		foreach(x; array) foreach(y; s.array) r += tuple(x, y);
		return r;
	}

	bool isEmpty() const { return !array.length;}                                     // A ≟ ∅

	bool opBinary(string op : "in")(const Set s) const {                              // A ⊂ s
		foreach(v; array) if(v.isNotIn(s.array)) return false;
		return true;
	}

	bool opEquals(const Set s) const {                                                // A ≟ B
		if (array.length != s.array.length) return false;
		return this in s;
	}

	T[] array() const @property { return array.dup;}

}

Set!(Tuple!(T, T)) sqr(T)(const Set!T s) { return s * s; }                                 // A²

auto pow(T, uint n : 0)(const Set!T s) {                                                   // A ^ 0
	return Set!T.empty;
}

auto pow(T, uint n : 1)(const Set!T s) {                                                   // A ^ 1 = A
	return s;
}

auto pow(T, uint n : 2)(const Set!T s) {                                                   // A ^ 2 (=A²)
	return sqr!T(s);
}

auto pow(T, uint n)(const Set!T s) if(n % 2) {                                             // if n Odd,  A^n = A * (A^(n/2))²
        return s * sqr!T(pow!(T, n/2)(s));
}

auto pow(T, uint n)(const Set!T s) if(!(n % 2)) {                                           // if n Even, A^n = (A^(n/2))²
	return sqr!T(pow!(T, n/2)(s));
}

size_t Card(T)(const Set!T s) {return s.length; }                                           // Card(A)

Set!(Set!T) power(T)(Set!T s) {                                                             // ∀B ∈ P(A) ⇒ B ⊂ A
	Set!(Set!T) ret;
	foreach(e; s.array) {
		Set!(Set!T) rs;
		foreach(x; ret.array) {
			x += e;
			rs += x;
		}
		ret += rs;
	}
	return ret;
}

bool isIn(T)(T x, T[] array){
	foreach(a; array) if(a == x) return true;
	return false;
}
bool isNotIn(T)(T x, T[] array){
	foreachj(a; array) if(a == x) return false;
	return true;
}

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.


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

    writeln("Christmas comes on a Sunday in the years:\n",
            iota(2008, 2122)
            .filter!(y => Date(y, 12, 25).dayOfWeek == DayOfWeek.sun));
}

The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date/time representation, such as overflow issues similar to y2k problems.


Translation of: Common Lisp

import std.stdio, std.math, std.algorithm, std.traits,
       std.typecons, std.numeric, std.range, std.conv;

template elementwiseMat(string op) {
    T[][] elementwiseMat(T)(in T[][] A, in T B) pure nothrow {
        if (A.empty)
            return null;
        auto R = new typeof(return)(A.length, A[0].length);
        foreach (immutable r, const row; A)
            R[r][] = mixin("row[] " ~ op ~ "B");
        return R;
    }

    T[][] elementwiseMat(T, U)(in T[][] A, in U[][] B)
    pure nothrow if (is(Unqual!T == Unqual!U)) {
        assert(A.length == B.length);
        if (A.empty)
            return null;
        auto R = new typeof(return)(A.length, A[0].length);
        foreach (immutable r, const row; A) {
            assert(row.length == B[r].length);
            R[r][] = mixin("row[] " ~ op ~ "B[r][]");
        }
        return R;
    }
}

alias mSum = elementwiseMat!q{ + },
      mSub = elementwiseMat!q{ - },
      pMul = elementwiseMat!q{ * },
      pDiv = elementwiseMat!q{ / };

bool isRectangular(T)(in T[][] mat) pure nothrow {
    return mat.all!(r => r.length == mat[0].length);
}

T[][] matMul(T)(in T[][] a, in T[][] b) pure nothrow
in {
    assert(a.isRectangular && b.isRectangular &&
           a[0].length == b.length);
} body {
    auto result = new T[][](a.length, b[0].length);
    auto aux = new T[b.length];
    foreach (immutable j; 0 .. b[0].length) {
        foreach (immutable k; 0 .. b.length)
            aux[k] = b[k][j];
        foreach (immutable i; 0 .. a.length)
            result[i][j] = a[i].dotProduct(aux);
    }
    return result;
}

Unqual!T[][] transpose(T)(in T[][] m) pure nothrow {
    auto r = new Unqual!T[][](m[0].length, m.length);
    foreach (immutable nr, row; m)
        foreach (immutable nc, immutable c; row)
            r[nc][nr] = c;
    return r;
}

T norm(T)(in T[][] m) pure nothrow {
    return transversal(m, 0).map!q{ a ^^ 2 }.sum.sqrt;
}

Unqual!T[][] makeUnitVector(T)(in size_t dim) pure nothrow {
    auto result = new Unqual!T[][](dim, 1);
    foreach (row; result)
        row[] = 0;
    result[0][0] = 1;
    return result;
}

/// Return a nxn identity matrix.
Unqual!T[][] matId(T)(in size_t n) pure nothrow {
    auto Id = new Unqual!T[][](n, n);
    foreach (immutable r, row; Id) {
        row[] = 0;
        row[r] = 1;
    }
    return Id;
}

T[][] slice2D(T)(in T[][] A,
                 in size_t ma, in size_t mb,
                 in size_t na, in size_t nb) pure nothrow {
    auto B = new T[][](mb - ma + 1, nb - na + 1);
    foreach (immutable i, brow; B)
        brow[] = A[ma + i][na .. na + brow.length];
    return B;
}

size_t rows(T)(in T[][] A) pure nothrow { return A.length; }

size_t cols(T)(in T[][] A) pure nothrow {
    return A.length ? A[0].length : 0;
}

T[][] mcol(T)(in T[][] A, in size_t n) pure nothrow {
    return slice2D(A, 0, A.rows - 1, n, n);
}

T[][] matEmbed(T)(in T[][] A, in T[][] B,
                  in size_t row, in size_t col) pure nothrow {
    auto C = new T[][](rows(A), cols(A));
    foreach (immutable i, const arow; A)
        C[i][] = arow[]; // Some wasted copies.
    foreach (immutable i, const brow; B)
        C[row + i][col .. col + brow.length] = brow[];
    return C;
}

// Main routines ---------------

T[][] makeHouseholder(T)(in T[][] a) {
    immutable m = a.rows;
    immutable T s = a[0][0].sgn;
    immutable e = makeUnitVector!T(m);
    immutable u = mSum(a, pMul(e, a.norm * s));
    immutable v = pDiv(u, u[0][0]);
    immutable beta = 2.0 / v.transpose.matMul(v)[0][0];
    return mSub(matId!T(m), pMul(v.matMul(v.transpose), beta));
}

Tuple!(T[][],"Q", T[][],"R") QRdecomposition(T)(T[][] A) {
    immutable m = A.rows;
    immutable n = A.cols;
    auto Q = matId!T(m);

    // Work on n columns of A.
    foreach (immutable i; 0 .. (m == n ? n - 1 : n)) {
        // Select the i-th submatrix. For i=0 this means the original
        // matrix A.
        immutable B = slice2D(A, i, m - 1, i, n - 1);

        // Take the first column of the current submatrix B.
        immutable x = mcol(B, 0);

        // Create the Householder matrix for the column and embed it
        // into an mxm identity.
        immutable H = matEmbed(matId!T(m), x.makeHouseholder, i, i);

        // The product of all H matrices from the right hand side is
        // the orthogonal matrix Q.
        Q = Q.matMul(H);

        // The product of all H matrices with A from the LHS is the
        // upper triangular matrix R.
        A  = H.matMul(A);
    }

    // Return Q and R.
    return typeof(return)(Q, A);
}

// Polynomial regression ---------------

/// Solve an upper triangular system by back substitution.
T[][] solveUpperTriangular(T)(in T[][] R, in T[][] b) pure nothrow {
    immutable n = R.cols;
    auto x = new T[][](n, 1);

    foreach_reverse (immutable k; 0 .. n) {
        T tot = 0;
        foreach (immutable j; k + 1 .. n)
            tot += R[k][j] * x[j][0];
        x[k][0] = (b[k][0] - tot) / R[k][k];
    }

    return x;
}

/// Solve a linear least squares problem by QR decomposition.
T[][] lsqr(T)(T[][] A, in T[][] b) pure nothrow {
    const qr = A.QRdecomposition;
    immutable n = qr.R.cols;
    return solveUpperTriangular(
        slice2D(qr.R, 0, n - 1, 0, n - 1),
        slice2D(qr.Q.transpose.matMul(b), 0, n - 1, 0, 0));
}

T[][] polyFit(T)(in T[][] x, in T[][] y, in size_t n) pure nothrow {
    immutable size_t m = x.cols;
    auto A = new T[][](m, n + 1);
    foreach (immutable i, row; A)
        foreach (immutable j, ref item; row)
            item = x[0][i] ^^ j;
    return lsqr(A, y.transpose);
}

void main() {
    // immutable (Q, R) = QRdecomposition([[12.0, -51,   4],
    immutable qr = QRdecomposition([[12.0, -51,   4],
                                    [ 6.0, 167, -68],
                                    [-4.0,  24, -41]]);
    immutable form = "[%([%(%2.3f, %)]%|,\n %)]\n";
    writefln(form, qr.Q);
    writefln(form, qr.R);

    immutable x = [[0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]];
    immutable y = [[1.0, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]];
    polyFit(x, y, 2).writeln;
}

The code performs QR decomposition on a given matrix using the Householder reflections method. It decomposes the matrix into an orthogonal matrix and an upper triangular matrix. It also demonstrates the use of QR decomposition for solving linear least squares problems. The code handles cases where the matrix is not square by cutting off zero padded bottom rows. The final solution is obtained by back substitution. The code utilizes functions from Element-wise_operations, Matrix multiplication, and Matrix transposition.


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

    [1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2]
    .sort()
    .uniq
    .writeln;
}

implement three methods to remove duplicate elements from an array: 1) using a hash table, 2) sorting the elements and removing consecutive duplicates, and 3) iterating through the list and discarding any repeated elements. An additional method using an associative array is also implemented.


import std.stdio : writefln, writeln;
import std.algorithm: filter;
import std.array;

T[] quickSort(T)(T[] xs) =>
  xs.length == 0 ? [] :
    xs[1 .. $].filter!(x => x< xs[0]).array.quickSort ~
    xs[0 .. 1] ~
    xs[1 .. $].filter!(x => x>=xs[0]).array.quickSort;

void main() =>
  [4, 65, 2, -31, 0, 99, 2, 83, 782, 1].quickSort.writeln;

implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by selecting a pivot element and dividing the rest of the elements into two partitions, one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The code includes two versions of the algorithm, one that creates new arrays for the partitions and another more efficient one that sorts the array in place by swapping elements. The pivot selection method is not specified.


Works with: D version DMD 1.026
Library: Tango
module datetimedemo ;

import tango.time.Time ;
import tango.text.locale.Locale ;
import tango.time.chrono.Gregorian ;

import tango.io.Stdout ;

void main() {
    Gregorian g = new Gregorian ;
    Stdout.layout = new Locale; // enable Stdout to handle date/time format
    Time d = g.toTime(2007, 11, 10, 0, 0, 0, 0, g.AD_ERA) ;
    Stdout.format("{:yyy-MM-dd}", d).newline ;
    Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;
    d = g.toTime(2008, 2, 1, 0, 0, 0, 0, g.AD_ERA) ;
    Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;
}

display the current date in two formats: "2007-11-23" and "Friday, November 23, 2007".


import std.algorithm;
import std.range;

auto powerSet(R)(R r)
{
	return
		(1L<<r.length)
		.iota
		.map!(i =>
			r.enumerate
			.filter!(t => (1<<t[0]) & i)
			.map!(t => t[1])
		);
}

unittest
{
	int[] emptyArr;
	assert(emptyArr.powerSet.equal!equal([emptyArr]));
	assert(emptyArr.powerSet.powerSet.equal!(equal!equal)([[], [emptyArr]]));
}

void main(string[] args)
{
	import std.stdio;
	args[1..$].powerSet.each!writeln;
}

import std.range;

struct PowerSet(R)
	if (isRandomAccessRange!R)
{
	R r;
	size_t position;

	struct PowerSetItem
	{
		R r;
		size_t position;

		private void advance()
		{
			while (!(position & 1))
			{
				r.popFront();
				position >>= 1;
			}
		}

		@property bool empty() { return position == 0; }
		@property auto front()
		{
			advance();
			return r.front;
		}
		void popFront()
		{
			advance();
			r.popFront();
			position >>= 1;
		}
	}

	@property bool empty() { return position == (1 << r.length); }
	@property PowerSetItem front() { return PowerSetItem(r.save, position); }
	void popFront() { position++; }
}

auto powerSet(R)(R r) { return PowerSet!R(r); }

The code takes a set S as input and generates its power set. The power set includes all possible subsets of S, including the empty set and the set itself. For a set with n elements, the power set will have 2^n elements. The code also demonstrates the ability to handle edge cases such as the power set of an empty set and the power set of a set containing only the empty set. The implementation uses a lazy enumeration approach to generate the power set.


string toRoman(int n) pure nothrow
in {
    assert(n < 5000);
} body {
    static immutable weights = [1000, 900, 500, 400, 100, 90,
                                50, 40, 10, 9, 5, 4, 1];
    static immutable symbols = ["M","CM","D","CD","C","XC","L",
                                "XL","X","IX","V","IV","I"];

    string roman;
    foreach (i, w; weights) {
        while (n >= w) {
            roman ~= symbols[i];
            n -= w;
        }
        if (n == 0)
            break;
    }
    return roman;
} unittest {
    assert(toRoman(455)  == "CDLV");
    assert(toRoman(3456) == "MMMCDLVI");
    assert(toRoman(2488) == "MMCDLXXXVIII");
}

void main() {}

create a function that converts a positive integer into its equivalent Roman numeral representation.


// All D arrays are capable of bounds checks.

import std.stdio, core.stdc.stdlib;
import std.container: Array;

void main() {
    // GC-managed heap allocated dynamic array:
    auto array1 = new int[1];
    array1[0] = 1;
    array1 ~= 3; // append a second item
    // array1[10] = 4; // run-time error
    writeln("A) Element 0: ", array1[0]);
    writeln("A) Element 1: ", array1[1]);

    // Stack-allocated fixed-size array:
    int[5] array2;
    array2[0] = 1;
    array2[1] = 3;
    // array2[2] = 4; // compile-time error
    writeln("B) Element 0: ", array2[0]);
    writeln("B) Element 1: ", array2[1]);

    // Stack-allocated dynamic fixed-sized array,
    // length known only at run-time:
    int n = 2;
    int[] array3 = (cast(int*)alloca(n * int.sizeof))[0 .. n];
    array3[0] = 1;
    array3[1] = 3;
    // array3[10] = 4; // run-time error
    writeln("C) Element 0: ", array3[0]);
    writeln("C) Element 1: ", array3[1]);

    // Phobos-defined  heap allocated not GC-managed array:
    Array!int array4;
    array4.length = 2;
    array4[0] = 1;
    array4[1] = 3;
    // array4[10] = 4; // run-time exception
    writeln("D) Element 0: ", array4[0]);
    writeln("D) Element 1: ", array4[1]);
}

demonstrate the basic syntax of creating an array, assigning a value to it, and retrieving an element in a specific programming language. It includes both fixed-length and dynamic arrays, and shows how to push a value into the array.


Library: Phobos
Works with: D version 2
import std.file: copy;

void main() {
    copy("input.txt", "output.txt");
}

void main() {
import std.file;
auto data = std.file.read("input.txt");
std.file.write("output.txt", data);
}

import std.stdio;

int main() {
    auto from = File("input.txt", "rb");
    scope(exit) from.close();

    auto to = File("output.txt", "wb");
    scope(exit) to.close();

    foreach(buffer; from.byChunk(new ubyte[4096*1024])) {
        to.rawWrite(buffer);
    }

    return 0;
}

Library: Tango
Works with: D version 1

import tango.io.device.File;

void main()
{
    auto from = new File("input.txt");
    auto to = new File("output.txt", File.WriteCreate);
    to.copy(from).close;
    from.close;
}

import tango.io.device.File;

void main()
{
    auto to = new File("output.txt", File.WriteCreate);
    to.copy(new File("input.txt")).close;
}

demonstrate how to read content from an input file into an intermediate variable and then write this content into an output file. Exception handling is managed by Tango. The codes also include a shorter example where the output file is not explicitly closed.


void main() {
    import std.stdio, std.string;

    immutable s = "alphaBETA";
    s.toUpper.writeln;
    s.toLower.writeln;
}

demonstrate the conversion of the string "alphaBETA" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.


Compact Versions[edit]
import std.stdio, std.typecons, std.math, std.algorithm,
       std.random, std.traits, std.range, std.complex;

auto bruteForceClosestPair(T)(in T[] points) pure nothrow @nogc {
//  return pairwise(points.length.iota, points.length.iota)
//         .reduce!(min!((i, j) => abs(points[i] - points[j])));
  auto minD = Unqual!(typeof(T.re)).infinity;
  T minI, minJ;
  foreach (immutable i, const p1; points.dropBackOne)
    foreach (const p2; points[i + 1 .. $]) {
      immutable dist = abs(p1 - p2);
      if (dist < minD) {
        minD = dist;
        minI = p1;
        minJ = p2;
      }
    }
  return tuple(minD, minI, minJ);
}

auto closestPair(T)(T[] points) pure nothrow {
  static Tuple!(typeof(T.re), T, T) inner(in T[] xP, /*in*/ T[] yP)
  pure nothrow {
    if (xP.length <= 3)
      return xP.bruteForceClosestPair;
    const Pl = xP[0 .. $ / 2];
    const Pr = xP[$ / 2 .. $];
    immutable xDiv = Pl.back.re;
    auto Yr = yP.partition!(p => p.re <= xDiv);
    immutable dl_pairl = inner(Pl, yP[0 .. yP.length - Yr.length]);
    immutable dr_pairr = inner(Pr, Yr);
    immutable dm_pairm = dl_pairl[0]<dr_pairr[0] ? dl_pairl : dr_pairr;
    immutable dm = dm_pairm[0];
    const nextY = yP.filter!(p => abs(p.re - xDiv) < dm).array;

    if (nextY.length > 1) {
      auto minD = typeof(T.re).infinity;
      size_t minI, minJ;
      foreach (immutable i; 0 .. nextY.length - 1)
        foreach (immutable j; i + 1 .. min(i + 8, nextY.length)) {
          immutable double dist = abs(nextY[i] - nextY[j]);
          if (dist < minD) {
            minD = dist;
            minI = i;
            minJ = j;
          }
        }
      return dm <= minD ? dm_pairm :
                        typeof(return)(minD, nextY[minI], nextY[minJ]);
    } else
      return dm_pairm;
  }

  points.sort!q{ a.re < b.re };
  const xP = points.dup;
  points.sort!q{ a.im < b.im };
  return inner(xP, points);
}

void main() {
  alias C = complex;
  auto pts = [C(5,9), C(9,3), C(2), C(8,4), C(7,4), C(9,10), C(1,9),
              C(8,2), C(0,10), C(9,6)];
  pts.writeln;
  writeln("bruteForceClosestPair: ", pts.bruteForceClosestPair);
  writeln("          closestPair: ", pts.closestPair);

  rndGen.seed = 1;
  Complex!double[10_000] points;
  foreach (ref p; points)
    p = C(uniform(0.0, 1000.0) + uniform(0.0, 1000.0));
  writeln("bruteForceClosestPair: ", points.bruteForceClosestPair);
  writeln("          closestPair: ", points.closestPair);
}

The code provides two solutions to the Closest Pair of Points problem in a two-dimensional plane. The first function uses a brute force algorithm with a time complexity of O(n^2) to find the two points with the minimum distance between them. The second function uses a more efficient divide and conquer approach with a time complexity of O(n log n) to find the closest pair of points. The divide and conquer function sorts the points based on x and y coordinates, divides them into two halves, and recursively finds the closest pairs in each half. It then compares the closest pairs from both halves and the points lying in the strip around the dividing line to find the overall closest pair. The code also includes performance metrics for data generation and execution of both algorithms.


int[3] array;
array[0] = 5;
// array.length = 4; // compile-time error

int[] array;
array ~= 5; // append 5
array.length = 3;
array[3] = 17; // runtime error: out of bounds. check removed in release mode.
array = [2, 17, 3];
writefln(array.sort); // 2, 3, 17

int[int] array;
// array ~= 5; // it doesn't work that way!
array[5] = 17;
array[6] = 20;
// prints "[5, 6]" -> "[17, 20]" - although the order is not specified.
writefln(array.keys, " -> ", array.values);
assert(5 in array); // returns a pointer, by the way
if (auto ptr = 6 in array) writefln(*ptr); // 20

The code creates a collection in a statically-typed language, adds values to it, and reviews examples related to various types of collections such as arrays, associative arrays, linked lists, queues, sets, and stacks. It also includes the use of static, dynamic, and associative arrays in D programming language.


Translation of: Python
void main() @safe /*@nogc*/ {
    import std.stdio, std.algorithm, std.typecons, std.conv;

    static struct Bounty {
        int value;
        double weight, volume;
    }

    immutable Bounty panacea = {3000,  0.3, 0.025};
    immutable Bounty ichor =   {1800,  0.2, 0.015};
    immutable Bounty gold =    {2500,  2.0, 0.002};
    immutable Bounty sack =    {   0, 25.0, 0.25 };

    immutable maxPanacea = min(sack.weight / panacea.weight,
                               sack.volume / panacea.volume).to!int;
    immutable maxIchor   = min(sack.weight / ichor.weight,
                               sack.volume / ichor.volume).to!int;
    immutable maxGold    = min(sack.weight / gold.weight,
                               sack.volume / gold.volume).to!int;

    Bounty best = {0, 0, 0};
    Tuple!(int, int, int) bestAmounts;

    foreach (immutable nPanacea; 0 .. maxPanacea)
        foreach (immutable nIchor; 0 .. maxIchor)
            foreach (immutable nGold; 0 .. maxGold) {
                immutable Bounty current = {
                    value: nPanacea * panacea.value +
                           nIchor * ichor.value +
                           nGold * gold.value,
                    weight: nPanacea * panacea.weight +
                            nIchor * ichor.weight +
                            nGold * gold.weight,
                    volume: nPanacea * panacea.volume +
                            nIchor * ichor.volume +
                            nGold * gold.volume};

                if (current.value > best.value &&
                    current.weight <= sack.weight &&
                    current.volume <= sack.volume) {
                    best = Bounty(current.value, current.weight, current.volume);
                    bestAmounts = tuple(nPanacea, nIchor, nGold);
                }
            }

    writeln("Maximum value achievable is ", best.value);
    writefln("This is achieved by carrying (one solution) %d" ~
             " panacea, %d ichor and %d gold", bestAmounts[]);
    writefln("The weight to carry is %4.1f and the volume used is %5.3f",
             best.weight, best.volume);
}

"Calculate the maximum value of items a traveler can carry in his knapsack from Shangri La, considering the weight and volume constraints of the knapsack and the value, weight, and volume of each item. The code provides one of the four possible solutions to maximize the value taken."


Iterative[edit]
import std.stdio;

void main() {
    for (int i = 1; ; i++) {
        write(i);
        if (i >= 10)
            break;
        write(", ");
    }

    writeln();
}

The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.


Translation of: Python
import std.stdio, std.string, std.algorithm, std.range;

final class ArgumentException : Exception {
    this(string text) pure nothrow @safe /*@nogc*/ {
        super(text);
    }
}

alias TDependencies = string[][string];

string[][] topoSort(TDependencies d) pure /*nothrow @safe*/ {
    foreach (immutable k, v; d)
        d[k] = v.sort().uniq.filter!(s => s != k).array;
    foreach (immutable s; d.byValue.join.sort().uniq)
        if (s !in d)
            d[s] = [];

    string[][] sorted;
    while (true) {
        string[] ordered;

        foreach (immutable item, const dep; d)
            if (dep.empty)
                ordered ~= item;
        if (!ordered.empty)
            sorted ~= ordered.sort().release;
        else
            break;

        TDependencies dd;
        foreach (immutable item, const dep; d)
            if (!ordered.canFind(item))
                dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
        d = dd;
    }

    //if (!d.empty)
    if (d.length > 0)
        throw new ArgumentException(format(
            "A cyclic dependency exists amongst:\n%s", d));

    return sorted;
}

void main() {
    immutable data =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01           ieee dw01 dware gtech
dw02           ieee dw02 dware
dw03           std synopsys dware dw03 dw02 dw01 ieee gtech
dw04           dw04 ieee dw01 dware gtech
dw05           dw05 ieee dware
dw06           dw06 ieee dware
dw07           ieee dware
dware          ieee dware
gtech          ieee gtech
ramlib         std ieee
std_cell_lib   ieee std_cell_lib
synopsys";

    TDependencies deps;
    foreach (immutable line; data.splitLines)
        deps[line.split[0]] = line.split[1 .. $];

    auto depw = deps.dup;
    foreach (immutable idx, const subOrder; depw.topoSort)
        writefln("#%d : %s", idx + 1,  subOrder);

    writeln;
    depw = deps.dup;
    depw["dw01"] ~= "dw04";
    foreach (const subOrder; depw.topoSort) // Should throw.
        subOrder.writeln;
}

The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.


void main() {
    import std.stdio;
    import std.algorithm: startsWith, endsWith, find, countUntil;

    "abcd".startsWith("ab").writeln;      // true
    "abcd".endsWith("zn").writeln;        // false
    "abab".find("bb").writeln;            // empty array (no match)
    "abcd".find("bc").writeln;            // "bcd" (substring start
                                           //        at match)
    "abab".countUntil("bb").writeln;      // -1 (no match)
    "abab".countUntil("ba").writeln;      //  1 (index of 1st match)

    // std.algorithm.startsWith also works on arrays and ranges:
    [1, 2, 3].countUntil(3).writeln;      //  2
    [1, 2, 3].countUntil([2, 3]).writeln; //  1
}

The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.


import std.stdio;

void main() {
    fourSquare(1,7,true,true);
    fourSquare(3,9,true,true);
    fourSquare(0,9,false,false);
}

void fourSquare(int low, int high, bool unique, bool print) {
    int count;

    if (print) {
        writeln("a b c d e f g");
    }
    for (int a=low; a<=high; ++a) {
        for (int b=low; b<=high; ++b) {
            if (!valid(unique, a, b)) continue;

            int fp = a+b;
            for (int c=low; c<=high; ++c) {
                if (!valid(unique, c, a, b)) continue;
                for (int d=low; d<=high; ++d) {
                    if (!valid(unique, d, a, b, c)) continue;
                    if (fp != b+c+d) continue;

                    for (int e=low; e<=high; ++e) {
                        if (!valid(unique, e, a, b, c, d)) continue;
                        for (int f=low; f<=high; ++f) {
                            if (!valid(unique, f, a, b, c, d, e)) continue;
                            if (fp != d+e+f) continue;

                            for (int g=low; g<=high; ++g) {
                                if (!valid(unique, g, a, b, c, d, e, f)) continue;
                                if (fp != f+g) continue;

                                ++count;
                                if (print) {
                                    writeln(a,' ',b,' ',c,' ',d,' ',e,' ',f,' ',g);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (unique) {
        writeln("There are ", count, " unique solutions in [",low,",",high,"]");
    } else {
        writeln("There are ", count, " non-unique solutions in [",low,",",high,"]");
    }
}

bool valid(bool unique, int needle, int[] haystack ...) {
    if (unique) {
        foreach (value; haystack) {
            if (needle == value) {
                return false;
            }
        }
    }
    return true;
}

The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.


IMPORT STD.STDIO, STD.DATETIME, STD.STRING, STD.CONV,
       STD.ALGORITHM, STD.ARRAY;

VOID PRINT_CALENDAR(IN UINT YEAR, IN UINT COLS)
IN {
    ASSERT(COLS > 0 && COLS <= 12);
} BODY {
    STATIC ENUM CAMEL_CASE = (STRING[] PARTS) PURE =>
        PARTS[0] ~ PARTS[1 .. $].MAP!CAPITALIZE.JOIN;

    IMMUTABLE ROWS = 12 / COLS + (12 % COLS != 0);
    MIXIN("AUTO DATE = " ~ "DATE(YEAR, 1, 1);".CAPITALIZE);
    ENUM STRING S1 = CAMEL_CASE("DAY OF WEEK".SPLIT);
    MIXIN(FORMAT("AUTO OFFS = CAST(INT)DATE.%S;", S1));
    CONST MONTHS = "JANUARY FEBRUARY MARCH APRIL MAY JUNE
        JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER"
        .SPLIT.MAP!CAPITALIZE.ARRAY;

    STRING[8][12] MONS;
    FOREACH (IMMUTABLE M; 0 .. 12) {
        MONS[M][0] = MONTHS[M].CENTER(21);
        MONS[M][1] = " " ~ "SU MO TU WE TH FR SA"
                           .SPLIT.MAP!CAPITALIZE.JOIN(" ");
        ENUM STRING S2 = CAMEL_CASE("DAYS IN MONTH".SPLIT);
        MIXIN(FORMAT("IMMUTABLE DIM = DATE.%S;", S2));
        FOREACH (IMMUTABLE D; 1 .. 43) {
            IMMUTABLE DAY = D > OFFS && D <= OFFS + DIM;
            IMMUTABLE STR = DAY ? FORMAT(" %2S", D-OFFS) : "   ";
            MONS[M][2 + (D - 1) / 7] ~= STR;
        }
        OFFS = (OFFS + DIM) % 7;
        DATE.ADD!"MONTHS"(1);
    }

    FORMAT("[%S %S]", "SNOOPY".CAPITALIZE, "PICTURE".CAPITALIZE)
    .CENTER(COLS * 24 + 4).WRITELN;
    WRITELN(YEAR.TEXT.CENTER(COLS * 24 + 4), "\N");
    FOREACH (IMMUTABLE R; 0 .. ROWS) {
        STRING[8] S;
        FOREACH (IMMUTABLE C; 0 .. COLS) {
            IF (R * COLS + C > 11)
                BREAK;
            FOREACH (IMMUTABLE I, LINE; MONS[R * COLS + C])
                S[I] ~= FORMAT("   %S", LINE);
        }
        WRITEFLN("%-(%S\N%)\N", S);
    }
}

STATIC THIS() {
    PRINT_CALENDAR(1969, 3);
}

import std.string;mixin(import("CALENDAR").toLower);void main(){}

The code provides an algorithm for a calendar task, formatted to fill a 132-character wide page, inspired by 1969 era line printers. The entire code is in uppercase, as it was often mandatory in the 1960s due to character encoding limitations. The code does not include Snoopy generation but outputs a placeholder instead. The code is stored in a text file named "CALENDAR", which is then imported and mixed-in by another source code file for safety.


Lazy Functional Version[edit]

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

    enum triples = (in uint n) pure nothrow @safe /*@nogc*/ =>
        iota(1, n + 1)
        .map!(z => iota(1, z + 1)
                   .map!(x => iota(x, z + 1).map!(y => tuple(x, y, z))))
        .joiner.joiner
        .filter!(t => t[0] ^^ 2 + t[1] ^^ 2 == t[2] ^^ 2 && t[].only.sum <= n)
        .map!(t => tuple(t[0 .. 2].gcd == 1, t[]));

    auto xs = triples(100);
    writeln("Up to 100 there are ", xs.count, " triples, ",
            xs.filter!q{ a[0] }.count, " are primitive.");
}

The code determines the number of Pythagorean triples, which are sets of three positive integers that satisfy the condition a^2 + b^2 = c^2 and a < b < c. It also identifies the number of these triples that are primitive, meaning the three numbers are co-prime. The code calculates these triples for perimeters up to 100. For extra credit, the code is optimized to handle larger perimeters up to 1,000,000, 10,000,000, and 100,000,000. The performance of the code is measured in terms of run-time.


Library: FLTK4d
 module Window;

 import fltk4d.all;

 void main() {
     auto window = new Window(300, 300, "A window");
     window.show;
     FLTK.run;
 }

Library: Derelict
Library: SDL
 import derelict.sdl.sdl;

 int main(char[][] args)
 {
     DerelictSDL.load();

     SDL_Event event;
     auto done = false;

     SDL_Init(SDL_INIT_VIDEO);
     scope(exit) SDL_Quit();

     SDL_SetVideoMode(1024, 768, 0, SDL_OPENGL);
     SDL_WM_SetCaption("My first Window", "SDL test");

     while (!done)
     {
         if (SDL_PollEvent(&event) == 1)
         {
             switch (event.type)
 	     {
                 case SDL_QUIT:
 	              done = true;
 		          break;
 		 default:
 		      break;
 	     }
 	 }
     }

    return 0;
 }

Library: QD

 import qd;

 void main() {
   screen(640, 480);
   while (true) events();
 }

Create a GUI window using QD, a wrapper around SDL, which can handle close requests.


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

    uint[26] frequency;

    foreach (const buffer; "unixdict.txt".File.byChunk(2 ^^ 15))
        foreach (immutable c; buffer.filter!isAlpha)
            frequency[c.toLower - 'a']++;

    writefln("%(%(%s, %),\n%)", frequency[].chunks(10));
}

Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.


struct SLinkedNode(T) {
    T data;
    typeof(this)* next;
}

void main() {
    alias SLinkedNode!int N;
    N* n = new N(10);
}

define a data structure for a singly-linked list element. This element holds a numeric value and a mutable link to the next element. The code also includes references to various related data structures and operations, such as arrays, collections, doubly-linked lists, queues, sets, stacks, and generic template-based node elements. Additionally, it mentions the Phobos library's singly-linked list and Tango's LinkSeq collection.


SVG Version[edit]
Translation of: Raku
import std.stdio, std.math;

enum width = 1000, height = 1000; // Image dimension.
enum length = 400;                // Trunk size.
enum scale = 6.0 / 10;            // Branch scale relative to trunk.

void tree(in double x, in double y, in double length, in double angle) {
    if (length < 1)
        return;
    immutable x2 = x + length * angle.cos;
    immutable y2 = y + length * angle.sin;
    writefln("<line x1='%f' y1='%f' x2='%f' y2='%f' " ~
             "style='stroke:black;stroke-width:1'/>", x, y, x2, y2);
    tree(x2, y2, length * scale, angle + PI / 5);
    tree(x2, y2, length * scale, angle - PI / 5);
}

void main() {
    "<svg width='100%' height='100%' version='1.1'
     xmlns='http://www.w3.org/2000/svg'>".writeln;
    tree(width / 2.0, height, length, 3 * PI / 2);
    "</svg>".writeln;
}

Turtle Version[edit]

Translation of: Logo
import grayscale_image, turtle;

void tree(Color)(Image!Color img, ref Turtle t, in uint depth,
                 in real step, in real scale, in real angle) {
    if (depth == 0) return;
    t.forward(img, step);
    t.right(angle);
    img.tree(t, depth - 1, step * scale, scale, angle);
    t.left(2 * angle);
    img.tree(t, depth - 1, step * scale, scale, angle);
    t.right(angle);
    t.forward(img, -step);
}

void main() {
    auto img = new Image!Gray(330, 300);
    auto t = Turtle(165, 270, -90);
    img.tree(t, 10, 80, 0.7, 30);
    img.savePGM("fractal_tree.pgm");
}

Alternative version[edit]
Translation of: Java

import dfl.all;
import std.math;

class FractalTree: Form {

    private immutable DEG_TO_RAD = PI / 180.0;

    this() {
        width = 600;
        height = 500;
        text = "Fractal Tree";
        backColor = Color(0xFF, 0xFF, 0xFF);
        startPosition = FormStartPosition.CENTER_SCREEN;
        formBorderStyle = FormBorderStyle.FIXED_DIALOG;
        maximizeBox = false;
    }

    private void drawTree(Graphics g, Pen p, int x1, int y1, double angle, int depth) {
        if (depth == 0) return;
        int x2 = x1 + cast(int) (cos(angle * DEG_TO_RAD) * depth * 10.0);
        int y2 = y1 + cast(int) (sin(angle * DEG_TO_RAD) * depth * 10.0);
        g.drawLine(p, x1, y1, x2, y2);
        drawTree(g, p, x2, y2, angle - 20, depth - 1);
        drawTree(g, p, x2, y2, angle + 20, depth - 1);
    }

    protected override void onPaint(PaintEventArgs ea){
        super.onPaint(ea);
        Pen p = new Pen(Color(0, 0xAA, 0));
        drawTree(ea.graphics, p, 300, 450, -90, 9);
    }
}

int main() {
    int result = 0;
    try {
        Application.run(new FractalTree);
    } catch(Exception e) {
        msgBox(e.msg, "Fatal Error", MsgBoxButtons.OK, MsgBoxIcon.ERROR);
        result = 1;
    }
    return result;
}

The code utilizes the turtle and grayscale image modules to generate and draw a fractal tree. It begins by drawing the trunk, then splits the end of the trunk at a certain angle to create two branches. This process is repeated until a desired level of branching is achieved. The code is written in DFL.


Procedural Style[edit]
import std.stdio, std.math, std.algorithm;

T[] factors(T)(in T n) pure nothrow {
    if (n == 1)
        return [n];

    T[] res = [1, n];
    T limit = cast(T)real(n).sqrt + 1;
    for (T i = 2; i < limit; i++) {
        if (n % i == 0) {
            res ~= i;
            immutable q = n / i;
            if (q > i)
                res ~= q;
        }
    }

    return res.sort().release;
}

void main() {
    writefln("%(%s\n%)", [45, 53, 64, 1111111].map!factors);
}

compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.


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

    immutable data =
"Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column."
    .split.map!(r => r.chomp("$").split("$")).array;

    size_t[size_t] maxWidths;
    foreach (const line; data)
        foreach (immutable i, const word; line)
            maxWidths[i] = max(maxWidths.get(i, 0), word.length);

    foreach (immutable just; TypeTuple!(leftJustify, center, rightJustify))
        foreach (immutable line; data)
            writefln("%-(%s %)", line.length.iota
                     .map!(i => just(line[i], maxWidths[i], ' ')));
}

The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.


Translation of: Go
import std.stdio, std.array;

void printCuboid(in int dx, in int dy, in int dz) {
    static cline(in int n, in int dx, in int dy, in string cde) {
        writef("%*s", n+1, cde[0 .. 1]);
        write(cde[1 .. 2].replicate(9*dx - 1));
        write(cde[0]);
        writefln("%*s", dy+1, cde[2 .. $]);
    }

    cline(dy+1, dx, 0, "+-");
    foreach (i; 1 .. dy+1)
        cline(dy-i+1, dx, i-1, "/ |");
    cline(0, dx, dy, "+-|");
    foreach (_; 0 .. 4*dz - dy - 2)
        cline(0, dx, dy, "| |");
    cline(0, dx, dy, "| +");
    foreach_reverse (i; 0 .. dy)
        cline(0, dx, i, "| /");
    cline(0, dx, 0, "+-\n");
}

void main() {
    printCuboid(2, 3, 4);
    printCuboid(1, 1, 1);
    printCuboid(6, 2, 1);
}

generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.


import openldap;
import std.stdio;

void main() {
  auto ldap = LDAP("ldap://localhost");
  auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test"));
  int b = ldap.bind_s(r[0].dn, "password");
  scope(exit) ldap.unbind;
  if (b)
  {
    writeln("error on binding");
    return;
  }

  // do something
  ...

}

Establish a connection to an Active Directory or Lightweight Directory Access Protocol server using dopenldap.


Using Standard Functions[edit]
import std.stdio;
import std.ascii: letters, U = uppercase, L = lowercase;
import std.string: makeTrans, translate;

immutable r13 = makeTrans(letters,
                          //U[13 .. $] ~ U[0 .. 13] ~
                          U[13 .. U.length] ~ U[0 .. 13] ~
                          L[13 .. L.length] ~ L[0 .. 13]);

void main() {
    writeln("This is the 1st test!".translate(r13, null));
}

implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is "rotated" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.


import std.stdio, std.algorithm;

struct Pair { string name, value; }

void main() {
    Pair[] pairs = [{"Joe",    "5531"},
                    {"Adam",   "2341"},
                    {"Bernie",  "122"},
                    {"Walter", "1234"},
                    {"David",    "19"}];

    pairs.schwartzSort!q{ a.name }.writeln;
}

sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.


import std.stdio: write, writeln;

void main() {
    for (int i; i < 5; i++) {
        for (int j; j <= i; j++)
            write("*");
        writeln();
    }
    writeln();

    foreach (i; 0 .. 5) {
        foreach (j; 0 .. i + 1)
            write("*");
        writeln();
    }
}

demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.


void main() {
    auto hash = ["foo":42, "bar":100];
    assert("foo" in hash);
}

"Create an associative array, also known as a dictionary, map, or hash."


struct LinearCongruentialGenerator {
    enum uint RAND_MAX = (1U << 31) - 1;
    uint seed = 0;

    uint randBSD() pure nothrow @nogc {
        seed = (seed * 1_103_515_245 + 12_345) & RAND_MAX;
        return seed;
    }

    uint randMS() pure nothrow @nogc {
        seed = (seed * 214_013 + 2_531_011) & RAND_MAX;
        return seed >> 16;
    }
}

void main() {
    import std.stdio;

    LinearCongruentialGenerator rnd;

    foreach (immutable i; 0 .. 10)
        writeln(rnd.randBSD);
    writeln;

    rnd.seed = 0;
    foreach (immutable i; 0 .. 10)
        writeln(rnd.randMS);
}

12345
1406932606
654583775
1449466924
229283573
1109335178
1051550459
1293799192
794471793
551188310

38
7719
21238
2437
8855
11797
8365
32285
10450
30612

"Implement two historic random number generators: the rand() function from BSD libc, and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). Both generators use the linear congruential generator formula, but with different constants and seed values. The generators produce a sequence of integers that are not cryptographically secure but can be used for simple tasks like the Miller-Rabin primality test or FreeCell deals."


struct SLinkedNode(T) {
    T data;
    typeof(this)* next;
}

void insertAfter(T)(SLinkedNode!T* listNode, SLinkedNode!T* newNode) {
    newNode.next = listNode.next;
    listNode.next = newNode;
}

void main() {
    alias N = SLinkedNode!char;

    auto lh = new N('A', new N('B'));
    auto c = new N('C');

    // Inserts C after A, creating the (A C B) list:
    insertAfter(lh, c);

    // The GC will collect the memory.
}

"Defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element C into a list of elements A->B, after element A."


int ethiopian(int n1, int n2) pure nothrow @nogc
in {
    assert(n1 >= 0, "Multiplier can't be negative");
} body {
    static enum doubleNum = (in int n) pure nothrow @nogc => n * 2;
    static enum halveNum = (in int n) pure nothrow @nogc => n / 2;
    static enum isEven = (in int n) pure nothrow @nogc => !(n & 1);

    int result;
    while (n1 >= 1) {
        if (!isEven(n1))
            result += n2;
        n1 = halveNum(n1);
        n2 = doubleNum(n2);
    }

    return result;
} unittest {
    assert(ethiopian(77, 54) == 77 * 54);
    assert(ethiopian(8, 923) == 8 * 923);
    assert(ethiopian(64, -4) == 64 * -4);
}

void main() {
    import std.stdio;

    writeln("17 ethiopian 34 is ", ethiopian(17, 34));
}

The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.


Translation of: Scala
import std.stdio, std.algorithm, std.range, std.conv, std.string,
       std.concurrency, permutations2, arithmetic_rational;

string solve(in int target, in int[] problem) {
    static struct T { Rational r; string e; }

    Generator!T computeAllOperations(in Rational[] L) {
        return new typeof(return)({
            if (!L.empty) {
                immutable x = L[0];
                if (L.length == 1) {
                    yield(T(x, x.text));
                } else {
                    foreach (const o; computeAllOperations(L.dropOne)) {
                        immutable y = o.r;
                        auto sub = [T(x * y, "*"), T(x + y, "+"), T(x - y, "-")];
                        if (y) sub ~= [T(x / y, "/")];
                        foreach (const e; sub)
                            yield(T(e.r, format("(%s%s%s)", x, e.e, o.e)));
                    }
                }
            }
        });
    }

    foreach (const p; problem.map!Rational.array.permutations!false)
        foreach (const sol; computeAllOperations(p))
            if (sol.r == target)
                return sol.e;
    return "No solution";
}

void main() {
    foreach (const prob; [[6, 7, 9, 5], [3, 3, 8, 8], [1, 1, 1, 1]])
        writeln(prob, ": ", solve(24, prob));
}

The code takes four digits as input or generates them randomly, then computes arithmetic expressions according to the rules of the 24 game. It also displays examples of solutions it generates. The code utilizes the Rational struct and permutations functions from two other Rosetta Code Tasks.


Iterative Version[edit]
uint factorial(in uint n) pure nothrow @nogc
in {
    assert(n <= 12);
} body {
    uint result = 1;
    foreach (immutable i; 1 .. n + 1)
        result *= i;
    return result;
}

// Computed and printed at compile-time.
pragma(msg, 12.factorial);

void main() {
    import std.stdio;

    // Computed and printed at run-time.
    12.factorial.writeln;
}

The code calculates the factorial of a given number. It can be implemented either iteratively or recursively. The function may optionally handle errors for negative input values. It is related to the task of generating primorial numbers.


void main() {
    import std.stdio, std.random, std.string, std.algorithm,
           std.range, std.ascii;

    immutable hidden = "123456789"d.randomCover.take(4).array;
    while (true) {
        "Next guess: ".write;
        const d = readln.strip.array.sort().release;
        if (d.count == 4 && d.all!isDigit && d.uniq.count == 4) {
            immutable bulls = d.zip(hidden).count!q{ a[0] == a[1] },
                      cows = d.count!(g => hidden.canFind(g)) - bulls;
            if (bulls == 4)
                return " You guessed it!".writeln;
            writefln("bulls %d, cows %d", bulls, cows);
        }
        " Bad guess! (4 unique digits, 1-9)".writeln;
    }
}

generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.


import std.stdio, std.random, std.math;

struct NormalRandom {
    double mean, stdDev;

    // Necessary because it also defines an opCall.
    this(in double mean_, in double stdDev_) pure nothrow {
        this.mean = mean_;
        this.stdDev = stdDev_;
    }

    double opCall() const /*nothrow*/ {
        immutable r1 = uniform01, r2 = uniform01; // Not nothrow.
        return mean + stdDev * sqrt(-2 * r1.log) * cos(2 * PI * r2);
    }
}

void main() {
    double[1000] array;
    auto nRnd = NormalRandom(1.0, 0.5);
    foreach (ref x; array)
        //x = nRnd;
        x = nRnd();
}

Alternative Version[edit]

Library: tango
import tango.math.random.Random;

void main() {
    double[1000] list;
    auto r = new Random();
    foreach (ref l; list) {
        r.normalSource!(double)()(l);
        l = 1.0 + 0.5 * l;
    }
}

generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using libraries that generate uniformly distributed random numbers.


void main() {
    import std.stdio, std.numeric;

    [1.0, 3.0, -5.0].dotProduct([4.0, -2.0, -1.0]).writeln;
}

"Implements a function to compute the dot product of two vectors of the same length by multiplying corresponding terms from each vector and summing the products."


void main() {
    import std.stdio;

    immutable fileName = "input_loop1.d";

    foreach (const line; fileName.File.byLine) {
        pragma(msg, typeof(line)); // Prints: const(char[])
        // line is a transient slice, so if you need to
        // retain it for later use, you have to .dup or .idup it.
        line.writeln; // Do something with each line.
    }

    // Keeping the line terminators:
    foreach (const line; fileName.File.byLine(KeepTerminator.yes)) {
        // line is a transient slice.
        line.writeln;
    }

    foreach (const string line; fileName.File.lines) {
        // line is a transient slice.
        line.writeln;
    }
}

Library: Tango
import tango.io.Console;
import tango.text.stream.LineIterator;

void main (char[][] args) {
    foreach (line; new LineIterator!(char)(Cin.input)) {
        // do something with each line
    }
}

Library: Tango
import tango.io.Console;
import tango.text.stream.SimpleIterator;

void main (char[][] args) {
    foreach (word; new SimpleIterator!(char)(" ", Cin.input)) {
        // do something with each word
    }
}

read data from a text stream either word-by-word or line-by-line until there's no more data. It duplicates 'line' and 'word' variables for later use as they are transient slices.


Works with: D version 2.011+
module xmltest ;

import std.stdio ;
import std.xml ;

void main() {
  auto doc = new Document("root") ;
//doc.prolog = q"/<?xml version="1.0"?>/" ; // default
  doc ~= new Element("element", "Some text here") ;
  writefln(doc) ;
// output: <?xml version="1.0"?><root><element>Some text here</element></root>
}

Create a simple DOM and serialize it into the specified XML format.


Works with: Tango

Stdout(Clock.now.span.days / 365).newline;

the system time in a specified unit, which can be used for debugging, network information, random number seeds, or program performance. The time-span is calculated from 1 Jan 1 A.D, with the lowest unit available being nanoseconds. The task is related to date formatting and retrieving system time.


Functional Version[edit]
import std.stdio, std.algorithm, std.string, std.numeric, std.ascii;

char checksum(in char[] sedol) pure @safe /*@nogc*/
in {
    assert(sedol.length == 6);
    foreach (immutable c; sedol)
        assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c)));
} out (result) {
    assert(result.isDigit);
} body {
    static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10);
    immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]);
    return digits[10 - (d % 10)];
}

void main() {
    foreach (const sedol; "710889 B0YBKJ 406566 B0YBLH 228276
                          B0YBKL 557910 B0YBKR 585284 B0YBKT".split)
        writeln(sedol, sedol.checksum);
}

The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the corresponding SEDOL. It also validates each input to ensure it is correctly formed according to the allowed characters in a SEDOL string.


Translation of: C
import std.stdio, std.math, std.algorithm, std.numeric;

alias V3 = double[3];
immutable light = normalize([30.0, 30.0, -50.0]);

V3 normalize(V3 v) pure @nogc {
    v[] /= dotProduct(v, v) ^^ 0.5;
    return v;
}

double dot(in ref V3 x, in ref V3 y) pure nothrow @nogc {
    immutable double d = dotProduct(x, y);
    return d < 0 ? -d : 0;
}

void drawSphere(in double R, in double k, in double ambient) @nogc {
    enum shades = ".:!*oe&#%@";
    foreach (immutable i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) {
        immutable double x = i + 0.5;
        foreach (immutable j; cast(int)floor(-2 * R) ..
                              cast(int)ceil(2 * R) + 1) {
            immutable double y = j / 2. + 0.5;
            if (x ^^ 2 + y ^^ 2 <= R ^^ 2) {
                immutable vec = [x, y, (R^^2 - x^^2 - y^^2) ^^ 0.5]
                                .normalize;
                immutable double b = dot(light, vec) ^^ k + ambient;
                int intensity = cast(int)((1 - b) * (shades.length-1));
                intensity = min(shades.length - 1, max(intensity, 0));
                shades[intensity].putchar;
            } else
                ' '.putchar;
        }
        '\n'.putchar;
    }
}

void main() {
    drawSphere(20, 4, 0.1);
    drawSphere(10, 2, 0.4);
}

"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection."


Translation of: Python
import std.stdio, std.string, std.range, std.algorithm;

string nth(in uint n) pure {
    static immutable suffix = "th st nd rd th th th th th th".split;
    return "%d'%s".format(n, (n % 100 <= 10 || n % 100 > 20) ?
                             suffix[n % 10] : "th");
}

void main() {
    foreach (r; [iota(26), iota(250, 266), iota(1000, 1026)])
        writefln("%-(%s %)", r.map!nth);
}

The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.


import std.stdio;

string stripchars(string s, string chars) {
    import std.algorithm;
    import std.conv;
    return s.filter!(c => !chars.count(c)).to!string;
}

string stripchars2(string s, string chars) {
    import std.regex;
    return replaceAll(s, regex("[" ~ chars ~ "]"), "");
}

void main() {
    string s = "She was a soul stripper. She took my heart!";
    string chars = "aei";

    writeln(stripchars(s, chars));
    writeln(stripchars2(s, chars));
}

The function 'stripchars' takes two strings as input, removes all occurrences of characters in the second string from the first string, and returns the modified string.


import core.stdc.stdlib;
import std.stdio;

void main() {
    int limit;
    write("Max number (>0): ");
    readf!"%d\n"(limit);
    if (limit <= 0) {
        writeln("The max number to consider must be greater than zero.");
        exit(1);
    }

    int terms;
    write("Terms (>0): ");
    readf!"%d\n"(terms);
    if (terms <= 0) {
        writeln("The number of terms to consider must be greater than zero.");
        exit(1);
    }

    int[] factors = new int[terms];
    string[] words = new string[terms];

    for (int i=0; i<terms; ++i) {
        write("Factor ", i+1, " and word: ");
        readf!"%d %s\n"(factors[i], words[i]);
        if (factors[i] <= 0) {
            writeln("The factor to consider must be greater than zero.");
            exit(1);
        }
    }

    foreach(n; 1..limit+1) {
        bool print = true;

        for (int i=0; i<terms; ++i) {
            if (n % factors[i] == 0) {
                write(words[i]);
                print = false;
            }
        }

        if (print) {
            writeln(n);
        } else {
            writeln();
        }
    }
}

implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.


import std.stdio;

void main() {
    string s = "world!";
    s = "Hello " ~ s;
    writeln(s);
}

Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.


Text mode[edit]

variables : X Y F
constants : + −
start  : FX
rules  : (X → X+YF+),(Y → -FX-Y)
angle  : 90°
import std.stdio, std.string;

struct Board {
    enum char spc = ' ';
    char[][] b = [[' ']]; // Set at least 1x1 board.
    int shiftx, shifty;

    void clear() pure nothrow {
        shiftx = shifty = 0;
        b = [['\0']];
    }

    void check(in int x, in int y) pure nothrow {
        while (y + shifty < 0) {
            auto newr = new char[b[0].length];
            newr[] = spc;
            b = newr ~ b;
            shifty++;
        }

        while (y + shifty >= b.length) {
            auto newr = new char[b[0].length];
            newr[] = spc;
            b ~= newr;
        }

        while (x + shiftx < 0) {
            foreach (ref c; b)
                c = [spc] ~ c;
            shiftx++;
        }

        while (x + shiftx >= b[0].length)
            foreach (ref c; b)
                c ~= [spc];
    }

    char opIndexAssign(in char value, in int x, in int y)
    pure nothrow {
        check(x, y);
        b[y + shifty][x + shiftx] = value;
        return value;
    }

    string toString() const pure {
        return format("%-(%s\n%)", b);
    }
}

struct Turtle {
    static struct TState {
        int[2] xy;
        int heading;
    }

    enum int[2][] dirs = [[1, 0],  [1,   1], [0,  1], [-1,  1],
                          [-1, 0], [-1, -1], [0, -1],  [1, -1]];
    enum string trace = r"-\|/-\|/";
    TState t;

    void reset() pure nothrow {
        t = typeof(t).init;
    }

    void turn(in int dir) pure nothrow {
        t.heading = (t.heading + 8 + dir) % 8;
    }

    void forward(ref Board b) pure nothrow {
        with (t) {
            xy[] += dirs[heading][];
            b[xy[0], xy[1]] = trace[heading];
            xy[] += dirs[heading][];
            b[xy[0], xy[1]] = b.spc;
        }
    }
}

void dragonX(in int n, ref Turtle t, ref Board b) pure nothrow {
    if (n >= 0) { // X -> X+YF+
        dragonX(n - 1, t, b);
        t.turn(2);
        dragonY(n - 1, t, b);
        t.forward(b);
        t.turn(2);
    }
}

void dragonY(in int n, ref Turtle t, ref Board b) pure nothrow {
    if (n >= 0) { // Y -> -FX-Y
        t.turn(-2);
        t.forward(b);
        dragonX(n - 1, t, b);
        t.turn(-2);
        dragonY(n - 1, t, b);
    }
}

void main() {
    Turtle t;
    Board b;
                      // Seed : FX
    t.forward(b);     // <- F
    dragonX(7, t, b); // <- X
    writeln(b);
}

The code generates a Dragon Curve fractal either directly or by writing it to an image file. It uses different algorithms including recursive, successive approximation, iterative, and Lindenmayer system of expansions. The recursive algorithm involves right and left curling dragons, while the successive approximation rewrites each straight line as two new segments at a right angle. The iterative method uses bit manipulation to determine the direction of the turn. The Lindenmayer system uses two symbols for straight lines. Additionally, the code includes a textual version of the Dragon Curve and uses modules from the Bresenham's line algorithm and Grayscale Image tasks. The code also allows for the calculation of absolute X,Y coordinates of a point and a predicate test to check if a given X,Y point or segment is on the curve.


void main() {
    immutable num = uniform(1, 10).text;

    do write("What's next guess (1 - 9)? ");
    while (readln.strip != num);

    writeln("Yep, you guessed my ", num);
}

"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing."


import std.ascii: lowercase;

void main() {}

void main() {
    char['z' - 'a' + 1] arr;

    foreach (immutable i, ref c; arr)
        c = 'a' + i;
}

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

    char[26] arr = 26.iota.map!(i => cast(char)('a' + i)).array;
}

void main() {
    char[] arr;

    foreach (immutable char c; 'a' .. 'z' + 1)
        arr ~= c;

    assert(arr == "abcdefghijklmnopqrstuvwxyz");
}

generate an array, list, or string of all lower case ASCII characters from 'a' to 'z'. The code also demonstrates how to access a similar sequence if it exists in the standard library. The coding style used is reliable and suitable for large programs, with strong typing utilized if available. The code avoids manually enumerating all lowercase characters to prevent bugs.


void main() {
    import std.stdio;

    foreach (immutable i; 0 .. 16)
        writefln("%b", i);
}

generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.


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

enum VarName(alias var) = var.stringof;

void setOpt(alias Var)(in string line) {
    auto m = match(line, regex(`^(?i)` ~ VarName!Var ~ `(?-i)(\s*=?\s+(.*))?`));

    if (!m.empty) {
        static if (is(typeof(Var) == string[]))
            Var = m.captures.length > 2 ? m.captures[2].split(regex(`\s*,\s*`)) : [""];
        static if (is(typeof(Var) == string))
            Var = m.captures.length > 2 ? m.captures[2] : "";
        static if (is(typeof(Var) == bool))
            Var = true;
        static if (is(typeof(Var) == int))
            Var = m.captures.length > 2 ? to!int(m.captures[2]) : 0;
    }
}

void main(in string[] args) {
    string fullName, favouriteFruit;
    string[] otherFamily;
    bool needsPeeling, seedsRemoved; // Default false.

    auto f = "readcfg.conf".File;

    foreach (line; f.byLine) {
        auto opt = line.strip.idup;

        setOpt!fullName(opt);
        setOpt!favouriteFruit(opt);
        setOpt!needsPeeling(opt);
        setOpt!seedsRemoved(opt);
        setOpt!otherFamily(opt);
    }

    writefln("%s = %s", VarName!fullName, fullName);
    writefln("%s = %s", VarName!favouriteFruit, favouriteFruit);
    writefln("%s = %s", VarName!needsPeeling, needsPeeling);
    writefln("%s = %s", VarName!seedsRemoved, seedsRemoved);
    writefln("%s = %s", VarName!otherFamily, otherFamily);
}

The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration parameters. It handles an optional equals sign separating configuration parameter data from the option name. It also supports multiple parameters for a configuration option, storing them in an array. The output includes four variables: fullname, favouritefruit, needspeeling, and seedsremoved, and an array otherfamily with multiple parameters.


import std.stdio, std.math;

real haversineDistance(in real dth1, in real dph1,
                       in real dth2, in real dph2)
pure nothrow @nogc {
    enum real R = 6371;
    enum real TO_RAD = PI / 180;

    alias imr = immutable real;
    imr ph1d = dph1 - dph2;
    imr ph1 = ph1d * TO_RAD;
    imr th1 = dth1 * TO_RAD;
    imr th2 = dth2 * TO_RAD;

    imr dz = th1.sin - th2.sin;
    imr dx = ph1.cos * th1.cos - th2.cos;
    imr dy = ph1.sin * th1.cos;
    return asin(sqrt(dx ^^ 2 + dy ^^ 2 + dz ^^ 2) / 2) * 2 * R;
}

void main() {
    writefln("Haversine distance: %.1f km",
             haversineDistance(36.12, -86.67, 33.94, -118.4));
}

implement the Haversine formula to calculate the great-circle distance between Nashville International Airport (BNA) and Los Angeles International Airport (LAX) using their respective longitudes and latitudes. The earth's radius is considered as 6372.8 km or 6371 km based on the user's preference. The formula is used in navigation and spherical trigonometry.


Library: phobos
void main() {
  import std.stdio, std.net.curl;
  writeln(get("http://google.com"));
}

Library: tango
import tango.io.Console;
import tango.net.http.HttpGet;

void main() {
  Cout.stream.copy( (new HttpGet("http://google.com")).open );
}

import tango.io.Console;
import tango.net.InternetAddress;
import tango.net.device.Socket;

void main() {
  auto site = new Socket;
  site.connect (new InternetAddress("google.com",80)).write ("GET / HTTP/1.0\n\n");

  Cout.stream.copy (site);
}

"Prints the content of a specified URL to the console using HTTP request."


Functional Version[edit]
Translation of: Haskell
import std.algorithm, std.range, std.string;

enum luhnTest = (in string n) pure /*nothrow*/ @safe /*@nogc*/ =>
    retro(n)
    .zip(only(1, 2).cycle)
    .map!(p => (p[0] - '0') * p[1])
    .map!(d => d / 10 + d % 10)
    .sum % 10 == 0;

void main() {
    assert("49927398716 49927398717 1234567812345678 1234567812345670"
           .split.map!luhnTest.equal([true, false, false, true]));
}

More Imperative Version[edit]
Translation of: C
import std.algorithm;

bool luhnTest(in string num) @safe pure nothrow @nogc {
    uint sum;
    foreach_reverse (immutable i, immutable n; num) {
        immutable uint ord = n - '\u0030';
        sum += ((num.length - i) & 1) ? ord : ord / 5 + (2 * ord) % 10;
    }
    return sum % 10 == 0;
}

void main() {
    immutable data = ["49927398716",
                      "49927398717",
                      "1234567812345678",
                      "1234567812345670"];
    assert(data.map!luhnTest.equal([true, false, false, true]));
}

Stronger Statically Typed Version[edit]

Translation of: SPARK
import std.stdio;

struct Interval(T) {
    immutable T a, b;

    this(in T a_, in T b_) pure nothrow @nogc {
        this.a = a_;
        this.b = b_;
    }

    bool opBinaryRight(string op="in")(in T x)
    const pure nothrow @nogc {
        return x >= a && x <= b;
    }

    pure nothrow @safe @nogc const invariant {
        assert(a <= b);
    }
}

Interval!T interval(T)(in T a, in T b) pure nothrow @nogc {
    return Interval!T(a, b);
}

bool luhnTest(in string num) pure nothrow @nogc
in {
    assert(num.length <= 20);
} body {
    int sum = 0;
    bool od = true;
    bool ok = true;
    immutable int numLen = num.length;

    foreach_reverse (immutable p; 0 .. numLen) {
        immutable int i = num[p] - '0';
        if (i !in interval(0, 9)) {
            ok = false;
            break;
        }

        immutable int x = ((i * 2) % 10) + (i / 5);
        assert((numLen - p) in interval(0, 19));
        assert(sum in interval(0, (numLen - p) * 10));
        assert(i in interval(0, 9));
        assert(x in interval(0, 9));
        sum += od ? i : x;
        od = !od;
    }

    return ok && (sum % 10) == 0;
}

void main() {
    foreach (immutable n; ["49927398716", "49927398717",
                           "1234567812345678", "1234567812345670",
                           "123456781234567D"])
        writefln("%s is %svalid", n, luhnTest(n) ? "" : "not ");
}

The code validates credit card numbers using the Luhn test. It first reverses the order of the digits, then sums the odd digits to form a partial sum (s1). It also multiplies the even digits by two, sums the digits if the result is greater than nine, and forms another partial sum (s2). If the sum of s1 and s2 ends in zero, the number is a valid credit card number. The function is used to validate a list of given numbers.


Translation of: Python
import std.stdio, std.algorithm, std.array, std.string, std.range;

T pop(T)(ref T[] items, in size_t i) pure /*nothrow*/ @safe /*@nogc*/ {
    auto aux = items[i];
    items = items.remove(i);
    return aux;
}

string josephus(in int n, in int k) pure /*nothrow*/ @safe {
    auto p = n.iota.array;
    int i;
    immutable(int)[] seq;
    while (!p.empty) {
        i = (i + k - 1) % p.length;
        seq ~= p.pop(i);
    }

    return format("Prisoner killing order:\n%(%(%d %)\n%)." ~
                  "\nSurvivor: %d",
                  seq[0 .. $ - 1].chunks(20), seq[$ - 1]);
}

void main() /*@safe*/ {
    josephus(5, 2).writeln;
    writeln;
    josephus(41, 3).writeln;
}

- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).
- Calculate the position of any prisoner in the killing sequence.
- Provide an option to save a certain number of prisoners (m).
- The numbering of prisoners can start from either 0 or 1.
- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.


import std.stdio, std.array;

void main() {
    writeln("ha".replicate(5));
}

import std.stdio;

void main() {
    char[] chars;     // create the dynamic array
    chars.length = 5; // set the length
    chars[] = '*';    // set all characters in the string to '*'
    writeln(chars);
}

implement a function to repeat a string a certain number of times, and another function to repeat a single character a specified number of times.


void main() {
    import std.stdio, std.regex;

    immutable s = "I am a string";

    // Test.
    if (s.match("string$"))
        "Ends with 'string'.".writeln;

    // Substitute.
    s.replace(" a ".regex, " another ").writeln;
}

utilize std.string functions to efficiently match and substitute parts of a string using regular expressions.


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

void main() {
    int a = 10, b = 20;
    try {
        a = readln().strip().to!int();
        b = readln().strip().to!int();
    } catch (StdioException e) {}
    writeln("a = ", a, ", b = ", b);

    writeln("a + b = ", a + b);
    writeln("a - b = ", a - b);
    writeln("a * b = ", a * b);
    writeln("a / b = ", a / b);
    writeln("a % b = ", a % b);
    writeln("a ^^ b = ", a ^^ b);
}

The code takes two integers as input from the user and calculates their sum, difference, product, integer quotient, remainder, and exponentiation. It also indicates the rounding method for quotient and the sign matching for the remainder. It does not include error handling. A bonus feature is the inclusion of the 'divmod' operator example. The division and modulus are defined as in C99.


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

    "the three truths".count("th").writeln;
    "ababababab".count("abab").writeln;
}

The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.


Recursive Version[edit]
import std.stdio;

void hanoi(in int n, in char from, in char to, in char via) {
    if (n > 0) {
        hanoi(n - 1, from, via, to);
        writefln("Move disk %d from %s to %s", n, from, to);
        hanoi(n - 1, via, to, from);
    }
}

void main() {
    hanoi(3, 'L', 'M', 'R');
}

"Implement a recursive solution to solve the Towers of Hanoi problem, based on the shortest and 'mysterious' TH algorithm."


T binomial(T)(in T n, T k) pure nothrow {
    if (k > (n / 2))
        k = n - k;
    T bc = 1;
    foreach (T i; T(2) .. k + 1)
        bc = (bc * (n - k + i)) / i;
    return bc;
}

void main() {
    import std.stdio, std.bigint;

    foreach (const d; [[5, 3], [100, 2], [100, 98]])
        writefln("(%3d %3d) = %s", d[0], d[1], binomial(d[0], d[1]));
    writeln("(100  50) = ", binomial(100.BigInt, 50.BigInt));
}

The code calculates any binomial coefficient using the provided formula. It is capable of outputting the binomial coefficient of (5,3) which equals 10. The code also includes tasks for generating combinations and permutations, both with and without replacement. Additionally, it can handle large coefficients, as demonstrated by the correct calculation of 100C50.


import std.stdio: writeln;

void shellSort(T)(T[] seq) pure nothrow {
    int inc = seq.length / 2;
    while (inc) {
        foreach (ref i, el; seq) {
            while (i >= inc && seq[i - inc] > el) {
                seq[i] = seq[i - inc];
                i -= inc;
            }
            seq[i] = el;
        }
        inc = (inc == 2) ? 1 : cast(int)(inc * 5.0 / 11);
    }
}

void main() {
    auto data = [22, 7, 2, -5, 8, 4];
    shellSort(data);
    writeln(data);
}

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


module grayscale_image;

import core.stdc.stdio, std.array, std.algorithm, std.string, std.ascii;
public import bitmap;

struct Gray {
    ubyte c;
    enum black = typeof(this)(0);
    enum white = typeof(this)(255);
    alias c this;
}

Image!Color loadPGM(Color)(Image!Color img, in string fileName) {
    static int readNum(FILE* f) nothrow @nogc {
        int n;
        while (!fscanf(f, "%d ", &n)) {
            if ((n = fgetc(f)) == '#') {
                while ((n = fgetc(f)) != '\n')
                    if (n == EOF)
                        return 0;
            } else
                return 0;
        }
        return n;
    }

    if (img is null)
        img = new Image!Color();

    auto fin = fopen(fileName.toStringz(), "rb");
    scope(exit) if (fin) fclose(fin);
    if (!fin)
        throw new Exception("Can't open input file.");

    if (fgetc(fin) != 'P' ||
        fgetc(fin) != '5' ||
        !isWhite(fgetc(fin)))
        throw new Exception("Not a PGM (PPM P5) image.");

    immutable int nc = readNum(fin);
    immutable int nr = readNum(fin);
    immutable int maxVal = readNum(fin);
    if (nc <= 0 || nr <= 0 || maxVal <= 0)
        throw new Exception("Wrong input image sizes.");
    img.allocate(nc, nr);
    auto pix = new ubyte[img.image.length];

    immutable count = fread(pix.ptr, 1, nc * nr, fin);
    if (count != nc * nr)
        throw new Exception("Wrong number of items read.");

    pix.copy(img.image);
    return img;
}

void savePGM(Color)(in Image!Color img, in string fileName)
in {
    assert(img !is null);
    assert(!fileName.empty);
    assert(img.nx > 0 && img.ny > 0 &&
           img.image.length == img.nx * img.ny,
           "Wrong image.");
} body {
    auto fout = fopen(fileName.toStringz(), "wb");
    if (fout == null)
        throw new Exception("File can't be opened.");
    fprintf(fout, "P5\n%d %d\n255\n", img.nx, img.ny);
    auto pix = new ubyte[img.image.length];
    foreach (i, ref p; pix)
        p = cast(typeof(pix[0]))img.image[i];
    immutable count = fwrite(pix.ptr, ubyte.sizeof,
                             img.nx * img.ny, fout);
    if (count != img.nx * img.ny)
        new Exception("Wrong number of items written.");
    fclose(fout);
}

Gray lumCIE(in RGB c) pure nothrow @nogc {
    return Gray(cast(ubyte)(0.2126 * c.r +
                            0.7152 * c.g +
                            0.0722 * c.b + 0.5));
}

Gray lumAVG(in RGB c) pure nothrow @nogc {
    return Gray(cast(ubyte)(0.3333 * c.r +
                            0.3333 * c.g +
                            0.3333 * c.b + 0.5));
}

Image!Gray rgb2grayImage(alias Conv=lumCIE)(in Image!RGB im) nothrow {
    auto result = new typeof(return)(im.nx, im.ny);
    foreach (immutable i, immutable rgb; im.image)
        result.image[i] = Conv(rgb);
    return result;
}

Image!RGB gray2rgbImage(in Image!Gray im) nothrow {
    auto result = new typeof(return)(im.nx, im.ny);
    foreach (immutable i, immutable gr; im.image)
        result.image[i] = RGB(gr, gr, gr);
    return result;
}

version (grayscale_image_main) {
    void main() {
        auto im1 = new Image!Gray;
        im1.loadPGM("lena.pgm");
        gray2rgbImage(im1).savePPM6("lena_rgb.ppm");

        auto img2 = new Image!RGB;
        img2.loadPPM6("quantum_frog.ppm");
        img2.rgb2grayImage.savePGM("quantum_frog_grey.pgm");
    }
}

extend the data storage type to support grayscale images. They define two operations: one for converting a color image to a grayscale image and another for the reverse conversion. The luminance of a color is calculated using the CIE recommended formula. The codes also ensure that rounding errors in floating-point arithmetic do not cause run-time problems or distorted results when the calculated luminance is stored as an unsigned integer. The bitmap module from the Bitmap Task page is utilized in these codes.


Library: QD
uses Library: SDL
Library: SDL_ttf
Library: tools
module test26;

import qd, SDL_ttf, tools.time;

void main() {
  screen(320, 200);
  auto last = sec();
  string text = "Hello World! ";
  auto speed = 0.2;
  int dir = true;
  while (true) {
    cls;
    print(10, 10, Bottom|Right, text);
    if (sec() - last > speed) {
      last = sec();
      if (dir == 0) text = text[$-1] ~ text[0 .. $-1];
      else text = text[1 .. $] ~ text[0];
    }
    flip; events;
    if (mouse.clicked
      && mouse.pos in display.select(10, 10, 100, 20)
    ) dir = !dir;
  }
}

Create a GUI animation where the string "Hello World! " appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.


import std.stdio;

void main() {
    int val;
    do {
        val++;
        write(val, " ");
    } while (val % 6 != 0);
}

The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


Byte Length[edit]
import std.stdio;

void showByteLen(T)(T[] str) {
    writefln("Byte length: %2d - %(%02x%)",
             str.length * T.sizeof, cast(ubyte[])str);
}

void main() {
    string s1a = "møøse"; // UTF-8
    showByteLen(s1a);
    wstring s1b = "møøse"; // UTF-16
    showByteLen(s1b);
    dstring s1c = "møøse"; // UTF-32
    showByteLen(s1c);
    writeln();

    string s2a = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢";
    showByteLen(s2a);
    wstring s2b = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢";
    showByteLen(s2b);
    dstring s2c = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢";
    showByteLen(s2c);
    writeln();

    string s3a = "J̲o̲s̲é̲";
    showByteLen(s3a);
    wstring s3b = "J̲o̲s̲é̲";
    showByteLen(s3b);
    dstring s3c = "J̲o̲s̲é̲";
    showByteLen(s3c);
}

calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.


import std.stdio;
import std.random;

void main()
{
  Mt19937 gen;
  gen.seed(unpredictableSeed);
  auto n = gen.front;
  writeln(n);
}

demonstrate how to generate a random 32-bit number using a system's built-in mechanism, not just a software algorithm, similar to the /dev/urandom devices in Unix. It also includes an example of using the MersenneTwisterEngine to generate uniformly-distributed 32-bit numbers with a period of 2^19937.


import std.stdio;

void main() {
    // strip first character
    writeln("knight"[1 .. $]);

    // strip last character
    writeln("socks"[0 .. $ - 1]);

    // strip both first and last characters
    writeln("brooms"[1 .. $ - 1]);
}

The code demonstrates the removal of the first and last characters from a string. It shows how to obtain a string with the first character removed, a string with the last character removed, and a string with both the first and last characters removed. It works with any valid Unicode code point in UTF-8 or UTF-16, focusing on logical characters (code points) rather than 8-bit or 16-bit code units. Handling all Unicode characters for other encodings like 8-bit ASCII or EUC-JP is not required.


Unix Domain Socket[edit]

There is no need to worry about possible collisions with existing files in the filesystem.
There is no socket file to be removed upon program termination.
We do not need to create a file for the socket at all. This obviates target directory existence, permissions checks, and reduces filesystem clutter. Also, it works in chrooted environments.

bool is_unique_instance()
{
    import std.socket;
    auto socket = new Socket(AddressFamily.UNIX, SocketType.STREAM);
    auto addr = new UnixAddress("\0/tmp/myapp.uniqueness.sock");
    try
    {
        socket.bind(addr);
        return true;
    }
    catch (SocketOSException e)
    {
        import core.stdc.errno : EADDRINUSE;

        if (e.errorCode == EADDRINUSE)
            return false;
        else
            throw e;
    }
}

The code checks if there is only one instance of the application running by using Unix domain sockets in the abstract namespace. If another instance is found, it displays a message and exits. It generates a unique name for the program and uses it as the address when binding the socket.