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.


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.


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.


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.


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();
}

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.


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.


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


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.


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


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]));
}
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]));
}

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.


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.


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.


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.


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.


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

struct Digit {
    immutable char d;

    this(in char d_) pure nothrow @safe @nogc
    in { assert(d_ >= '0' && d_ <= '9'); }
    body { this.d = d_; }

    this(in int d_) pure nothrow @safe @nogc
    in { assert(d_ >= '0' && d_ <= '9'); }
    body { this.d = cast(char)d_; } // Required cast.

    alias d this;
}

enum size_t sudokuUnitSide = 3;
enum size_t sudokuSide = sudokuUnitSide ^^ 2; // Sudoku grid side.
alias SudokuTable = Digit[sudokuSide ^^ 2];

Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem)
pure nothrow {
    alias Tgrid = uint;
    Tgrid[SudokuTable.length] grid = void;
    problem[].map!(c => c - '0').copy(grid[]);

    // DMD doesn't inline this function. Performance loss.
    Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {
        return grid[y * sudokuSide + x];
    }

    // DMD doesn't inline this function. If you want to retain
    // the same performance as the C++ entry and you use the DMD
    // compiler then this function must be manually inlined.
    bool checkValidity(in Tgrid val, in size_t x, in size_t y)
    pure nothrow @safe @nogc {
        /*static*/ foreach (immutable i; staticIota!(0, sudokuSide))
            if (access(i, y) == val || access(x, i) == val)
                return false;

        immutable startX = (x / sudokuUnitSide) * sudokuUnitSide;
        immutable startY = (y / sudokuUnitSide) * sudokuUnitSide;

        /*static*/ foreach (immutable i; staticIota!(0, sudokuUnitSide))
            /*static*/ foreach (immutable j; staticIota!(0, sudokuUnitSide))
                if (access(startX + j, startY + i) == val)
                    return false;

        return true;
    }

    bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {
        if (pos == SudokuTable.length)
            return true;
        if (grid[pos] > 0)
            return canPlaceNumbers(pos + 1);

        foreach (immutable n; 1 .. sudokuSide + 1)
            if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) {
                grid[pos] = n;
                if (canPlaceNumbers(pos + 1))
                    return true;
                grid[pos] = 0;
            }

        return false;
    }

    if (canPlaceNumbers) {
        //return typeof(return)(grid[]
        //                      .map!(c => Digit(c + '0'))
        //                      .array);
        immutable SudokuTable result = grid[]
                                       .map!(c => Digit(c + '0'))
                                       .array;
        return typeof(return)(result);
    } else
        return typeof(return)();
}

string representSudoku(in ref SudokuTable sudo)
pure nothrow @safe out(result) {
    assert(result.countchars("1-9") == sudo[].count!q{a != '0'});
    assert(result.countchars(".") == sudo[].count!q{a == '0'});
} body {
    static assert(sudo.length == 81,
        "representSudoku works only with a 9x9 Sudoku.");
    string result;

    foreach (immutable i; 0 .. sudokuSide) {
        foreach (immutable j; 0 .. sudokuSide) {
            result ~= sudo[i * sudokuSide + j];
            result ~= ' ';
            if (j == 2 || j == 5)
                result ~= "| ";
        }
        result ~= "\n";
        if (i == 2 || i == 5)
            result ~= "------+-------+------\n";
    }

    return result.replace("0", ".");
}

void main() {
    enum ValidateCells(string s) = s.map!Digit.array;

    immutable SudokuTable problem = ValidateCells!("
        850002400
        720000009
        004000000
        000107002
        305000900
        040000000
        000080070
        017000000
        000036040".removechars(whitespace));
    problem.representSudoku.writeln;

    immutable solution = problem.sudokuSolver;
    if (solution.isNull)
        writeln("Unsolvable!");
    else
        solution.get.representSudoku.writeln;
}

The code solves a given partially filled 9x9 Sudoku grid and displays the result in a user-friendly format. It utilizes strong static typing and idioms to avoid memory allocations on the heap, making it efficient for larger programs. The solution is inspired by the Algorithmics of Sudoku and a Python Sudoku Solver video from Computerphile.


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

    auto a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    a.randomShuffle;
    a.writeln;
}

Implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The algorithm can be adjusted to return a new array instead if in-place modification is not suitable. It can also be modified to iterate from left to right for convenience. Test cases are provided for verification.


import std.stdio, std.datetime, std.traits;

void lastFridays(in uint year) {
    auto date = Date(year, 1, 1);
    foreach (_; [EnumMembers!Month]) {
        date.day(date.daysInMonth);
        date.roll!"days"(-(date.dayOfWeek + 2) % 7);
        writeln(date);
        date.add!"months"(1, AllowDayOverflow.no);
    }
}

void main() {
    lastFridays(2012);
}

2012-Jan-27
2012-Feb-24
2012-Mar-30
2012-Apr-27
2012-May-25
2012-Jun-29
2012-Jul-27
2012-Aug-31
2012-Sep-28
2012-Oct-26
2012-Nov-30
2012-Dec-28

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


Works with: D version 2.0
import std.stdio;

void main() {
    write("Goodbye, World!");
}

"Display the string 'Goodbye, World!' without appending a newline at the end."


import std.stdio, std.traits;

S rot(S)(in S s, in int key) pure nothrow @safe
if (isSomeString!S) {
    auto res = s.dup;

    foreach (immutable i, ref c; res) {
        if ('a' <= c && c <= 'z')
            c = ((c - 'a' + key) % 26 + 'a');
        else if ('A' <= c && c <= 'Z')
            c = ((c - 'A' + key) % 26 + 'A');
    }
    return res;
}

void main() @safe {
    enum key = 3;
    immutable txt = "The five boxing wizards jump quickly";
    writeln("Original:  ", txt);
    writeln("Encrypted: ", txt.rot(key));
    writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}

implement both encoding and decoding functionalities of a Caesar cipher. The cipher rotates the letters of the alphabet based on a key ranging from 1 to 25. It replaces each letter with the next 1st to 25th letter in the alphabet, wrapping Z back to A. The codes also consider the fact that Caesar cipher is identical to Vigenère cipher with a key of length 1 and Rot-13 is identical to Caesar cipher with key 13. Despite its simplicity, this cipher provides almost no security.


import std.stdio, std.bigint, std.math;

T gcd(T)(T a, T b) pure nothrow {
    while (b) {
        immutable t = b;
        b = a % b;
        a = t;
    }
    return a;
}

T lcm(T)(T m, T n) pure nothrow {
    if (m == 0) return m;
    if (n == 0) return n;
    return abs((m * n) / gcd(m, n));
}

void main() {
    lcm(12, 18).writeln;
    lcm("2562047788015215500854906332309589561".BigInt,
        "6795454494268282920431565661684282819".BigInt).writeln;
}

calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


import std.stdio;

void main(string[] args) {
    writeln("CUSIP       Verdict");
    foreach(arg; args[1..$]) {
        writefln("%9s : %s", arg, isValidCusip(arg) ? "Valid" : "Invalid");
    }
}

class IllegalCharacterException : Exception {
    this(string msg) {
        super(msg);
    }
}

bool isValidCusip(string cusip) in {
    assert(cusip.length == 9, "Incorrect cusip length");
} body {
    try {
        auto check = cusipCheckDigit(cusip);
        return cusip[8] == ('0' + check);
    } catch (IllegalCharacterException e) {
        return false;
    }
}

unittest {
    // Oracle Corporation
    assertEquals(isValidCusip("68389X105"), true);

    // Oracle Corporation (invalid)
    assertEquals(isValidCusip("68389X106"), false);
}

int cusipCheckDigit(string cusip) in {
    assert(cusip.length == 9, "Incorrect cusip length");
} body {
    int sum;
    for (int i=0; i<8; ++i) {
        char c = cusip[i];
        int v;

        switch(c) {
            case '0': .. case '9':
                v = c - '0';
                break;
            case 'A': .. case 'Z':
                v = c - 'A' + 10;
                break;
            case '*':
                v = 36;
                break;
            case '@':
                v = 37;
                break;
            case '#':
                v = 38;
                break;
            default:
                throw new IllegalCharacterException("Saw character: " ~ c);
        }
        if (i%2 == 1) {
            v = 2 * v;
        }

        sum = sum + (v / 10) + (v % 10);
    }

   return (10 - (sum % 10)) % 10;
}

unittest {
    // Apple Incorporated
    assertEquals(cusipCheckDigit("037833100"), 0);

    // Cisco Systems
    assertEquals(cusipCheckDigit("17275R102"), 2);

    // Google Incorporated
    assertEquals(cusipCheckDigit("38259P508"), 8);

    // Microsoft Corporation
    assertEquals(cusipCheckDigit("594918104"), 4);

    // Oracle Corporation
    assertEquals(cusipCheckDigit("68389X105"), 5);
}

version(unittest) {
    void assertEquals(T)(T actual, T expected) {
        import core.exception;
        import std.conv;
        if (actual != expected) {
            throw new AssertError("Actual [" ~ to!string(actual) ~ "]; Expected [" ~ to!string(expected) ~ "]");
        }
    }
}

/// Invoke with `cusip 037833100 17275R102 38259P508 594918104 68389X106 68389X105`

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


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

  writeln("Word size = ", size_t.sizeof * 8, " bits.");
  writeln(endian == Endian.littleEndian ? "Little" : "Big", " endian.");
}

"Outputs the word size and endianness of the host machine."


void main() {
    import std.stdio, std.algorithm, std.conv, std.array, std.regex,
           std.typecons, std.net.curl;

    immutable r1 = `"title":"Category:([^"]+)"`;
    const languages = get("www.rosettacode.org/w/api.php?action=query"~
                          "&list=categorymembers&cmtitle=Category:Pro"~
                          "gramming_Languages&cmlimit=500&format=json")
                      .matchAll(r1).map!q{ a[1].dup }.array;

    auto pairs = get("www.rosettacode.org/w/index.php?" ~
                      "title=Special:Categories&limit=5000")
                  .matchAll(`title="Category:([^"]+)">[^<]+` ~
                            `</a>[^(]+\((\d+) members\)`)
                  .filter!(m => languages.canFind(m[1]))
                  .map!(m => tuple(m[2].to!uint, m[1].dup));

    foreach (i, res; pairs.array.sort!q{a > b}.release)
        writefln("%3d. %3d - %s", i + 1, res[]);
}

Sample output (top twenty as of 2013-01-24):
  1. 717 - Tcl
  2. 663 - Python
  3. 643 - C
  4. 626 - PicoLisp
  5. 622 - J
  6. 587 - Go
  7. 587 - Ruby
  8. 585 - D
  9. 568 - Perl 6
 10. 564 - Ada
 11. 554 - Mathematica
 12. 535 - Perl
 13. 532 - Haskell
 14. 514 - BBC BASIC
 15. 505 - REXX
 16. 491 - Java
 17. 478 - OCaml
 18. 469 - PureBasic
 19. 462 - Unicon
 20. 430 - AutoHotkey

The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It accesses data either through web scraping or using the API method. The code also has the option to filter out incorrect results. The final output is a complete ranked list of all programming languages. The code needs to be compiled with dmd using specific parameters.


import std.stdio: writeln;

void main() {
    auto collection1 = "ABC";
    foreach (element; collection1)
        writeln(element);

    auto collection2 = [1, 2, 3];
    foreach (element; collection1)
        writeln(element);

    auto collection3 = [1:10, 2:20, 3:30];
    foreach (element; collection3)
        writeln(element);

    foreach (key, value; collection3)
        writeln(key, " ", value);
}

iterate through each element in a collection in order and print them. This is applicable to collections such as strings, arrays, associative arrays, or those that implement an opApply function or have basic Range methods. The "for each" loop is used if available, otherwise another loop is used for iteration.


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

    "Hello,How,Are,You,Today".split(',').join('.').writeln;
}

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


import std.stdio, std.numeric;

long myGCD(in long x, in long y) pure nothrow @nogc {
    if (y == 0)
        return x;
    return myGCD(y, x % y);
}

void main() {
    gcd(15, 10).writeln; // From Phobos.
    myGCD(15, 10).writeln;
}

calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.


import std.array, std.socket;

void main() {
    auto listener = new TcpSocket;
    assert(listener.isAlive);
    listener.bind(new InternetAddress(12321));
    listener.listen(10);

    Socket currSock;
    uint bytesRead;
    ubyte[1] buff;

    while (true) {
        currSock = listener.accept();
        while ((bytesRead = currSock.receive(buff)) > 0)
            currSock.send(buff);
        currSock.close();
        buff.clear();
    }
}

import std.stdio, std.socket, std.array;

void main() {
    enum ushort port = 7;
    enum int backlog = 10;
    enum int max_connections = 60;
    enum BUFFER_SIZE = 16;

    auto listener = new TcpSocket;
    assert(listener.isAlive);
    listener.bind(new InternetAddress(port));
    listener.listen(backlog);
    debug writeln("Listening on port ", port);

    // Room for listener.
    auto sset = new SocketSet(max_connections + 1);

    Socket[] sockets;
    char[BUFFER_SIZE] buf;

    for (;; sset.reset()) {
        sset.add(listener);
        foreach (each; sockets)
            sset.add(each);

        // Update socket set with only those sockets that have data
        // avaliable for reading. Options are for read, write,
        // and error.
        Socket.select(sset, null, null);

        // Read the data from each socket remaining, and handle
        // the request.
        for (int i = 0; ; i++) {
NEXT:
            if (i == sockets.length)
                break;
            if (sset.isSet(sockets[i])) {
                int read = sockets[i].receive(buf);
                if (Socket.ERROR == read) {
                    debug writeln("Connection error.");
                    goto SOCK_DOWN;
                } else if (read == 0) {
                    debug {
                        try {
                            // If the connection closed due to an
                            // error, remoteAddress() could fail.
                            writefln("Connection from %s closed.",
                                     sockets[i].remoteAddress()
                                     .toString());
                        } catch (SocketException) {
                            writeln("Connection closed.");
                        }
                    }
SOCK_DOWN:
                    sockets[i].close(); //Release socket resources now.

                    // Remove from socket from sockets, and id from
                    // threads.
                    if (i != sockets.length - 1)
                        sockets[i] = sockets.back;
                    sockets.length--;
                    debug writeln("\tTotal connections: ",
                                  sockets.length);
                    goto NEXT; // -i- is still the NEXT index.
                } else {
                    debug
                        writefln("Received %d bytes from %s:"
                                 ~ "\n-----\n%s\n-----",
                                 read,
                                 sockets[i].remoteAddress().toString(),
                                 buf[0 .. read]);

                    // Echo what was sent.
                    sockets[i].send(buf[0 .. read]);
                }
            }
        }

        // Connection request.
        if (sset.isSet(listener)) {
            Socket sn;
            try {
                if (sockets.length < max_connections) {
                    sn = listener.accept();
                    debug writefln("Connection from %s established.",
                                   sn.remoteAddress().toString());
                    assert(sn.isAlive);
                    assert(listener.isAlive);
                    sockets ~= sn;
                    debug writefln("\tTotal connections: %d",
                                   sockets.length);
                } else {
                    sn = listener.accept();
                    debug writefln("Rejected connection from %s;"
                                   ~ " too many connections.",
                                   sn.remoteAddress().toString());
                    assert(sn.isAlive);
                    sn.close();
                    assert(!sn.isAlive);
                    assert(listener.isAlive);
                }
            } catch (Exception e) {
                debug writefln("Error accepting: %s", e.toString());
                if (sn)
                    sn.close();
            }
        }
    }
}

The code implements an echo server that listens on TCP port 12321, accepts connections, and echoes back complete lines to clients. It supports simultaneous connections from multiple clients, handling each connection in a multi-threaded or multi-process manner. The server continues to respond to other clients even if one client sends a partial line or stops reading responses. Connection information is logged to standard output. The server is designed to prevent denial-of-service attacks by multiplexing clients. However, it processes buffers one character at a time and only supports connections from localhost for testing purposes.


"Implement a boolean function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, using the Phobos function standard. The function does not recognize binary and hex literals."


auto data = get("https://sourceforge.net");
writeln(data);

send a GET request to "https://www.w3.org/" without authentication, validate the host certificate, and print the response to the console. It also contrasts with the HTTP Request task and HTTPS request with authentication task. The task is implemented using curl.


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

struct Vec2 { // To be replaced with Phobos code.
    double x, y;

    Vec2 opBinary(string op="-")(in Vec2 other)
    const pure nothrow @safe @nogc {
        return Vec2(this.x - other.x, this.y - other.y);
    }

    typeof(x) cross(in Vec2 other) const pure nothrow @safe @nogc {
        return this.x * other.y - this.y * other.x;
    }
}

immutable(Vec2)[] clip(in Vec2[] subjectPolygon, in Vec2[] clipPolygon)
pure /*nothrow*/ @safe in {
    assert(subjectPolygon.length > 1);
    assert(clipPolygon.length > 1);
    // Probably clipPolygon needs to be convex and probably
    // its vertices need to be listed in a direction.
} out(result) {
    assert(result.length > 1);
} body {
    alias Edge = Tuple!(Vec2,"p", Vec2,"q");

    static enum isInside = (in Vec2 p, in Edge cle)
    pure nothrow @safe @nogc =>
        (cle.q.x - cle.p.x) * (p.y - cle.p.y) >
        (cle.q.y - cle.p.y) * (p.x - cle.p.x);

    static Vec2 intersection(in Edge se, in Edge cle)
    pure nothrow @safe @nogc {
        immutable dc = cle.p - cle.q;
        immutable dp = se.p - se.q;
        immutable n1 = cle.p.cross(cle.q);
        immutable n2 = se.p.cross(se.q);
        immutable n3 = 1.0 / dc.cross(dp);
        return Vec2((n1 * dp.x - n2 * dc.x) * n3,
                    (n1 * dp.y - n2 * dc.y) * n3);
    }

    // How much slower is this compared to lower-level code?
    static enum edges = (in Vec2[] poly) pure nothrow @safe @nogc =>
        // poly[$ - 1 .. $].chain(poly).zip!Edge(poly);
        poly[$ - 1 .. $].chain(poly).zip(poly).map!Edge;

    immutable(Vec2)[] result = subjectPolygon.idup; // Not nothrow.

    foreach (immutable clipEdge; edges(clipPolygon)) {
        immutable inputList = result;
        result.destroy;
        foreach (immutable inEdge; edges(inputList)) {
            if (isInside(inEdge.q, clipEdge)) {
                if (!isInside(inEdge.p, clipEdge))
                    result ~= intersection(inEdge, clipEdge);
                result ~= inEdge.q;
            } else if (isInside(inEdge.p, clipEdge))
                result ~= intersection(inEdge, clipEdge);
        }
    }

    return result;
}

// Code adapted from the C version.
void saveEPSImage(in string fileName, in Vec2[] subjPoly,
                  in Vec2[] clipPoly, in Vec2[] clipped)
in {
    assert(!fileName.empty);
    assert(subjPoly.length > 1);
    assert(clipPoly.length > 1);
    assert(clipped.length > 1);
} body {
    auto eps = File(fileName, "w");

    // The image bounding box is hard-coded, not computed.
    eps.writeln(
"%%!PS-Adobe-3.0
%%%%BoundingBox: 40 40 360 360
/l {lineto} def
/m {moveto} def
/s {setrgbcolor} def
/c {closepath} def
/gs {fill grestore stroke} def
");

    eps.writef("0 setlinewidth %g %g m ", clipPoly[0].tupleof);
    foreach (immutable cl; clipPoly[1 .. $])
        eps.writef("%g %g l ", cl.tupleof);
    eps.writefln("c 0.5 0 0 s gsave 1 0.7 0.7 s gs");

    eps.writef("%g %g m ", subjPoly[0].tupleof);
    foreach (immutable s; subjPoly[1 .. $])
        eps.writef("%g %g l ", s.tupleof);
    eps.writefln("c 0 0.2 0.5 s gsave 0.4 0.7 1 s gs");

    eps.writef("2 setlinewidth [10 8] 0 setdash %g %g m ",
               clipped[0].tupleof);
    foreach (immutable c; clipped[1 .. $])
        eps.writef("%g %g l ", c.tupleof);
    eps.writefln("c 0.5 0 0.5 s gsave 0.7 0.3 0.8 s gs");

    eps.writefln("%%%%EOF");
    eps.close;
    writeln(fileName, " written.");
}

void main() {
    alias V = Vec2;
    immutable subjectPolygon = [V(50, 150), V(200, 50), V(350, 150),
                                V(350, 300), V(250, 300), V(200, 250),
                                V(150, 350), V(100, 250), V(100, 200)];
    immutable clippingPolygon = [V(100, 100), V(300, 100),
                                 V(300, 300), V(100, 300)];
    immutable clipped = subjectPolygon.clip(clippingPolygon);
    writefln("%(%s\n%)", clipped);
    saveEPSImage("sutherland_hodgman_clipping_out.eps",
                 subjectPolygon, clippingPolygon, clipped);
}

Implement the Sutherland-Hodgman polygon clipping algorithm to find the intersection of a given arbitrary polygon and a convex polygon. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle and prints the sequence of points defining the resulting clipped polygon. It also provides an option to display all three polygons on a graphical surface, each in a different color, and generates an EPS file as output.


import std.algorithm;
import std.stdio;

void main() {
    immutable scores = [
        "Solomon": 44,
        "Jason": 42,
        "Errol": 42,
        "Garry": 41,
        "Bernard": 41,
        "Barry": 41,
        "Stephen": 39
    ];

    scores.standardRank;
    scores.modifiedRank;
    scores.denseRank;
    scores.ordinalRank;
    scores.fractionalRank;
}

/*
Standard ranking
1 44 Solomon
2 42 Jason
2 42 Errol
4 41 Garry
4 41 Bernard
4 41 Barry
7 39 Stephen
*/
void standardRank(const int[string] data) {
    writeln("Standard Rank");

    int rank = 1;
    foreach (value; data.values.dup.sort!"a>b".uniq) {
        int temp = rank;
        foreach(k,v; data) {
            if (v==value) {
                writeln(temp, " ", v, " ", k);
                rank++;
            }
        }
    }

    writeln;
}

/*
Modified ranking
1 44 Solomon
3 42 Jason
3 42 Errol
6 41 Garry
6 41 Bernard
6 41 Barry
7 39 Stephen
*/
void modifiedRank(const int[string] data) {
    writeln("Modified Rank");

    int rank = 0;
    foreach (value; data.values.dup.sort!"a>b".uniq) {
        foreach(k,v; data) {
            if (v==value) {
                rank++;
            }
        }
        foreach(k,v; data) {
            if (v==value) {
                writeln(rank, " ", v, " ", k);
            }
        }
    }

    writeln;
}

/*
Dense ranking
1 44 Solomon
2 42 Jason
2 42 Errol
3 41 Garry
3 41 Bernard
3 41 Barry
4 39 Stephen
*/
void denseRank(const int[string] data) {
    writeln("Dense Rank");

    int rank = 1;
    foreach (value; data.values.dup.sort!"a>b".uniq) {
        foreach(k,v; data) {
            if (v==value) {
                writeln(rank, " ", v, " ", k);
            }
        }
        rank++;
    }

    writeln;
}

/*
Ordinal ranking
1 44 Solomon
2 42 Jason
3 42 Errol
4 41 Garry
5 41 Bernard
6 41 Barry
7 39 Stephen
*/
void ordinalRank(const int[string] data) {
    writeln("Ordinal Rank");

    int rank = 1;
    foreach (value; data.values.dup.sort!"a>b".uniq) {
        foreach(k,v; data) {
            if (v==value) {
                writeln(rank, " ", v, " ", k);
                rank++;
            }
        }
    }

    writeln;
}

/*
Fractional ranking
1,0 44 Solomon
2,5 42 Jason
2,5 42 Errol
5,0 41 Garry
5,0 41 Bernard
5,0 41 Barry
7,0 39 Stephen
*/
void fractionalRank(const int[string] data) {
    writeln("Fractional Rank");

    int rank = 0;
    foreach (value; data.values.dup.sort!"a>b".uniq) {
        real avg = 0;
        int cnt;

        foreach(k,v; data) {
            if (v==value) {
                rank++;
                cnt++;
                avg+=rank;
            }
        }
        avg /= cnt;

        foreach(k,v; data) {
            if (v==value) {
                writef("%0.1f ", avg);
                writeln(v, " ", k);
            }
        }
    }

    writeln;
}

"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties."


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

    enum degrees = 45.0L;
    enum t0 = degrees * PI / 180.0L;
    writeln("Reference:  0.7071067811865475244008");
    writefln("Sine:       %.20f  %.20f", PI_4.sin, t0.sin);
    writefln("Cosine:     %.20f  %.20f", PI_4.cos, t0.cos);
    writefln("Tangent:    %.20f  %.20f", PI_4.tan, t0.tan);

    writeln;
    writeln("Reference:  0.7853981633974483096156");
    immutable real t1 = PI_4.sin.asin;
    writefln("Arcsine:    %.20f %.20f", t1, t1 * 180.0L / PI);

    immutable real t2 = PI_4.cos.acos;
    writefln("Arccosine:  %.20f %.20f", t2, t2 * 180.0L / PI);

    immutable real t3 = PI_4.tan.atan;
    writefln("Arctangent: %.20f %.20f", t3, t3 * 180.0L / PI);
}

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


import std.stdio, std.typecons, std.functional;

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

immutable Item[] items = [
    {"map",           9, 150, 1}, {"compass",      13,  35, 1},
    {"water",       153, 200, 3}, {"sandwich",     50,  60, 2},
    {"glucose",      15,  60, 2}, {"tin",          68,  45, 3},
    {"banana",       27,  60, 3}, {"apple",        39,  40, 3},
    {"cheese",       23,  30, 1}, {"beer",         52,  10, 3},
    {"suntan cream", 11,  70, 1}, {"camera",       32,  30, 1},
    {"t-shirt",      24,  15, 2}, {"trousers",     48,  10, 2},
    {"umbrella",     73,  40, 1}, {"w-trousers",   42,  70, 1},
    {"w-overcoat",   43,  75, 1}, {"note-case",    22,  80, 1},
    {"sunglasses",    7,  20, 1}, {"towel",        18,  12, 2},
    {"socks",         4,  50, 1}, {"book",         30,  10, 2}];

Tuple!(int, const(int)[]) chooseItem(in int iWeight, in int idx) nothrow @safe {
    alias memoChooseItem = memoize!chooseItem;
    if (idx < 0)
        return typeof(return)();

    int bestV;
    const(int)[] bestList;
    with (items[idx])
        foreach (immutable i; 0 .. quantity + 1) {
            immutable wlim = iWeight - i * weight;
            if (wlim < 0)
                break;

            //const (val, taken) = memoChooseItem(wlim, idx - 1);
            const val_taken = memoChooseItem(wlim, idx - 1);
            if (val_taken[0] + i * value > bestV) {
                bestV = val_taken[0] + i * value;
                bestList = val_taken[1] ~ i;
            }
        }

    return tuple(bestV, bestList);
}

void main() {
    // const (v, lst) = chooseItem(400, items.length - 1);
    const v_lst = chooseItem(400, items.length - 1);

    int w;
    foreach (immutable i, const cnt; v_lst[1])
        if (cnt > 0) {
            writeln(cnt, " ", items[i].name);
            w += items[i].weight * cnt;
        }

    writeln("Total weight: ", w, " Value: ", v_lst[0]);
}

The code implements a solution to the bounded knapsack problem using memoization. It helps a tourist to decide which items to carry on a trip to maximize the total value without exceeding the weight limit of 4 kg. The items, their weights, values, and available quantities are given in a list, and the tourist can only take whole units of any item.


import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;

__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
    /*
     * Signal safety: It is not safe to call clock(), printf(),
     * or exit() inside a signal handler. Instead, we set a flag.
     */
    gotint = 1;
}

void main() {
    auto sw = StopWatch(AutoStart.yes);
    signal(SIGINT, &handleSigint);
    for (int i=0; !gotint;) {
        Thread.sleep(500_000.usecs);
        if (gotint) {
            break;
        }
        writeln(++i);
    }
    sw.stop();
    auto td = sw.peek();
    writeln("Program has run for ", td);
}

an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.


void main() {
    import std.string;

    immutable s = "12349".succ;
    assert(s == "12350");
}


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

string commonDirPath(in string[] paths, in string sep = "/") pure {
    if (paths.empty)
        return null;
    return paths.map!(p => p.split(sep)).reduce!commonPrefix.join(sep);
}

void main() {
    immutable paths = ["/home/user1/tmp/coverage/test",
                       "/home/user1/tmp/covert/operator",
                       "/home/user1/tmp/coven/members"];
    writeln(`The common path is: "`, paths.commonDirPath, '"');
}

"Create a function that identifies and returns the common directory path from a set of given directory paths, using a specified directory separator. The function also includes a test case using '/' as the directory separator and three specific strings as input paths. The code utilizes the 'std.algorithm.commonPrefix' function to find the common prefix of two ranges."


import std.stdio;

void main() {
    auto items = [0,1,2,3,4,5];
    sattoloCycle(items);
    items.writeln;
}

/// The Sattolo cycle is an algorithm for randomly shuffling an array in such a way that each element ends up in a new position.
void sattoloCycle(R)(R items) {
    import std.algorithm : swapAt;
    import std.random : uniform;

    for (int i=items.length; i-- > 1;) {
        int j = uniform(0, i);
        items.swapAt(i, j);
    }
}

unittest {
    import std.range : lockstep;
    auto o = ['a', 'b', 'c', 'd', 'e'];

    auto s = o.dup;
    sattoloCycle(s);
    foreach (a, b; lockstep(o, s)) {
        assert(a != b, "An element stayed in place unexpectedly.");
    }
}

Implement the Sattolo cycle algorithm to randomly shuffle an array ensuring each element ends up in a new position. The algorithm modifies the input array in-place, but can be amended to return a new array. The algorithm can also be amended to iterate from left to right. The difference between this and the Knuth shuffle is the range from which j is chosen. Test cases are provided for validation.


import std.stdio, std.algorithm;

T median(T)(T[] nums) pure nothrow {
    nums.sort();
    if (nums.length & 1)
        return nums[$ / 2];
    else
        return (nums[$ / 2 - 1] + nums[$ / 2]) / 2.0;
}

void main() {
    auto a1 = [5.1, 2.6, 6.2, 8.8, 4.6, 4.1];
    writeln("Even median: ", a1.median);

    auto a2 = [5.1, 2.6, 8.8, 4.6, 4.1];
    writeln("Odd median:  ", a2.median);
}

The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.


import std.stdio, std.algorithm, std.conv;

/// With if-else.
void fizzBuzz(in uint n) {
    foreach (immutable i; 1 .. n + 1)
        if (!(i % 15))
            "FizzBuzz".writeln;
        else if (!(i % 3))
            "Fizz".writeln;
        else if (!(i % 5))
            "Buzz".writeln;
        else
            i.writeln;
}

/// With switch case.
void fizzBuzzSwitch(in uint n) {
    foreach (immutable i; 1 .. n + 1)
        switch (i % 15) {
            case 0:
                "FizzBuzz".writeln;
                break;
            case 3, 6, 9, 12:
                "Fizz".writeln;
                break;
            case 5, 10:
                "Buzz".writeln;
                break;
            default:
                i.writeln;
        }
}

void fizzBuzzSwitch2(in uint n) {
    foreach (immutable i; 1 .. n + 1)
        (i % 15).predSwitch(
        0,       "FizzBuzz",
        3,       "Fizz",
        5,       "Buzz",
        6,       "Fizz",
        9,       "Fizz",
        10,      "Buzz",
        12,      "Fizz",
        /*else*/ i.text).writeln;
}

void main() {
    100.fizzBuzz;
    writeln;
    100.fizzBuzzSwitch;
    writeln;
    100.fizzBuzzSwitch2;
}

import std;

void main()
{
    auto fizzbuzz(in uint i)
    {
        string r;
        if (i % 3 == 0) r ~= "fizz";
        if (i % 5 == 0) r ~= "buzz";
        if (r.length == 0) r ~= i.to!string;
        return r;
    }

    enum r = 1.iota(101).map!fizzbuzz;

    r.each!writeln;
}

print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.


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

    for (real y = -1.2; y < 1.2; y += 0.05) {
        for (real x = -2.05; x < 0.55; x += 0.03) {
            auto z = 0.complex;
            foreach (_; 0 .. 100)
                z = z ^^ 2 + complex(x, y);
            write(z.abs < 2 ? '#' : '.');
        }
        writeln;
    }
}

generate and draw the Mandelbrot set using various algorithms and functions. It utilizes std.complex as D built-in complex numbers are deprecated. The output produced is similar to the original.


import std.stdio;

void main() {
    immutable array = [1, 2, 3, 4, 5];

    int sum = 0;
    int prod = 1;

    foreach (x; array) {
        sum += x;
        prod *= x;
    }

    writeln("Sum: ", sum);
    writeln("Product: ", prod);
}

"Calculates the sum and product of all integers in an array in a single pass."


"Determines if a given year is a leap year in the Gregorian calendar using the datetime library."


import std.bitmanip, core.stdc.string, std.conv, std.math, std.array,
       std.string;

version (D_InlineAsm_X86) {} else {
    static assert(false, "For X86 machine only.");
}

// CTFE construction of transform expressions.
uint S(in uint n) pure nothrow @safe @nogc {
    static immutable aux = [7u, 12, 17, 22, 5, 9, 14, 20, 4, 11,
                            16, 23, 6, 10, 15, 21];
    return aux[(n / 16) * 4 + (n % 4)];
}

uint K(in uint n) pure nothrow @safe @nogc {
    uint r = 0;
    if (n <= 15)
        r = n;
    else if (n <= 31)
        r = 5 * n + 1;
    else if (n <= 47)
        r = 3 * n + 5;
    else
        r = 7 * n;
    return r % 16;
}

uint T(in uint n) pure nothrow @nogc {
    return cast(uint)(abs(sin(n + 1.0L)) * (2UL ^^ 32));
}

string[] ABCD(in int n) pure nothrow {
    enum abcd = ["EAX", "EBX", "ECX", "EDX"];
    return abcd[(64 - n) % 4 .. 4] ~ abcd[0 .. (64 - n) % 4];
}

string SUB(in int n, in string s) pure nothrow {
    return s
           .replace("ax", n.ABCD[0])
           .replace("bx", n.ABCD[1])
           .replace("cx", n.ABCD[2])
           .replace("dx", n.ABCD[3]);
}

// FF, GG, HH & II expressions part 1 (F, G, H, I).
string fghi1(in int n) pure nothrow @nogc {
    switch (n / 16) {
        case 0:
            // (bb & cc) | (~bb & dd)
            return q{
                        mov ESI, bx;
                        mov EDI, bx;
                        not ESI;
                        and EDI, cx;
                        and ESI, dx;
                        or EDI, ESI;
                        add ax, EDI;
                    };
        case 1:
            // (dd & bb) | (~dd & cc)
            return q{
                        mov ESI, dx;
                        mov EDI, dx;
                        not ESI;
                        and EDI, bx;
                        and ESI, cx;
                        or EDI, ESI;
                        add ax, EDI;
                    };
        case 2: // (bb ^ cc ^ dd)
            return q{
                        mov EDI, bx;
                        xor EDI, cx;
                        xor EDI, dx;
                        add ax, EDI;
                    };
        case 3: // (cc ^ (bb | ~dd))
            return q{
                       mov EDI, dx;
                       not EDI;
                       or EDI, bx;
                       xor EDI, cx;
                       add ax, EDI;
                    };
        default:
            assert(false);
    }
}

// FF, GG, HH & II expressions part 2.
string fghi2(in int n) pure nothrow {
    return q{
                add ax, [EBP + 4 * KK];
                add ax, TT;
            } ~ n.fghi1;
}

// FF, GG, HH & II expressions prepended with previous parts
// & subsitute ABCD.
string FGHI(in int n) pure nothrow {
    // aa = ((aa << SS)|( aa >>> (32 - SS))) + bb = ROL(aa, SS) + bb
    return SUB(n, n.fghi2 ~ q{
                                rol ax, SS;
                                add ax, bx;
                             });
}

string genExpr(uint n) pure nothrow {
    return FGHI(n)
           .replace("SS", n.S.text)
           .replace("KK", n.K.text)
           .replace("TT", "0x" ~ to!string(n.T, 16));
}

string genTransformCode(int n) pure nothrow {
    return (n < 63) ? n.genExpr ~ genTransformCode(n + 1) : n.genExpr;
}

enum string coreZMD5 = 0.genTransformCode;

struct ZMD5 {
    uint[4] state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];
    ulong count;
    ubyte[64] buffer;

    ubyte[64] padding = [
      0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0];

    private void transform(ubyte* block) pure nothrow @nogc {
        uint[16] x = void;

        version (BigEndian) {
            foreach (immutable i; 0 .. 16)
                x[i] = littleEndianToNative!uint(*cast(ubyte[4]*)&block[i * 4]);
        } else {
            (cast(ubyte*)x.ptr)[0 .. 64] = block[0 .. 64];
        }

        auto pState = state.ptr;
        auto pBuffer = x.ptr;

        asm pure nothrow @nogc {
            mov  ESI, pState[EBP];
            mov  EDX, [ESI + 3 * 4];
            mov  ECX, [ESI + 2 * 4];
            mov  EBX, [ESI + 1 * 4];
            mov  EAX, [ESI + 0 * 4];
            push EBP;
            push ESI;

            mov  EBP, pBuffer[EBP];
        }

        mixin("asm pure nothrow @nogc { " ~ coreZMD5 ~ "}");

        asm pure nothrow @nogc {
            pop ESI;
            pop EBP;
            add [ESI + 0 * 4], EAX;
            add [ESI + 1 * 4], EBX;
            add [ESI + 2 * 4], ECX;
            add [ESI + 3 * 4], EDX;
        }
        x[] = 0;
    }

    void update(in void[] input) pure nothrow @nogc {
        auto inputLen = input.length;
        uint index = (count >> 3) & 0b11_1111U;
        count += inputLen * 8;
        immutable uint partLen = 64 - index;

        uint i;
        if (inputLen >= partLen) {
            memcpy(&buffer[index], input.ptr, partLen);
            transform(buffer.ptr);
            for (i = partLen; i + 63 < inputLen; i += 64)
                transform((cast(ubyte[])input)[i .. i + 64].ptr);
            index = 0;
        } else
            i = 0;

        if (inputLen - i)
            memcpy(&buffer[index], &input[i], inputLen - i);
    }

    void finish(ref ubyte[16] digest) pure nothrow @nogc {
        ubyte[8] bits = void;
        bits[0 .. 8] = nativeToLittleEndian(count)[];

        immutable uint index = (count >> 3) & 0b11_1111U;
        immutable uint padLen = (index < 56) ?
                                (56 - index) : (120 - index);
        update(padding[0 .. padLen]);
        update(bits);

        digest[0 .. 4]   = nativeToLittleEndian(state[0])[];
        digest[4 .. 8]   = nativeToLittleEndian(state[1])[];
        digest[8 .. 12]  = nativeToLittleEndian(state[2])[];
        digest[12 .. 16] = nativeToLittleEndian(state[3])[];

        // Zeroize sensitive information.
        memset(&this, 0, ZMD5.sizeof);
    }
}

string getDigestString(in void[][] data...) pure {
    ZMD5 ctx;
    foreach (datum; data)
        ctx.update(datum);
    ubyte[16] digest;
    ctx.finish(digest);
    return format("%-(%02X%)", digest);
}

void main() { // Benchmark code --------------
    import std.stdio, std.datetime, std.digest.md;

    writefln(`md5  digest("")  = %-(%02X%)`, "".md5Of);
    writefln(`zmd5 digest("")  = %s`, "".getDigestString);

    enum megaBytes = 512;
    writefln("\nTest performance / message size %dMBytes:", megaBytes);
    auto data = new float[megaBytes * 0x40000 + 13];

    StopWatch sw;
    sw.start;
    immutable d1 = data.md5Of;
    sw.stop;
    immutable time1 = sw.peek.msecs / 1000.0;
    writefln("digest(data) = %-(%02X%)", d1);
    writefln("std.md5: %8.2f M/sec  ( %8.2f secs)",
             megaBytes / time1, time1);

    sw.reset;
    sw.start;
    immutable d2 = data.getDigestString;
    sw.stop;
    immutable time2 = sw.peek.msecs / 1000.0;
    writefln("digest(data) = %s", d2);
    writefln("zmd5   : %8.2f M/sec  ( %8.2f secs)",
             megaBytes / time2, time2);
}

Output (dmd compiler):
md5  digest("")  = D41D8CD98F00B204E9800998ECF8427E
zmd5 digest("")  = D41D8CD98F00B204E9800998ECF8427E

Test performance / message size 512MBytes:
digest(data) = A36190ECA92203A477EFC4DAB966CE6F
std.md5:    45.85 M/sec  (    11.17 secs)
digest(data) = A36190ECA92203A477EFC4DAB966CE6F
zmd5   :   244.86 M/sec  (     2.09 secs)

Output (ldc2 compiler):
md5  digest("")  = D41D8CD98F00B204E9800998ECF8427E
zmd5 digest("")  = D41D8CD98F00B204E9800998ECF8427E

Test performance / message size 512MBytes:
digest(data) = A36190ECA92203A477EFC4DAB966CE6F
std.md5:   310.12 M/sec  (     1.65 secs)
digest(data) = A36190ECA92203A477EFC4DAB966CE6F
zmd5   :   277.06 M/sec  (     1.85 secs)

The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm's specifications without using built-in or external hashing libraries. It generates a correct message digest for an input string and demonstrates bit manipulation, working with little-endian data, and attention to boundary conditions. The code also includes challenges and implementation choices made during the development process. However, it does not mimic all calling modes and does not use built-in MD5 functions or library routines. The code has been validated with verification strings and hashes from RFC 1321.


import std.stdio, std.range;

void main() {
    int sol = 1;
    writeln("\t\tFIRE\t\tPOLICE\t\tSANITATION");
    foreach( f; iota(1,8) ) {
        foreach( p; iota(1,8) ) {
            foreach( s; iota(1,8) ) {
                if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {
                    writefln("SOLUTION #%2d:\t%2d\t\t%3d\t\t%6d", sol++, f, p, s);
                }
            }
        }
    }
}

		FIRE		POLICE		SANITATION
SOLUTION # 1:	 1		  4		     7
SOLUTION # 2:	 1		  6		     5
SOLUTION # 3:	 2		  4		     6
SOLUTION # 4:	 2		  6		     4
SOLUTION # 5:	 3		  2		     7
SOLUTION # 6:	 3		  4		     5
SOLUTION # 7:	 4		  2		     6
SOLUTION # 8:	 4		  6		     2
SOLUTION # 9:	 5		  4		     3
SOLUTION #10:	 5		  6		     1
SOLUTION #11:	 6		  2		     4
SOLUTION #12:	 6		  4		     2
SOLUTION #13:	 7		  2		     3
SOLUTION #14:	 7		  4		     1

generate all unique combinations of numbers between 1 and 7 for the police, sanitation, and fire departments such that the sum of the numbers is 12 and the police department number is even.


void main() {
    string src = "This is a string";

    // copy contents:
    auto dest1 = src.idup;

    // copy contents to mutable char array
    auto dest2 = src.dup;

    // copy just the fat reference of the string
    auto dest3 = src;
}

"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable."


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

int male(in int n) pure nothrow {
    return n ? n - male(n - 1).female : 0;
}

int female(in int n) pure nothrow {
    return n ? n - female(n - 1).male : 1;
}

void main() {
    20.iota.map!female.writeln;
    20.iota.map!male.writeln;
}

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.


import std.stdio, std.random;

void main() {
    const items = ["foo", "bar", "baz"];
    items[uniform(0, $)].writeln;
}

demonstrate how to select a random element from a list.


import std.stdio, std.uri;

void main() {
    writeln(decodeComponent("http%3A%2F%2Ffoo%20bar%2F"));
}

http://foo bar/

provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


import std.stdio, std.array, std.range, std.traits;

/// Recursive.
bool binarySearch(R, T)(/*in*/ R data, in T x) pure nothrow @nogc
if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {
    if (data.empty)
        return false;
    immutable i = data.length / 2;
    immutable mid = data[i];
    if (mid > x)
        return data[0 .. i].binarySearch(x);
    if (mid < x)
        return data[i + 1 .. $].binarySearch(x);
    return true;
}

/// Iterative.
bool binarySearchIt(R, T)(/*in*/ R data, in T x) pure nothrow @nogc
if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {
    while (!data.empty) {
        immutable i = data.length / 2;
        immutable mid = data[i];
        if (mid > x)
            data = data[0 .. i];
        else if (mid < x)
            data = data[i + 1 .. $];
        else
            return true;
    }
    return false;
}

void main() {
    /*const*/ auto items = [2, 4, 6, 8, 9].assumeSorted;
    foreach (const x; [1, 8, 10, 9, 5, 2])
        writefln("%2d %5s %5s %5s", x,
                 items.binarySearch(x),
                 items.binarySearchIt(x),
                 // Standard Binary Search:
                 !items.equalRange(x).empty);
}

The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a "secret value" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.


void main(in string[] args) {
    import std.stdio;

    foreach (immutable i, arg; args[1 .. $])
        writefln("#%2d : %s", i + 1, arg);
}

The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c "alpha beta" -h "gamma"'. It also includes functionalities for intelligent parsing of these arguments.


import std.stdio, std.json;

void main() {
    auto j = parseJSON(`{ "foo": 1, "bar": [10, "apples"] }`);
    writeln(toJSON(&j));
}

{"foo":1,"bar":[10,"apples"]}

"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON."


import std.stdio, std.math;

real nthroot(in int n, in real A, in real p=0.001) pure nothrow {
    real[2] x = [A, A / n];
    while (abs(x[1] - x[0]) > p)
        x = [x[1], ((n - 1) * x[1] + A / (x[1] ^^ (n-1))) / n];
    return x[1];
}

void main() {
    writeln(nthroot(10, 7131.5 ^^ 10));
    writeln(nthroot(6, 64));
}

Implement the principal nth root algorithm for a positive real number A.


import std.stdio, std.socket;

void main() {
    writeln(Socket.hostName());
}

"Determines and outputs the hostname of the current system where the routine is running."


import std.stdio;

void main() {
    write("Leonardo Numbers: ");
    leonardoNumbers( 25 );

    write("Fibonacci Numbers: ");
    leonardoNumbers( 25, 0, 1, 0 );
}

void leonardoNumbers(int count, int l0=1, int l1=1, int add=1) {
    int t;
    for (int i=0; i<count; ++i) {
        write(l0, " ");
        t = l0 + l1 + add;
        l0 = l1;
        l1 = t;
    }
    writeln();
}

generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.


import std.stdio, std.random, std.math, std.algorithm, std.range,
       std.typetuple;

void main() {
    void op(char c)() {
        if (stack.length < 2)
            throw new Exception("Wrong expression.");
        stack[$ - 2] = mixin("stack[$ - 2]" ~ c ~ "stack[$ - 1]");
        stack.popBack();
    }

    const problem = iota(4).map!(_ => uniform(1, 10))().array();
    writeln("Make 24 with the digits: ", problem);

    double[] stack;
    int[] digits;
    foreach (const char c; readln())
        switch (c) {
            case ' ', '\t', '\n': break;
            case '1': .. case '9':
                stack ~= c - '0';
                digits ~= c - '0';
                break;
            foreach (o; TypeTuple!('+', '-', '*', '/')) {
                case o: op!o(); break;
            }
            break;
            default: throw new Exception("Wrong char: " ~ c);
        }

    if (!digits.sort().equal(problem.dup.sort()))
        throw new Exception("Not using the given digits.");
    if (stack.length != 1)
        throw new Exception("Wrong expression.");
    writeln("Result: ", stack[0]);
    writeln(abs(stack[0] - 24) < 0.001 ? "Good job!" : "Try again.");
}

Make 24 with the digits: [1, 8, 9, 8]
8 1 - 9 + 8 +
Result: 24
Good job!

The code generates four random digits from 1 to 9 and prompts the user to input an arithmetic expression using these digits. It then evaluates the expression to check if it equals 24. The code allows the use of multiplication, division, addition, subtraction operators, and brackets. It does not allow the formation of multiple-digit numbers from the given digits.