On Monday, 24 November 2025 at 14:37:22 UTC, Jabba Laci wrote:
I implemented [Advent of Code 2015, Day 6, Part 1](https://adventofcode.com/2015/day/6) in D. The code is here: https://github.com/jabbalaci/AdventOfCode2015/tree/main/day06/d/part1 . It runs for 3 seconds. I found it a bit much, so I also wrote it in Python. To my surprise, the Python program also ran for 3 seconds. I expected that the D program should be much faster.

For grins, I compiled yours on my little laptop, got 3.027 seconds runtime, then did the obvious conversion to a simple 2D array, which runs in 0.019 seconds.

Andy

```d
#!/usr/bin/env rdmd

import std.algorithm;
import std.conv;
import std.file;
import std.stdio;
import std.string;

const MAX_X = 1_000;
const MAX_Y = 1_000;
alias Dvals = ubyte[MAX_X][MAX_Y];

enum Option
{
    off = 0,
    on = 1,
    toggle = 2
}

private void
extract_pair(const string s, out size_t x, out size_t y)
{
    auto parts = s.split(",");
    x = parts[0].to!int;
    y = parts[1].to!int;
}

void process_line(ref Dvals d, in string line)
{
    auto parts = line.split();
    Option option;
    // dfmt off
    if (parts[1] == "on") {
        option = Option.on;
    } else if (parts[1] == "off") {
        option = Option.off;
    } else if (parts[0] == "toggle") {
        option = Option.toggle;
    } else {
        assert(0);
    }
    // dfmt on

    size_t x1, y1, x2, y2;
    if (option == Option.on || option == Option.off)
    {
        extract_pair(parts[2], x1, y1);
        extract_pair(parts[$ - 1], x2, y2);
        const ubyte val = (option == Option.on) ? 1 : 0;
        for (size_t i = x1; i <= x2; ++i)
        {
            for (size_t j = y1; j <= y2; ++j)
            {
                d[i][j] = val; // off: 0, on: 1
            }
        }
    }
    else if (option == Option.toggle)
    {
        extract_pair(parts[1], x1, y1);
        extract_pair(parts[$ - 1], x2, y2);
        for (size_t i = x1; i <= x2; ++i)
        {
            for (size_t j = y1; j <= y2; ++j)
            {
                d[i][j] ^= 1;
            }
        }
    }
    else
    {
        assert(0);
    }
}

auto
get_result(in Dvals d)
{
    // if value is 0: off, 1: on
    uint res = 0;
    foreach(x; 0 .. MAX_X) {
        foreach(y; 0 .. MAX_Y) {
            res += d[x][y];
        }
    }
    return res;
}

void main()
{
    // const fname = "example1.txt";
    // const fname = "example2.txt";
    // const fname = "example3.txt";
    const fname = "input.txt";

    const lines = readText(fname).splitLines;
    Dvals d;

    foreach (line; lines)
    {
        process_line(d, line);
    }
    int result = get_result(d);
    writeln(result);
}
```

Reply via email to