Translation of: C++

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.


Standard Version[edit]

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


Translation of: C
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.


Translation of: Python

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.


Translation of: C
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'.


Textual Version[edit]

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.


Translation of: C++
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."


Translation of: C++
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.


Short Functional Version[edit]
import std.algorithm, std.array;

alias encode = group;

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

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

Basic Imperative Version[edit]
import std.stdio, std.array, std.conv;

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

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

    return count.text ~ last ~ output;
}

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

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

    return result;
}

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

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


import std.stdio;

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

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


import std.stdio, std.uri;

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

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

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


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

struct Item {
    string name;
    real amount, value;

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

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

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

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

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

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

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


Short Functional Version[edit]
import std.stdio, std.algorithm, std.string, std.exception, std.file;

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

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


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

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

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

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

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

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

import std.stdio, std.array;

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

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

    return mat;
}

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

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


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

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

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

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

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


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

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

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

Hybrid[edit]
Works with: D version 1
Library: Hybrid

import "themes/default.cfg"

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

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

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

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

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

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

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

		Thread.yield();
	}
}

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


import std.stdio: writeln;

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

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

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


import std.stdio, std.string;

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

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

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

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


import std.stdio, std.range;

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

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

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


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

void main() {
    import std.stdio;

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

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


void main() {
    import std.stdio;

    enum width = 512, height = 512;

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

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


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

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

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

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


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

struct PiDigits {
    immutable uint nDigits;

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

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

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

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

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

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


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


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

void main() {
    assert(ackermann(2, 4) == 11);
}

More Efficient Version[edit]
Translation of: Mathematica
import std.stdio, std.bigint, std.conv;

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

    return result;
}

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

    return ack(m, n.BigInt);
}

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

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

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


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


Short Version[edit]

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

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

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


import std.stdio: writeln;

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

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

demonstrate how to concatenate two arrays.


Dynamic Programming Version[edit]
Translation of: Python
import std.stdio, std.algorithm, std.typecons, std.array, std.range;

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

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

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

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

    return result;
}

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

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

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


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

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

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

    return engagedTo;
}

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

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

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

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

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

    return true;
}

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

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

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

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

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

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

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

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

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


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

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

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

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

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


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


Basic Version[edit]
Translation of: Python

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

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

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

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

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


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

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

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


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

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


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

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

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


void main() {
    import std.stdio;

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

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


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

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

void main() {
    import std.stdio;

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

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

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

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


High-level 32-bit Unicode Version[edit]
import std.traits, std.algorithm;

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

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

Mid-level 32-bit Unicode Version[edit]
import std.traits;

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

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

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

Low-level 32-bit Unicode Version[edit]
import std.stdio, core.exception, std.traits;

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

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

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

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

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

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

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

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


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

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

Library: tango
import tango.sys.Environment;

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

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


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

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

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


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

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

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

Iterative[edit]
public static ulong Fib(uint x) {
    if (x == 0) return 0;

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

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

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


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

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

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

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

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

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


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

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

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

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


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

using System.Linq;

// ...

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

// ...

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

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

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