How to resolve the algorithm Zig-zag matrix step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Zig-zag matrix step by step in the D programming language

Table of Contents

Problem Statement

Produce a zig-zag array.

A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the
numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images).

For example, given   5,   produce this array:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Zig-zag matrix step by step in the D programming language

Source code in the d programming language

int[][] zigZag(in int n) pure nothrow @safe {
    static void move(in int n, ref int i, ref int j)
    pure nothrow @safe @nogc {
        if (j < n - 1) {
            if (i > 0) i--;
            j++;
        } else
            i++;
    }

    auto a = new int[][](n, n);
    int x, y;
    foreach (v; 0 .. n ^^ 2) {
        a[y][x] = v;
        (x + y) % 2 ? move(n, x, y) : move(n, y, x);
    }
    return a;
}

void main() {
    import std.stdio;

    writefln("%(%(%2d %)\n%)", 5.zigZag);
}


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

int[][] zigZag(in int n) pure nothrow {
    static struct P2 { int x, y; }
    const L = iota(n ^^ 2).map!(i => P2(i % n, i / n)).array
              .sort!q{ (a.x + a.y == b.x + b.y) ?
                       ((a.x + a.y) % 2 ? a.y < b.y : a.x < b.x) :
                       (a.x + a.y) < (b.x + b.y) }.release;

    auto result = new typeof(return)(n, n);
    foreach (immutable i, immutable p; L)
        result[p.y][p.x] = i;
    return result;
}

void main() {
    writefln("%(%(%2d %)\n%)", 5.zigZag);
}


  

You may also check:How to resolve the algorithm Loops/For with a specified step step by step in the Lambdatalk programming language
You may also check:How to resolve the algorithm Morse code step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Natural sorting step by step in the Racket programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the Elixir programming language
You may also check:How to resolve the algorithm Collections step by step in the Gambas programming language