Function send_mail(from,recipient,cc,subject,message)
	With CreateObject("CDO.Message")
		.From = from
		.To = recipient
		.CC = cc
		.Subject = subject
		.Textbody = message
		.Configuration.Fields.Item _
			("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
		.Configuration.Fields.Item _
			("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
		        "mystmpserver"
		.Configuration.Fields.Item _
		    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
		.Configuration.Fields.Update
		.Send
	End With
End Function

Call send_mail("Alerts@alerts.org","jkspeed@jkspeed.org","","Test Email","this is a test message")

Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.


For i = 0 To 20
	WScript.StdOut.WriteLine Oct(i)
Next

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.


function Squish( s1 )
	dim sRes
	sRes = vbNullString
	dim i, c
	for i = 1 to len( s1 )
		c = lcase( mid( s1, i, 1 ))
		if instr( "abcdefghijklmnopqrstuvwxyz0123456789", c ) then
			sRes = sRes & c
		end if
	next
	Squish = sRes
end function

function isPalindrome( s1 )
	dim squished
	squished = Squish( s1 )
	isPalindrome = ( squished = StrReverse( squished ) )
end function
wscript.echo isPalindrome( "My dog has fleas")
wscript.echo isPalindrome( "Madam, I'm Adam.")
wscript.echo isPalindrome( "1 on 1")
wscript.echo isPalindrome( "In girum imus nocte et consumimur igni")

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.


var s = "socat".*;
std.mem.reverse(u8, &s);

var s = "socat".*;
std.mem.reverse(u8, s[0..]);

↑ https://bugs.openjdk.org/browse/JDK-8291660

take a string input, reverse it, and handle Unicode combining characters properly. The string is dereferenced to an array using `.*` and reversed in-place using `std.mem.reverse`. The final reversed string is stored in `s`. Tested on version 0.9.0.


const std = @import("std");

pub fn main() !void {
    const RndGen = std.rand.DefaultPrng;
    var rnd = RndGen.init(42);
    // possible improvement: make rng fair
    var rand_num1: u5 = undefined;
    var rand_num2: u5 = undefined;
    while (true) {
        rand_num1 = rnd.random().int(u5) % 20;
        try std.io.getStdOut().writer().print("{d}\n", .{rand_num1});
        if (rand_num1 == 10)
            break;
        rand_num2 = rnd.random().int(u5) % 20;
        try std.io.getStdOut().writer().print("{d}\n", .{rand_num2});
    }
}

generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.


const std = @import("std");

pub fn main() !void {
    var in = try std.fs.cwd().openFile("input.txt", .{});
    defer in.close();
    var out = try std.fs.cwd().openFile("output.txt", .{ .mode = .write_only });
    defer out.close();
    var file_reader = in.reader();
    var file_writer = out.writer();
    var buf: [100]u8 = undefined;
    var read: usize = 1;
    while (read > 0) {
        read = try file_reader.readAll(&buf);
        try file_writer.writeAll(buf[0..read]);
    }
}

demonstrate reading the contents of "input.txt" file into a variable and then writing this variable's contents into a new file called "output.txt".


const std = @import("std");

pub fn main() !void {
    const stdout_wr = std.io.getStdOut().writer();
    const string = "alphaBETA";
    var lower: [string.len]u8 = undefined;
    var upper: [string.len]u8 = undefined;
    for (string) |char, i| {
        lower[i] = std.ascii.toLower(char);
        upper[i] = std.ascii.toUpper(char);
    }
    try stdout_wr.print("lower: {s}\n", .{lower});
    try stdout_wr.print("upper: {s}\n", .{upper});

    // TODO use https://github.com/jecolon/zigstr
}

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


const std = @import("std");
pub fn main() !void {
    const stdout_wr = std.io.getStdOut().writer();
    var i: u8 = 1;
    while (i <= 10) : (i += 1) {
        try stdout_wr.print("{d}", .{i});
        if (i == 10) {
            try stdout_wr.writeAll("\n");
        } else {
            try stdout_wr.writeAll(", ");
        }
    }
}

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


const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer {
        const ok = gpa.deinit();
        std.debug.assert(ok == .ok);
    }
    const allocator = gpa.allocator();

    {
        const nc = try getCombs(allocator, 1, 7, true);
        defer allocator.free(nc.combinations);
        try stdout.print("{d} unique solutions in 1 to 7\n", .{nc.num});
        try stdout.print("{any}\n", .{nc.combinations});
    }
    {
        const nc = try getCombs(allocator, 3, 9, true);
        defer allocator.free(nc.combinations);
        try stdout.print("{d} unique solutions in 3 to 9\n", .{nc.num});
        try stdout.print("{any}\n", .{nc.combinations});
    }
    {
        const nc = try getCombs(allocator, 0, 9, false);
        defer allocator.free(nc.combinations);
        try stdout.print("{d} non-unique solutions in 0 to 9\n", .{nc.num});
    }
}
/// Caller owns combinations slice memory.
fn getCombs(allocator: Allocator, low: u16, high: u16, unique: bool) !struct { num: usize, combinations: [][7]usize } {
    var num: usize = 0;
    var valid_combinations = std.ArrayList([7]usize).init(allocator);
    for (low..high + 1) |a|
        for (low..high + 1) |b|
            for (low..high + 1) |c|
                for (low..high + 1) |d|
                    for (low..high + 1) |e|
                        for (low..high + 1) |f|
                            for (low..high + 1) |g|
                                if (validComb(a, b, c, d, e, f, g))
                                    if (!unique or try isUnique(allocator, a, b, c, d, e, f, g)) {
                                        num += 1;
                                        try valid_combinations.append([7]usize{ a, b, c, d, e, f, g });
                                    };
    return .{ .num = num, .combinations = try valid_combinations.toOwnedSlice() };
}
fn isUnique(allocator: Allocator, a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize) !bool {
    var data = std.AutoArrayHashMap(usize, void).init(allocator);
    defer data.deinit();
    try data.put(a, {});
    try data.put(b, {});
    try data.put(c, {});
    try data.put(d, {});
    try data.put(e, {});
    try data.put(f, {});
    try data.put(g, {});
    return data.count() == 7;
}
fn validComb(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize) bool {
    const square1 = a + b;
    const square2 = b + c + d;
    const square3 = d + e + f;
    const square4 = f + g;
    return square1 == square2 and square2 == square3 and square3 == square4;
}

The code finds all possible solutions for a puzzle where seven variables, represented by letters a through g, are replaced with decimal digits within a given range. The sum of the variables in each of the four squares should be equal. The code generates all unique solutions for ranges 1-7 and 3-9, and counts the number of solutions, including non-unique ones, for the range 0-9. The code is a translation of a Go solution into Zig, with manual memory management and error handling.


const std = @import("std");

var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);

const allocator = arena.allocator();

pub fn LinkedList(comptime Value: type) type {
    return struct {
        const This = @This();

        const Node = struct {
            value: Value,
            next: ?*Node,
        };

        head: ?*Node,
        tail: ?*Node,

        pub fn init() This {
            return LinkedList(Value) {
                .head = null,
                .tail = null,
            };
        }

        pub fn add(this: *This, value: Value) !void {
            var newNode = try allocator.create(Node);

            newNode.* = .{ .value = value, .next = null };

            if (this.tail) |tail| {
                tail.next = newNode;
                this.tail = newNode;
            } else if (this.head) |head| {
                head.next = newNode;
                this.tail = newNode;
            } else {
                this.head = newNode;
            }
        }
    };
}

define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.


Library: raylib
const std = @import("std");
const c = @cImport({
    @cInclude("raylib.h");
});

pub fn main() !void {
    c.SetConfigFlags(c.FLAG_WINDOW_RESIZABLE | c.FLAG_VSYNC_HINT);
    c.InitWindow(600, 480, "cuboid");
    defer c.CloseWindow();

    const camera = c.Camera3D{
        .position = .{ .x = 4.5, .y = 4.5, .z = 4.5 },
        .target = .{ .x = 0, .y = 0, .z = 0 },
        .up = .{ .x = 0, .y = 1, .z = 0 },
        .fovy = 45.0,
        .projection = c.CAMERA_PERSPECTIVE,
    };

    c.SetTargetFPS(60);

    while (!c.WindowShouldClose()) {
        c.BeginDrawing();
        defer c.EndDrawing();

        c.ClearBackground(c.BLACK);

        {
            c.BeginMode3D(camera);
            defer c.EndMode3D();

            c.DrawCubeWires(.{ .x = 0, .y = 0, .z = 0 }, 2, 3, 4, c.LIME);
        }
    }
}

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


// Warning: modifies the buffer in-place (returns pointer to in)
fn rot13(in: [] u8) []u8 {
    for (in) |*c| {
        var d : u8 = c.*;
        var x : u8 = d;
        x = if (@subWithOverflow(u8, d | 32, 97, &x) ) x else x;
        if (x < 26) {
            x = (x + 13) % 26 + 65 + (d & 32);
            c.* = x;
        }
    }
    return in;
}

const msg: [:0] const u8 =
    \\Lbh xabj vg vf tbvat gb or n onq qnl
    \\ jura gur yrggref va lbhe nycunorg fbhc
    \\ fcryy Q-V-F-N-F-G-R-E.
;

// need to copy the const string to a buffer
// before we can modify it in-place
//https://zig.news/kristoff/what-s-a-string-literal-in-zig-31e9

var buf: [500]u8 = undefined;
fn assignStr(out: []u8, str: [:0]const u8) void {
    for (str) |c, i| {
        out[i] = c;
    }
    out[str.len] = 0;
}

const print = @import("std").debug.print;

pub fn main() void {
    assignStr(&buf, msg);
    print("rot13={s}\n",.{rot13(&buf)});
}

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


const std = @import("std");

pub fn main() !void {
    const stdout_wr = std.io.getStdOut().writer();
    var i: u8 = 1;
    while (i < 5) : (i += 1) {
        var j: u8 = 1;
        while (j <= i) : (j += 1)
            try stdout_wr.writeAll("*");
        try stdout_wr.writeAll("\n");
    }
}

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


const std = @import("std");

var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);

const allocator = arena.allocator();

pub fn LinkedList(comptime Value: type) type {
    return struct {
        const This = @This();

        const Node = struct {
            value: Value,
            next: ?*Node,
        };

        head: ?*Node,
        tail: ?*Node,

        pub fn init() This {
            return LinkedList(Value) {
                .head = null,
                .tail = null,
            };
        }

        pub fn add(this: *This, value: Value) !void {
            var newNode = try allocator.create(Node);

            newNode.* = .{ .value = value, .next = null };

            if (this.tail) |tail| {
                tail.next = newNode;
                this.tail = newNode;
            } else if (this.head) |head| {
                head.next = newNode;
                this.tail = newNode;
            } else {
                this.head = newNode;
            }
        }
    };
}

var l1 = LinkedList(i32).init();

try list.add(1);

Defines a method to insert an element into a singly-linked list after a given element. The method is then used to insert an element 'C' into a list comprised of elements 'A' and 'B', specifically after element 'A'.


const stdout = @import("std").io.getStdOut().outStream();

pub fn factorial(comptime Num: type, n: i8) ?Num {
    return if (@typeInfo(Num) != .Int)
        @compileError("factorial called with num-integral type: " ++ @typeName(Num))
    else if (n < 0)
        null
    else calc: {
        var i: i8 = 1;
        var fac: Num = 1;
        while (i <= n) : (i += 1) {
            if (@mulWithOverflow(Num, fac, i, &fac))
                break :calc null;
        } else break :calc fac;
    };
}

pub fn main() !void {
    try stdout.print("-1! = {}\n", .{factorial(i32, -1)});
    try stdout.print("0! = {}\n", .{factorial(i32, 0)});
    try stdout.print("5! = {}\n", .{factorial(i32, 5)});
    try stdout.print("33!(64 bit) = {}\n", .{factorial(i64, 33)}); // not vailid i64 factorial
    try stdout.print("33! = {}\n", .{factorial(i128, 33)}); // biggest facorial possible
    try stdout.print("34! = {}\n", .{factorial(i128, 34)}); // will overflow
}

The code implements a function to calculate the factorial of a given positive integer number. The factorial is calculated either iteratively or recursively. The function supports all integer data types, checks for overflow and negative numbers, and returns null in case of a domain error. It also relates to the task of generating Primorial numbers.


const std = @import("std");
const Vector = std.meta.Vector;

pub fn main() !void {
    const a: Vector(3, i32) = [_]i32{1, 3, -5};
    const b: Vector(3, i32) = [_]i32{4, -2, -1};
    var dot: i32 = @reduce(.Add, a*b);

    try std.io.getStdOut().writer().print("{d}\n", .{dot});
}

Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].


Library: raylib
const std = @import("std");
const c = @cImport({
    @cInclude("raylib.h");
});

pub fn main() !void {
    c.SetConfigFlags(c.FLAG_WINDOW_RESIZABLE | c.FLAG_VSYNC_HINT);
    c.InitWindow(600, 480, "Draw a Sphere");
    defer c.CloseWindow();

    const camera = c.Camera3D{
        .position = .{ .x = 4.5, .y = 4.5, .z = 4.5 },
        .target = .{ .x = 0, .y = 0, .z = 0 },
        .up = .{ .x = 0, .y = 1, .z = 0 },
        .fovy = 45.0,
        .projection = c.CAMERA_PERSPECTIVE,
    };

    c.SetTargetFPS(60);

    while (!c.WindowShouldClose()) {
        c.BeginDrawing();
        defer c.EndDrawing();

        c.ClearBackground(c.BLACK);

        {
            c.BeginMode3D(camera);
            defer c.EndMode3D();

            c.DrawSphereWires(.{ .x = 0, .y = 0, .z = 0 }, 2, 20, 20, c.LIME);
        }
    }
}

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


const std = @import("std");

pub fn main() !void {
    const cnt_lower = 26;
    var lower: [cnt_lower]u8 = undefined;
    comptime var i = 0;
    inline while (i < cnt_lower) : (i += 1)
        lower[i] = i + 'a';

    const stdout_wr = std.io.getStdOut().writer();
    for (lower) |l|
        try stdout_wr.print("{c} ", .{l});
    try stdout_wr.writeByte('\n');
}

generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.


const std = @import("std");
const math = std.math; // Save some typing, reduce clutter. Otherwise math.sin() would be std.math.sin() etc.

pub fn main() !void {
    // Coordinates are found here:
    //     http://www.airport-data.com/airport/BNA/
    //     http://www.airport-data.com/airport/LAX/

    const bna = LatLong{
        .lat = .{ .d = 36, .m = 7, .s = 28.10 },
        .long = .{ .d = 86, .m = 40, .s = 41.50 },
    };

    const lax = LatLong{
        .lat = .{ .d = 33, .m = 56, .s = 32.98 },
        .long = .{ .d = 118, .m = 24, .s = 29.05 },
    };

    const distance = calcGreatCircleDistance(bna, lax);

    std.debug.print("

implement the Haversine formula to calculate the great-circle distance between Nashville International Airport (BNA) and Los Angeles International Airport (LAX) using their respective longitudes and latitudes. The earth's radius is approximated as either 6371.0 km or 6372.8 km, resulting in slightly different distances. The code also includes the use of Zig struct type for initialization and method calling.


const std = @import("std");

pub fn print(from: u32, to: u32) void {
    std.log.info("Moving disk from rod {} to rod {}", .{ from, to });
}

pub fn move(n: u32, from: u32, via: u32, to: u32) void {
    if (n > 1) {
        move(n - 1, from, to, via);
        print(from, to);
        move(n - 1, via, from, to);
    } else {
        print(from, to);
    }
}

pub fn main() !void {
    move(4, 1, 2, 3);
}

"Implement a recursive solution to solve the Towers of Hanoi problem."


const std = @import("std");

pub fn binomial(n: u32) ?[]const u64 {
    if (n >= rmax)
        return null
    else {
        const k = n * (n + 1) / 2;
        return pascal[k .. k + n + 1];
    }
}

pub fn nCk(n: u32, k: u32) ?u64 {
    if (n >= rmax)
        return null
    else if (k > n)
        return 0
    else {
        const j = n * (n + 1) / 2;
        return pascal[j + k];
    }
}

const rmax = 68;

const pascal = build: {
    @setEvalBranchQuota(100_000);
    var coefficients: [(rmax * (rmax + 1)) / 2]u64 = undefined;
    coefficients[0] = 1;
    var j: u32 = 0;
    var k: u32 = 1;
    var n: u32 = 1;
    while (n < rmax) : (n += 1) {
        var prev = coefficients[j .. j + n];
        var next = coefficients[k .. k + n + 1];
        next[0] = 1;
        var i: u32 = 1;
        while (i < n) : (i += 1)
            next[i] = prev[i] + prev[i - 1];
        next[i] = 1;
        j = k;
        k += n + 1;
    }
    break :build coefficients;
};

test "n choose k" {
    const expect = std.testing.expect;
    try expect(nCk(10, 5).? == 252);
    try expect(nCk(10, 11).? == 0);
    try expect(nCk(10, 10).? == 1);
    try expect(nCk(67, 33).? == 14226520737620288370);
    try expect(nCk(68, 34) == null);
}

The code calculates any binomial coefficient, with a specific focus on outputting the binomial coefficient of 5 choose 3, which is 10. It uses a specific formula for the calculation and is capable of handling tasks related to combinations, permutations, and their variations with and without replacement. The code has been optimized for a 64-bit machine by precomputing all possible values of nCk, allowing for table lookup at runtime. It also handles out-of-range values by returning null. The maximum representable value it can compute is 67 choose 33. The functionality can be tested through a unit test module.


const std = @import("std");

pub fn main() !void {
    var a: u8 = 0;
    // no do-while in syntax, trust the optimizer to do
    // correct Loop inversion https://en.wikipedia.org/wiki/Loop_inversion
    // If the variable `alive` is independent to other variables and not in
    // diverging control flow, then the optimization is possible in general.
    var alive = true;
    while (alive == true or a % 6 != 0) {
        alive = false;
        a += 1;
        try std.io.getStdOut().writer().print("{d}\n", .{a});
    }
}

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


const std = @import("std");

fn printResults(alloc: std.mem.Allocator, string: []const u8) !void {
    const cnt_codepts_utf8 = try std.unicode.utf8CountCodepoints(string);
    // There is no sane and portable extended ascii, so the best
    // we get is counting the bytes and assume regular ascii.
    const cnt_bytes_utf8 = string.len;
    const stdout_wr = std.io.getStdOut().writer();
    try stdout_wr.print("utf8  codepoints = {d}, bytes = {d}\n", .{ cnt_codepts_utf8, cnt_bytes_utf8 });

    const utf16str = try std.unicode.utf8ToUtf16LeWithNull(alloc, string);
    const cnt_codepts_utf16 = try std.unicode.utf16CountCodepoints(utf16str);
    const cnt_2bytes_utf16 = try std.unicode.calcUtf16LeLen(string);
    try stdout_wr.print("utf16 codepoints = {d}, bytes = {d}\n", .{ cnt_codepts_utf16, 2 * cnt_2bytes_utf16 });
}

pub fn main() !void {
    var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena_instance.deinit();
    const arena = arena_instance.allocator();
    const string1: []const u8 = "Hello, world!";
    try printResults(arena, string1);
    const string2: []const u8 = "møøse";
    try printResults(arena, string2);
    const string3: []const u8 = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢";
    try printResults(arena, string3);
    // \u{332} is underscore of previous character, which the browser may not
    // copy correctly
    const string4: []const u8 = "J\u{332}o\u{332}s\u{332}e\u{301}\u{332}";
    try printResults(arena, string4);
}

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


const std = @import("std");

pub fn main() !void {
    try std.io.getStdOut().writer().writeAll("Hello world!");
}

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


const std = @import("std");
const print = std.debug.print;

pub fn CusipCheckDigit(cusip: *const [9:0]u8) bool {
    var i: usize = 0;
    var sum: i32 = 0;
    while (i < 8) {
        const c = cusip[i];
        var v: i32 = undefined;
        if (c <= '9' and c >= '0') {
            v = c - 48;
        }
        else if (c <= 'Z' and c >= 'A') {
            v = c - 55;
        }
        else if (c == '*') {
            v = 36;
        }
        else if (c == '@') {
            v = 37;
        }
        else if (c == '#') {
            v = 38;
        }
        else {
            return false;
        }
        if (i % 2 == 1) {
            v *= 2;
        }
        sum = sum + @divFloor(v, 10) + @mod(v, 10);
        i += 1;
    }
    return (cusip[8] - 48 == @mod((10 - @mod(sum, 10)), 10));
}

pub fn main() void {
    const cusips = [_]*const [9:0]u8 {
        "037833100",
        "17275R102",
        "38259P508",
        "594918104",
        "68389X106",
        "68389X105"
    };
    for (cusips) |cusip| {
        print("{s} -> {}\n", .{cusip, CusipCheckDigit(cusip)});
    }
}

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.


const warn = @import("std").debug.warn;

pub fn main() void {
    const items = [_]i16{ 0, 1, 1, 2, 3, 5, 8 };

     for (items) |i| {
        warn("{}\n", .{i});
    }
}

Iterates through each element in a collection in order and prints it, using a "for each" loop or another loop if "for each" is not available in the language.


const std = @import("std");
pub fn main() void {
  const string = "Hello,How,Are,You,Today";
  var tokens = std.mem.split(u8, string, ",");
  std.debug.print("{s}", .{tokens.next().?});
  while (tokens.next()) |token| {
    std.debug.print(".{s}", .{token});
  }
}

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


pub fn gcd(u: anytype, v: anytype) @TypeOf(u) {
  if (@typeInfo(@TypeOf(u)) != .Int) {
    @compileError("non-integer type used on gcd: " ++ @typeName(@TypeOf(u)));
  }
  if (@typeInfo(@TypeOf(v)) != .Int) {
    @compileError("non-integer type used on gcd: " ++ @typeName(@TypeOf(v)));
  }
  return if (v != 0) gcd(v, @mod(u,v)) else u;
}

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.


const print = @import("std").debug.print;
pub fn main() void {
    var i: usize = 1;
    while (i <= 100) : (i += 1) {
        if (i % 3 == 0 and i % 5 == 0) {
            print("FizzBuzz\n", .{});
        } else if (i % 3 == 0) {
            print("Fizz\n", .{});
        } else if (i % 5 == 0) {
            print("Buzz\n", .{});
        } else {
            print("{}\n", .{i});
        }
    }
}

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


const print = @import("std").debug.print;
pub fn main() void {
  const numbers = [_]u8{ 1, 2, 3, 4, 5 };
  var sum: u8 = 0;
  var product: u8 = 1;
  for (numbers) |number| {
    product *= number;
    sum += number;
  }
  print("{} {}\n", .{ product, sum });
}

Calculate the sum and product of all integers in an array.


pub fn isLeapYear(year: anytype) bool {
  const inttype = @TypeOf(year);
  if (@typeInfo(inttype) != .Int) {
    @compileError("non-integer type used on leap year: " ++ @typeName(inttype));
  }
  return (if (@mod(year, @as(inttype, 100)) == 0)
    @mod(year, @as(inttype, 400)) == 0
  else
    @mod(year, @as(inttype, 4)) == 0);
}

"Determines if a specified year is a leap year in the Gregorian calendar."


Works with: Zig version 0.11.0dev
const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    try stdout.writeAll("Police  Sanitation  Fire\n");
    try stdout.writeAll("------  ----------  ----\n");

    var p: usize = 2;
    while (p <= 7) : (p += 2)
        for (1..7 + 1) |s|
            for (1..7 + 1) |f|
                if (p != s and s != f and f != p and p + f + s == 12) {
                    try stdout.print("  {d}         {d}         {d}\n", .{ p, s, f });
                };
}

generates all unique combinations of numbers between 1 and 7 (inclusive) for the police, sanitation, and fire departments in a city, such that the sum of the numbers is 12 and the police department number is even. The combinations are generated using a Zig struct iterator.


const std = @import("std");

const debug = std.debug;
const mem = std.mem;

test "copy a string" {
    const source = "A string.";

    // Variable `dest1` will have the same type as `source`, which is
    // `*const [9:0]u8`.
    const dest1 = source;

    // Variable `dest2`'s type is [9]u8.
    //
    // The difference between the two is that `dest1` string is null-terminated,
    // while `dest2` is not.
    var dest2: [source.len]u8 = undefined;
    mem.copy(u8, dest2[0..], source[0..]);

    debug.assert(mem.eql(u8, dest1[0..], "A string."));
    debug.assert(mem.eql(u8, dest2[0..], "A string."));
}

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


const std = @import("std");

const debug = std.debug;
const rand = std.rand;
const time = std.time;

test "pick random element" {
    var pcg = rand.Pcg.init(time.milliTimestamp());

    const chars = [_]u8{
        'A', 'B', 'C', 'D',
        'E', 'F', 'G', 'H',
        'I', 'J', 'K', 'L',
        'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X',
        'Y', 'Z', '?', '!',
        '<', '>', '(', ')',
    };

    var i: usize = 0;
    while (i < 32) : (i += 1) {
        if (i % 4 == 0) {
            debug.warn("\n  ", .{});
        }
        debug.warn("'{c}', ", .{chars[pcg.random.int(usize) % chars.len]});
    }

    debug.warn("\n", .{});
}

demonstrate how to select a random element from a list using the PCG algorithm.


Library: Raylib
Works with: Zig version 0.11.0dev Works with: Raylib version 4.6devconst math = @import("std").math;
const c = @cImport({
    @cInclude("raylib.h");
});

pub fn main() void {
    c.SetConfigFlags(c.FLAG_VSYNC_HINT);
    c.InitWindow(640, 320, "Pendulum");
    defer c.CloseWindow();

    // Simulation constants.
    const g = 9.81; // Gravity (should be positive).
    const length = 5.0; // Pendulum length.
    const theta0 = math.pi / 3.0; // Initial angle for which omega = 0.

    const e = g * length * (1 - @cos(theta0)); // Total energy = potential energy when starting.

    // Simulation variables.
    var theta: f32 = theta0; // Current angle.
    var omega: f32 = 0; // Angular velocity = derivative of theta.
    var accel: f32 = -g / length * @sin(theta0); // Angular acceleration = derivative of omega.

    c.SetTargetFPS(60);

    while (!c.WindowShouldClose()) // Detect window close button or ESC key
    {
        const half_width = @as(f32, @floatFromInt(c.GetScreenWidth())) / 2;
        const pivot = c.Vector2{ .x = half_width, .y = 0 };

        // Compute the position of the mass.
        const mass = c.Vector2{
            .x = 300 * @sin(theta) + pivot.x,
            .y = 300 * @cos(theta),
        };

        {
            c.BeginDrawing();
            defer c.EndDrawing();

            c.ClearBackground(c.RAYWHITE);

            c.DrawLineV(pivot, mass, c.GRAY);
            c.DrawCircleV(mass, 20, c.GRAY);
        }

        // Update theta and omega.
        const dt = c.GetFrameTime();
        theta += (omega + dt * accel / 2) * dt;
        omega += accel * dt;

        // If, due to computation errors, potential energy is greater than total energy,
        // reset theta to ±theta0 and omega to 0.
        if (length * g * (1 - @cos(theta)) >= e) {
            theta = math.sign(theta) * theta0;
            omega = 0;
        }
        accel = -g / length * @sin(theta);
    }
}

create and animate a simple physical model of a gravity pendulum.


const std = @import("std");

fn Run(comptime T: type) type {
    return struct {
        value: T,
        length: usize,
    };
}

fn encode(
    comptime T: type,
    input: []const T,
    allocator: std.mem.Allocator,
) ![]Run(T) {
    var runs = std.ArrayList(Run(T)).init(allocator);
    defer runs.deinit();

    var previous: ?T = null;
    var length: usize = 0;

    for (input) |current| {
        if (previous == current) {
            length += 1;
        } else if (previous) |value| {
            try runs.append(.{
                .value = value,
                .length = length,
            });
            previous = current;
            length = 1;
        } else {
            previous = current;
            length += 1;
        }
    }

    if (previous) |value| {
        try runs.append(.{
            .value = value,
            .length = length,
        });
    }

    return runs.toOwnedSlice();
}

test encode {
    const input =
        "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";

    const expected = [_]Run(u8){
        .{ .length = 12, .value = 'W' },
        .{ .length = 1, .value = 'B' },
        .{ .length = 12, .value = 'W' },
        .{ .length = 3, .value = 'B' },
        .{ .length = 24, .value = 'W' },
        .{ .length = 1, .value = 'B' },
        .{ .length = 14, .value = 'W' },
    };

    const allocator = std.testing.allocator;
    const actual = try encode(u8, input, allocator);
    defer allocator.free(actual);

    try std.testing.expectEqual(expected.len, actual.len);
    for (expected, actual) |e, a| {
        try std.testing.expectEqual(e.length, a.length);
        try std.testing.expectEqual(e.value, a.value);
    }
}

fn decode(
    comptime T: type,
    runs: []const Run(T),
    allocator: std.mem.Allocator,
) ![]T {
    var values = std.ArrayList(T).init(allocator);
    defer values.deinit();
    for (runs) |r|
        try values.appendNTimes(r.value, r.length);
    return values.toOwnedSlice();
}

test decode {
    const runs = [_]Run(u8){
        .{ .length = 12, .value = 'W' },
        .{ .length = 1, .value = 'B' },
        .{ .length = 12, .value = 'W' },
        .{ .length = 3, .value = 'B' },
        .{ .length = 24, .value = 'W' },
        .{ .length = 1, .value = 'B' },
        .{ .length = 14, .value = 'W' },
    };

    const allocator = std.testing.allocator;
    const decoded = try decode(u8, &runs, allocator);
    defer allocator.free(decoded);

    try std.testing.expectEqualStrings(
        "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",
        decoded,
    );
}

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer std.debug.assert(gpa.deinit() == .ok);

    const allocator = gpa.allocator();
    var input = std.ArrayList(u8).init(allocator);
    defer input.deinit();

    const stdout = std.io.getStdOut().writer();
    const stdin = std.io.getStdIn().reader();
    try stdout.print("Input: ", .{});
    try stdin.streamUntilDelimiter(input.writer(), '\n', null);

    const runs = try encode(u8, input.items, allocator);
    defer allocator.free(runs);

    try stdout.print("Encoded:\n", .{});
    for (runs) |r|
        try stdout.print("  {}\n", .{r});

    const decoded = try decode(u8, runs, allocator);
    defer allocator.free(decoded);

    try stdout.print("Decoded: {s}\n", .{decoded});
}

implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.


const std = @import("std");

const debug = std.debug;
const heap = std.heap;
const mem = std.mem;

test "string concatenation" {
    const hello = "Hello,";

    debug.warn("\n{}{}\n", .{ hello, " world!" });

    // Method 1: Array concatenation
    //
    // This only works if the values are known at compile-time.
    const hello_world_at_comptime = hello ++ " world!";

    debug.warn("{}\n", .{hello_world_at_comptime});

    // Method 2: std.mem.concat
    var buf: [128]u8 = undefined;
    const allocator = &heap.FixedBufferAllocator.init(&buf).allocator;

    const hello_world_concatenated = try mem.concat(allocator, u8, &[_][]const u8{ hello, " world!" });

    debug.warn("{}\n", .{hello_world_concatenated});

    // Method 3: std.mem.join
    const hello_world_joined = try mem.join(allocator, " ", &[_][]const u8{ hello, "world!" });

    debug.warn("{}\n", .{hello_world_joined});
}

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.


const std = @import("std");

const Node = struct {
    frequency: usize,
    kind: union(enum) {
        internal: struct {
            left: *Node,
            right: *Node,
        },
        leaf: u8,
    },

    fn initLeaf(frequency: usize, ch: u8) Node {
        return .{
            .frequency = frequency,
            .kind = .{ .leaf = ch },
        };
    }

    fn initInternal(
        allocator: std.mem.Allocator,
        left_child: Node,
        right_child: Node,
    ) !Node {
        const left = try allocator.create(Node);
        const right = try allocator.create(Node);
        left.* = left_child;
        right.* = right_child;
        return .{
            .frequency = left_child.frequency + right_child.frequency,
            .kind = .{ .internal = .{ .left = left, .right = right } },
        };
    }

    fn deinit(self: Node, allocator: std.mem.Allocator) void {
        switch (self.kind) {
            .internal => |inner| {
                inner.left.deinit(allocator);
                inner.right.deinit(allocator);
                allocator.destroy(inner.left);
                allocator.destroy(inner.right);
            },
            .leaf => {},
        }
    }

    fn compare(context: void, a: Node, b: Node) std.math.Order {
        _ = context;
        return std.math.order(a.frequency, b.frequency);
    }
};

pub fn main() !void {
    const text = "this is an example for huffman encoding";

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer std.debug.assert(gpa.deinit() == .ok);

    const allocator = gpa.allocator();
    var frequencies = std.AutoHashMap(u8, usize).init(allocator);
    defer frequencies.deinit();

    for (text) |ch| {
        const gop = try frequencies.getOrPut(ch);
        if (gop.found_existing) {
            gop.value_ptr.* += 1;
        } else {
            gop.value_ptr.* = 1;
        }
    }

    var prioritized_frequencies =
        std.PriorityQueue(Node, void, Node.compare).init(allocator, {});
    defer prioritized_frequencies.deinit();

    var freq_it = frequencies.iterator();
    while (freq_it.next()) |counted_char| {
        try prioritized_frequencies.add(Node.initLeaf(
            counted_char.value_ptr.*,
            counted_char.key_ptr.*,
        ));
    }

    while (prioritized_frequencies.len > 1) {
        try prioritized_frequencies.add(try Node.initInternal(
            allocator,
            prioritized_frequencies.remove(),
            prioritized_frequencies.remove(),
        ));
    }

    const root = prioritized_frequencies.items[0];
    defer root.deinit(allocator);

    var codes = std.AutoArrayHashMap(u8, []const u8).init(allocator);
    defer codes.deinit();

    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();

    try generateCodes(arena.allocator(), &root, &.{}, &codes);

    const stdout = std.io.getStdOut().writer();
    var code_it = codes.iterator();
    while (code_it.next()) |item| {
        try stdout.print("{c}: {s}\n", .{
            item.key_ptr.*,
            item.value_ptr.*,
        });
    }
}

fn generateCodes(
    arena: std.mem.Allocator,
    node: *const Node,
    prefix: []const u8,
    out_codes: *std.AutoArrayHashMap(u8, []const u8),
) !void {
    switch (node.kind) {
        .internal => |inner| {
            const left_prefix = try arena.alloc(u8, prefix.len + 1);
            std.mem.copy(u8, left_prefix, prefix);
            left_prefix[prefix.len] = '0';
            try generateCodes(arena, inner.left, left_prefix, out_codes);

            const right_prefix = try arena.alloc(u8, prefix.len + 1);
            std.mem.copy(u8, right_prefix, prefix);
            right_prefix[prefix.len] = '1';
            try generateCodes(arena, inner.right, right_prefix, out_codes);
        },
        .leaf => |ch| {
            try out_codes.put(ch, prefix);
        },
    }
}

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.


const std = @import("std");

pub fn main() !void {
    var i: u8 = 11;
    while (i > 0) {
        i -= 1;
        try std.io.getStdOut().writer().print("{d}\n", .{i});
    }
}

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


Works with: Zig version 0.11.0dev
const std = @import("std");
const Allocator = std.mem.Allocator;

/// Caller owns the returned slice memory.
fn vigenere(allocator: Allocator, text: []const u8, key: []const u8, encrypt: bool) Allocator.Error![]u8 {
    var dynamic_string = std.ArrayList(u8).init(allocator);
    var key_index: usize = 0;
    for (text) |letter| {
        const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter;
        if (std.ascii.isUpper(c)) {
            const k = key[key_index];
            const n = if (encrypt) ((c - 'A') + (k - 'A')) else 26 + c - k;
            try dynamic_string.append(n % 26 + 'A'); // A-Z
            key_index += 1;
            key_index %= key.len;
        }
    }
    return dynamic_string.toOwnedSlice();
}

pub fn main() anyerror!void {
    // allocator
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer {
        const ok = gpa.deinit();
        std.debug.assert(ok == .ok);
    }
    const allocator = gpa.allocator();
    //
    const stdout = std.io.getStdOut().writer();
    //
    const key = "VIGENERECIPHER";
    const text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";

    const encoded = try vigenere(allocator, text, key, true);
    defer allocator.free(encoded);
    try stdout.print("{s}\n", .{encoded});

    const decoded = try vigenere(allocator, encoded, key, false);
    defer allocator.free(decoded);
    try stdout.print("{s}\n", .{decoded});
}

Implement both encryption and decryption of a Vigenère cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.


const std = @import("std");

pub fn main() !void {
    const stdout_wr = std.io.getStdOut().writer();
    var i: u8 = 1;
    while (i < 10) : (i += 2)
        try stdout_wr.print("{d}\n", .{i});
}

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


pub fn ack(m: u64, n: u64) u64 {
    if (m == 0) return n + 1;
    if (n == 0) return ack(m - 1, 1);
    return ack(m - 1, ack(m, n - 1));
}

pub fn main() !void {
    const stdout = @import("std").io.getStdOut().writer();

    var m: u8 = 0;
    while (m <= 3) : (m += 1) {
        var n: u8 = 0;
        while (n <= 8) : (n += 1)
            try stdout.print("{d:>8}", .{ack(m, n)});
        try stdout.print("\n", .{});
    }
}

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.


const std = @import("std");
const stdout = std.io.getStdOut().outStream();

var board = [_]i8{-1} ** 8;

inline fn abs(x: var) @TypeOf(x) {
    return if (x < 0) -x else x;
}

fn safe(c: i32, r: i32) bool {
    var i: i32 = 0;
    return while (i < c) : (i += 1) {
        const q = board[@intCast(u3, i)];
        if (r == q or c == i + abs(q - r))
            break false;
    } else true;
}

pub fn main() !void {
    var i: i32 = 0;
    while (i >= 0) {
        var j = board[@intCast(u3, i)] + 1;
        while (j < 8) : (j += 1) {
            if (safe(i, j)) {
                board[@intCast(u3, i)] = j;
                i += 1;
                break;
            }
        } else {
            board[@intCast(u3, i)] = -1;
            i -= 1;
        }
        if (i == 8) { // found a solution
            for (board) |q|
                try stdout.print("{} ", .{q + 1});
            try stdout.print("\n", .{});
            i -= 1; // create a failure to try new solutions.
        }
    }
}

all 92 solutions to the eight queens puzzle for a board of size NxN, as per the problem defined in OEIS: A000170.


const std = @import("std");
fn concat(allocator: std.mem.Allocator, a: []const u32, b: []const u32) ![]u32 {
  const result = try allocator.alloc(u32, a.len + b.len);
  std.mem.copy(u32, result, a);
  std.mem.copy(u32, result[a.len..], b);
  return result;
}

pub fn main() void {
  var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
  const gpa = general_purpose_allocator.allocator();
  var array1 = [_]u32{ 1, 2, 3, 4, 5 };
  var array2 = [_]u32{ 6, 7, 8, 9, 10, 11, 12 };
  const array3 = concat(gpa, &array1, &array2);
  std.debug.print("Array 1: {any}\nArray 2: {any}\nArray 3: {any}", .{ array1, array2, array3 });
}

demonstrate how to concatenate two arrays.


var intStack []int

intStack = append(intStack, 7)

popped, intStack = intStack[len(intStack)-1], intStack[:len(intStack)-1]

len(intStack) == 0

intStack[len(intStack)-1]

package main

import "fmt"

type stack []interface{}

func (k *stack) push(s interface{}) {
    *k = append(*k, s)
}

func (k *stack) pop() (s interface{}, ok bool) {
    if k.empty() {
        return
    }
    last := len(*k) - 1
    s = (*k)[last]
    *k = (*k)[:last]
    return s, true
}

func (k *stack) peek() (s interface{}, ok bool) {
    if k.empty() {
        return
    }
    last := len(*k) - 1
    s = (*k)[last]
    return s, true
}

func (k *stack) empty() bool {
    return len(*k) == 0
}

func main() {
    var s stack
    fmt.Println("new stack:", s)
    fmt.Println("empty?", s.empty())
    s.push(3)
    fmt.Println("push 3. stack:", s)
    fmt.Println("empty?", s.empty())
    s.push("four")
    fmt.Println(`push "four" stack:`, s)
    if top, ok := s.peek(); ok {
        fmt.Println("top value:", top)
    } else {
        fmt.Println("nothing on stack")
    }
    if popped, ok := s.pop(); ok {
        fmt.Println(popped, "popped.  stack:", s)
    } else {
        fmt.Println("nothing to pop")
    }
}

implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and allows access to the topmost element without modifying the stack. It also includes a feature to test if the stack is empty.


func fib(a int) int {
  if a < 2 {
    return a
  }
  return fib(a - 1) + fib(a - 2)
}
import (
	"math/big"
)

func fib(n uint64) *big.Int {
	if n < 2 {
		return big.NewInt(int64(n))
	}
	a, b := big.NewInt(0), big.NewInt(1)
	for n--; n > 0; n-- {
		a.Add(a, b)
		a, b = b, a
	}
	return b
}
func fibNumber() func() int {
	fib1, fib2 := 0, 1
	return func() int {
		fib1, fib2 = fib2, fib1 + fib2
		return fib1
	}
}

func fibSequence(n int) int {
	f := fibNumber()
	fib := 0
	for i := 0; i < n; i++ {
		fib = f()
	}
	return fib
}
func fib(c chan int) {
	a, b := 0, 1
	for {
		c <- a
		a, b = b, a+b
	}
}

func main() {
	c := make(chan int)
	go fib(c)
	for i := 0; i < 10; i++ {
		fmt.Println(<-c)
	}
}

generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.


package main

import (
    "fmt"
    "math/rand"
)

func main() {
    a := rand.Perm(20)
    fmt.Println(a)       // show array to filter
    fmt.Println(even(a)) // show result of non-destructive filter
    fmt.Println(a)       // show that original array is unchanged
    reduceToEven(&a)     // destructive filter
    fmt.Println(a)       // show that a is now changed
    // a is not only changed, it is changed in place.  length and capacity
    // show that it still has its original allocated capacity but has now
    // been reduced in length.
    fmt.Println("a len:", len(a), "cap:", cap(a))
}

func even(a []int) (r []int) {
    for _, e := range a {
        if e%2 == 0 {
            r = append(r, e)
        }
    }
    return
}

func reduceToEven(pa *[]int) {
    a := *pa
    var last int
    for _, e := range a {
        if e%2 == 0 {
            a[last] = e
            last++
        }
    }
    *pa = a[:last]
}

select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.


package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "ABCDEFGH"
    n, m := 2, 3
    // for reference
    fmt.Println("Index: ", "01234567")
    fmt.Println("String:", s)
    // starting from n characters in and of m length
    fmt.Printf("Start %d, length %d:    %s\n", n, m, s[n : n+m])
    // starting from n characters in, up to the end of the string
    fmt.Printf("Start %d, to end:      %s\n", n, s[n:])
    // whole string minus last character
    fmt.Printf("All but last:         %s\n", s[:len(s)-1])
    // starting from a known character within the string and of m length
    dx := strings.IndexByte(s, 'D')
    fmt.Printf("Start 'D', length %d:  %s\n", m, s[dx : dx+m])
    // starting from a known substring within the string and of m length
    sx := strings.Index(s, "DE")
    fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}

The code performs the following operations on a string:
1. Extracts a substring starting from the nth character with a length of m.
2. Extracts a substring starting from the nth character up to the end of the string.
3. Returns the whole string except the last character.
4. Extracts a substring starting from a known character within the string with a length of m.
5. Extracts a substring starting from a known substring within the string with a length of m.

The code supports any valid Unicode code point, referencing logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. It is not required to handle all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP. The code is designed to work with ASCII data and handles strings as UTF-8 in Go.


package main

import (
    "fmt"
    "unicode"
    "unicode/utf8"
)

// no encoding
func reverseBytes(s string) string {
    r := make([]byte, len(s))
    for i := 0; i < len(s); i++ {
        r[i] = s[len(s)-1-i]
    }
    return string(r)
}

// reverseCodePoints interprets its argument as UTF-8 and ignores bytes
// that do not form valid UTF-8.  return value is UTF-8.
func reverseCodePoints(s string) string {
    r := make([]rune, len(s))
    start := len(s)
    for _, c := range s {
        // quietly skip invalid UTF-8
        if c != utf8.RuneError {
            start--
            r[start] = c
        }
    }
    return string(r[start:])
}

// reversePreservingCombiningCharacters interprets its argument as UTF-8
// and ignores bytes that do not form valid UTF-8.  return value is UTF-8.
func reversePreservingCombiningCharacters(s string) string {
    if s == "" {
        return ""
    }
    p := []rune(s)
    r := make([]rune, len(p))
    start := len(r)
    for i := 0; i < len(p); {
        // quietly skip invalid UTF-8
        if p[i] == utf8.RuneError {
            i++
            continue
        }
        j := i + 1
        for j < len(p) && (unicode.Is(unicode.Mn, p[j]) ||
            unicode.Is(unicode.Me, p[j]) || unicode.Is(unicode.Mc, p[j])) {
            j++
        }
        for k := j - 1; k >= i; k-- {
            start--
            r[start] = p[k]
        }
        i = j
    }
    return (string(r[start:]))
}

func main() {
    test("asdf")
    test("as⃝df̅")
}

func test(s string) {
    fmt.Println("\noriginal:      ", []byte(s), s)
    r := reverseBytes(s)
    fmt.Println("reversed bytes:", []byte(r), r)
    fmt.Println("original code points:", []rune(s), s)
    r = reverseCodePoints(s)
    fmt.Println("reversed code points:", []rune(r), r)
    r = reversePreservingCombiningCharacters(s)
    fmt.Println("combining characters:", []rune(r), r)
}

The code takes a string input, reverses it while preserving the order of Unicode combining characters. It assumes UTF-8 encoding and leverages Go's support for UTF-8 and its Unicode package for recognizing combining characters. For instance, "asdf" is reversed to "fdsa" and "as⃝df̅" to "f̅ds⃝a".


package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

type playfairOption int

const (
    noQ playfairOption = iota
    iEqualsJ
)

type playfair struct {
    keyword string
    pfo     playfairOption
    table   [5][5]byte
}

func (p *playfair) init() {
    // Build table.
    var used [26]bool // all elements false
    if p.pfo == noQ {
        used[16] = true // Q used
    } else {
        used[9] = true // J used
    }
    alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
        c := alphabet[k]
        if c < 'A' || c > 'Z' {
            continue
        }
        d := int(c - 65)
        if !used[d] {
            p.table[i][j] = c
            used[d] = true
            j++
            if j == 5 {
                i++
                if i == 5 {
                    break // table has been filled
                }
                j = 0
            }
        }
    }
}

func (p *playfair) getCleanText(plainText string) string {
    // Ensure everything is upper case.
    plainText = strings.ToUpper(plainText)
    // Get rid of any non-letters and insert X between duplicate letters.
    var cleanText strings.Builder
    // Safe to assume null byte won't be present in plainText.
    prevByte := byte('\000')
    for i := 0; i < len(plainText); i++ {
        nextByte := plainText[i]
        // It appears that Q should be omitted altogether if NO_Q option is specified;
        // we assume so anyway.
        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
            continue
        }
        // If iEqualsJ option specified, replace J with I.
        if nextByte == 'J' && p.pfo == iEqualsJ {
            nextByte = 'I'
        }
        if nextByte != prevByte {
            cleanText.WriteByte(nextByte)
        } else {
            cleanText.WriteByte('X')
            cleanText.WriteByte(nextByte)
        }
        prevByte = nextByte
    }
    l := cleanText.Len()
    if l%2 == 1 {
        // Dangling letter at end so add another letter to complete digram.
        if cleanText.String()[l-1] != 'X' {
            cleanText.WriteByte('X')
        } else {
            cleanText.WriteByte('Z')
        }
    }
    return cleanText.String()
}

func (p *playfair) findByte(c byte) (int, int) {
    for i := 0; i < 5; i++ {
        for j := 0; j < 5; j++ {
            if p.table[i][j] == c {
                return i, j
            }
        }
    }
    return -1, -1
}

func (p *playfair) encode(plainText string) string {
    cleanText := p.getCleanText(plainText)
    var cipherText strings.Builder
    l := len(cleanText)
    for i := 0; i < l; i += 2 {
        row1, col1 := p.findByte(cleanText[i])
        row2, col2 := p.findByte(cleanText[i+1])
        switch {
        case row1 == row2:
            cipherText.WriteByte(p.table[row1][(col1+1)%5])
            cipherText.WriteByte(p.table[row2][(col2+1)%5])
        case col1 == col2:
            cipherText.WriteByte(p.table[(row1+1)%5][col1])
            cipherText.WriteByte(p.table[(row2+1)%5][col2])
        default:
            cipherText.WriteByte(p.table[row1][col2])
            cipherText.WriteByte(p.table[row2][col1])
        }
        if i < l-1 {
            cipherText.WriteByte(' ')
        }
    }
    return cipherText.String()
}

func (p *playfair) decode(cipherText string) string {
    var decodedText strings.Builder
    l := len(cipherText)
    // cipherText will include spaces so we need to skip them.
    for i := 0; i < l; i += 3 {
        row1, col1 := p.findByte(cipherText[i])
        row2, col2 := p.findByte(cipherText[i+1])
        switch {
        case row1 == row2:
            temp := 4
            if col1 > 0 {
                temp = col1 - 1
            }
            decodedText.WriteByte(p.table[row1][temp])
            temp = 4
            if col2 > 0 {
                temp = col2 - 1
            }
            decodedText.WriteByte(p.table[row2][temp])
        case col1 == col2:
            temp := 4
            if row1 > 0 {
                temp = row1 - 1
            }
            decodedText.WriteByte(p.table[temp][col1])
            temp = 4
            if row2 > 0 {
                temp = row2 - 1
            }
            decodedText.WriteByte(p.table[temp][col2])
        default:
            decodedText.WriteByte(p.table[row1][col2])
            decodedText.WriteByte(p.table[row2][col1])
        }
        if i < l-1 {
            decodedText.WriteByte(' ')
        }
    }
    return decodedText.String()
}

func (p *playfair) printTable() {
    fmt.Println("The table to be used is :\n")
    for i := 0; i < 5; i++ {
        for j := 0; j < 5; j++ {
            fmt.Printf("%c ", p.table[i][j])
        }
        fmt.Println()
    }
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Print("Enter Playfair keyword : ")
    scanner.Scan()
    keyword := scanner.Text()
    var ignoreQ string
    for ignoreQ != "y" && ignoreQ != "n" {
        fmt.Print("Ignore Q when building table  y/n : ")
        scanner.Scan()
        ignoreQ = strings.ToLower(scanner.Text())
    }
    pfo := noQ
    if ignoreQ == "n" {
        pfo = iEqualsJ
    }
    var table [5][5]byte
    pf := &playfair{keyword, pfo, table}
    pf.init()
    pf.printTable()
    fmt.Print("\nEnter plain text : ")
    scanner.Scan()
    plainText := scanner.Text()
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
        return
    }
    encodedText := pf.encode(plainText)
    fmt.Println("\nEncoded text is :", encodedText)
    decodedText := pf.decode(encodedText)
    fmt.Println("Deccoded text is :", decodedText)
}

Implement the Playfair cipher for both encryption and decryption. It allows the user to replace 'J' with 'I' or exclude 'Q' from the alphabet. The encrypted and decrypted messages are outputted in capitalized digraphs, separated by spaces.


package main

import (
	"container/heap"
	"fmt"
)

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue struct {
	items []Vertex
	m     map[Vertex]int // value to index
	pr    map[Vertex]int // value to priority
}

func (pq *PriorityQueue) Len() int           { return len(pq.items) }
func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }
func (pq *PriorityQueue) Swap(i, j int) {
	pq.items[i], pq.items[j] = pq.items[j], pq.items[i]
	pq.m[pq.items[i]] = i
	pq.m[pq.items[j]] = j
}
func (pq *PriorityQueue) Push(x interface{}) {
	n := len(pq.items)
	item := x.(Vertex)
	pq.m[item] = n
	pq.items = append(pq.items, item)
}
func (pq *PriorityQueue) Pop() interface{} {
	old := pq.items
	n := len(old)
	item := old[n-1]
	pq.m[item] = -1
	pq.items = old[0 : n-1]
	return item
}

// update modifies the priority of an item in the queue.
func (pq *PriorityQueue) update(item Vertex, priority int) {
	pq.pr[item] = priority
	heap.Fix(pq, pq.m[item])
}
func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {
	heap.Push(pq, item)
	pq.update(item, priority)
}

const (
	Infinity      = int(^uint(0) >> 1)
	Uninitialized = -1
)

func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {
	vs := g.Vertices()
	dist = make(map[Vertex]int, len(vs))
	prev = make(map[Vertex]Vertex, len(vs))
	sid := source
	dist[sid] = 0
	q := &PriorityQueue{
		items: make([]Vertex, 0, len(vs)),
		m:     make(map[Vertex]int, len(vs)),
		pr:    make(map[Vertex]int, len(vs)),
	}
	for _, v := range vs {
		if v != sid {
			dist[v] = Infinity
		}
		prev[v] = Uninitialized
		q.addWithPriority(v, dist[v])
	}
	for len(q.items) != 0 {
		u := heap.Pop(q).(Vertex)
		for _, v := range g.Neighbors(u) {
			alt := dist[u] + g.Weight(u, v)
			if alt < dist[v] {
				dist[v] = alt
				prev[v] = u
				q.update(v, alt)
			}
		}
	}
	return dist, prev
}

// A Graph is the interface implemented by graphs that
// this algorithm can run on.
type Graph interface {
	Vertices() []Vertex
	Neighbors(v Vertex) []Vertex
	Weight(u, v Vertex) int
}

// Nonnegative integer ID of vertex
type Vertex int

// sg is a graph of strings that satisfies the Graph interface.
type sg struct {
	ids   map[string]Vertex
	names map[Vertex]string
	edges map[Vertex]map[Vertex]int
}

func newsg(ids map[string]Vertex) sg {
	g := sg{ids: ids}
	g.names = make(map[Vertex]string, len(ids))
	for k, v := range ids {
		g.names[v] = k
	}
	g.edges = make(map[Vertex]map[Vertex]int)
	return g
}
func (g sg) edge(u, v string, w int) {
	if _, ok := g.edges[g.ids[u]]; !ok {
		g.edges[g.ids[u]] = make(map[Vertex]int)
	}
	g.edges[g.ids[u]][g.ids[v]] = w
}
func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {
	s = g.names[v]
	for prev[v] >= 0 {
		v = prev[v]
		s = g.names[v] + s
	}
	return s
}
func (g sg) Vertices() []Vertex {
	vs := make([]Vertex, 0, len(g.ids))
	for _, v := range g.ids {
		vs = append(vs, v)
	}
	return vs
}
func (g sg) Neighbors(u Vertex) []Vertex {
	vs := make([]Vertex, 0, len(g.edges[u]))
	for v := range g.edges[u] {
		vs = append(vs, v)
	}
	return vs
}
func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }

func main() {
	g := newsg(map[string]Vertex{
		"a": 1,
		"b": 2,
		"c": 3,
		"d": 4,
		"e": 5,
		"f": 6,
	})
	g.edge("a", "b", 7)
	g.edge("a", "c", 9)
	g.edge("a", "f", 14)
	g.edge("b", "c", 10)
	g.edge("b", "d", 15)
	g.edge("c", "d", 11)
	g.edge("c", "f", 2)
	g.edge("d", "e", 6)
	g.edge("e", "f", 9)

	dist, prev := Dijkstra(g, g.ids["a"])
	fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev))
	fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev))
}

The code implements Dijkstra's algorithm to find the shortest path from a given source node to all other nodes in a directed, weighted graph. The graph is represented by an adjacency matrix or list and a start node. The code takes this graph as input and outputs a set of edges that depict the shortest path to each reachable node from the source. It also includes functionality to interpret the output and display the shortest path from the source node to specific nodes. The vertices and edges of the graph can be identified using either numbers or names.


package avl

// AVL tree adapted from Julienne Walker's presentation at
// http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx.
// This port uses similar indentifier names.

// The Key interface must be supported by data stored in the AVL tree.
type Key interface {
    Less(Key) bool
    Eq(Key) bool
}

// Node is a node in an AVL tree.
type Node struct {
    Data    Key      // anything comparable with Less and Eq.
    Balance int      // balance factor
    Link    [2]*Node // children, indexed by "direction", 0 or 1.
}

// A little readability function for returning the opposite of a direction,
// where a direction is 0 or 1.  Go inlines this.
// Where JW writes !dir, this code has opp(dir).
func opp(dir int) int {
    return 1 - dir
}

// single rotation
func single(root *Node, dir int) *Node {
    save := root.Link[opp(dir)]
    root.Link[opp(dir)] = save.Link[dir]
    save.Link[dir] = root
    return save
}

// double rotation
func double(root *Node, dir int) *Node {
    save := root.Link[opp(dir)].Link[dir]

    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]
    save.Link[opp(dir)] = root.Link[opp(dir)]
    root.Link[opp(dir)] = save

    save = root.Link[opp(dir)]
    root.Link[opp(dir)] = save.Link[dir]
    save.Link[dir] = root
    return save
}

// adjust valance factors after double rotation
func adjustBalance(root *Node, dir, bal int) {
    n := root.Link[dir]
    nn := n.Link[opp(dir)]
    switch nn.Balance {
    case 0:
        root.Balance = 0
        n.Balance = 0
    case bal:
        root.Balance = -bal
        n.Balance = 0
    default:
        root.Balance = 0
        n.Balance = bal
    }
    nn.Balance = 0
}

func insertBalance(root *Node, dir int) *Node {
    n := root.Link[dir]
    bal := 2*dir - 1
    if n.Balance == bal {
        root.Balance = 0
        n.Balance = 0
        return single(root, opp(dir))
    }
    adjustBalance(root, dir, bal)
    return double(root, opp(dir))
}

func insertR(root *Node, data Key) (*Node, bool) {
    if root == nil {
        return &Node{Data: data}, false
    }
    dir := 0
    if root.Data.Less(data) {
        dir = 1
    }
    var done bool
    root.Link[dir], done = insertR(root.Link[dir], data)
    if done {
        return root, true
    }
    root.Balance += 2*dir - 1
    switch root.Balance {
    case 0:
        return root, true
    case 1, -1:
        return root, false
    }
    return insertBalance(root, dir), true
}

// Insert a node into the AVL tree.
// Data is inserted even if other data with the same key already exists.
func Insert(tree **Node, data Key) {
    *tree, _ = insertR(*tree, data)
}

func removeBalance(root *Node, dir int) (*Node, bool) {
    n := root.Link[opp(dir)]
    bal := 2*dir - 1
    switch n.Balance {
    case -bal:
        root.Balance = 0
        n.Balance = 0
        return single(root, dir), false
    case bal:
        adjustBalance(root, opp(dir), -bal)
        return double(root, dir), false
    }
    root.Balance = -bal
    n.Balance = bal
    return single(root, dir), true
}

func removeR(root *Node, data Key) (*Node, bool) {
    if root == nil {
        return nil, false
    }
    if root.Data.Eq(data) {
        switch {
        case root.Link[0] == nil:
            return root.Link[1], false
        case root.Link[1] == nil:
            return root.Link[0], false
        }
        heir := root.Link[0]
        for heir.Link[1] != nil {
            heir = heir.Link[1]
        }
        root.Data = heir.Data
        data = heir.Data
    }
    dir := 0
    if root.Data.Less(data) {
        dir = 1
    }
    var done bool
    root.Link[dir], done = removeR(root.Link[dir], data)
    if done {
        return root, true
    }
    root.Balance += 1 - 2*dir
    switch root.Balance {
    case 1, -1:
        return root, true
    case 0:
        return root, false
    }
    return removeBalance(root, dir)
}

// Remove a single item from an AVL tree.
// If key does not exist, function has no effect.
func Remove(tree **Node, data Key) {
    *tree, _ = removeR(*tree, data)
}

package main

import (
    "encoding/json"
    "fmt"
    "log"

    "avl"
)

type intKey int

// satisfy avl.Key
func (k intKey) Less(k2 avl.Key) bool { return k < k2.(intKey) }
func (k intKey) Eq(k2 avl.Key) bool   { return k == k2.(intKey) }

// use json for cheap tree visualization
func dump(tree *avl.Node) {
    b, err := json.MarshalIndent(tree, "", "   ")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b))
}

func main() {
    var tree *avl.Node
    fmt.Println("Empty tree:")
    dump(tree)

    fmt.Println("\nInsert test:")
    avl.Insert(&tree, intKey(3))
    avl.Insert(&tree, intKey(1))
    avl.Insert(&tree, intKey(4))
    avl.Insert(&tree, intKey(1))
    avl.Insert(&tree, intKey(5))
    dump(tree)

    fmt.Println("\nRemove test:")
    avl.Remove(&tree, intKey(3))
    avl.Remove(&tree, intKey(1))
    dump(tree)
}

implement an AVL tree, a self-balancing binary search tree where the heights of two child subtrees of any node differ by at most one. The code ensures rebalancing of the tree during insertions and deletions. It provides basic operations with O(log n) time complexity for lookup, insertion, and deletion. The code doesn't allow duplicate node keys. The AVL tree implemented is more efficient for lookup-intensive applications compared to red-black trees.


package main

import (
    "fmt"
    "math"
)

var (
    Two  = "Two circles."
    R0   = "R==0.0 does not describe circles."
    Co   = "Coincident points describe an infinite number of circles."
    CoR0 = "Coincident points with r==0.0 describe a degenerate circle."
    Diam = "Points form a diameter and describe only a single circle."
    Far  = "Points too far apart to form circles."
)

type point struct{ x, y float64 }

func circles(p1, p2 point, r float64) (c1, c2 point, Case string) {
    if p1 == p2 {
        if r == 0 {
            return p1, p1, CoR0
        }
        Case = Co
        return
    }
    if r == 0 {
        return p1, p2, R0
    }
    dx := p2.x - p1.x
    dy := p2.y - p1.y
    q := math.Hypot(dx, dy)
    if q > 2*r {
        Case = Far
        return
    }
    m := point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2}
    if q == 2*r {
        return m, m, Diam
    }
    d := math.Sqrt(r*r - q*q/4)
    ox := d * dx / q
    oy := d * dy / q
    return point{m.x - oy, m.y + ox}, point{m.x + oy, m.y - ox}, Two
}

var td = []struct {
    p1, p2 point
    r      float64
}{
    {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 2.0},
    {point{0.0000, 2.0000}, point{0.0000, 0.0000}, 1.0},
    {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 2.0},
    {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 0.5},
    {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 0.0},
}

func main() {
    for _, tc := range td {
        fmt.Println("p1: ", tc.p1)
        fmt.Println("p2: ", tc.p2)
        fmt.Println("r: ", tc.r)
        c1, c2, Case := circles(tc.p1, tc.p2, tc.r)
        fmt.Println("  ", Case)
        switch Case {
        case CoR0, Diam:
            fmt.Println("   Center: ", c1)
        case Two:
            fmt.Println("   Center 1: ", c1)
            fmt.Println("   Center 2: ", c2)
        }
        fmt.Println()
    }
}

"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned."


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


package main

import "fmt"
import "math/rand"
import "time"

func main() {
    rand.Seed(time.Now().UnixNano())
    for {
        a := rand.Intn(20)
        fmt.Println(a)
        if a == 10 {
            break
        }
        b := rand.Intn(20)
        fmt.Println(b)
    }
}

generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.


package main

import (
    "fmt"
    "math"
)

// limit search to small primes.  really this is higher than
// you'd want it, but it's fun to factor M67.
const qlimit = 2e8

func main() {
    mtest(31)
    mtest(67)
    mtest(929)
}

func mtest(m int32) {
    // the function finds odd prime factors by
    // searching no farther than sqrt(N), where N = 2^m-1.
    // the first odd prime is 3, 3^2 = 9, so M3 = 7 is still too small.
    // M4 = 15 is first number for which test is meaningful.
    if m < 4 {
        fmt.Printf("%d < 4.  M%d not tested.\n", m, m)
        return
    }
    flimit := math.Sqrt(math.Pow(2, float64(m)) - 1)
    var qlast int32
    if flimit < qlimit {
        qlast = int32(flimit)
    } else {
        qlast = qlimit
    }
    composite := make([]bool, qlast+1)
    sq := int32(math.Sqrt(float64(qlast)))
loop:
    for q := int32(3); ; {
        if q <= sq {
            for i := q * q; i <= qlast; i += q {
                composite[i] = true
            }
        }
        if q8 := q % 8; (q8 == 1 || q8 == 7) && modPow(2, m, q) == 1 {
            fmt.Printf("M%d has factor %d\n", m, q)
            return
        }
        for {
            q += 2
            if q > qlast {
                break loop
            }
            if !composite[q] {
                break
            }
        }
    }
    fmt.Printf("No factors of M%d found.\n", m)
}

// base b to power p, mod m
func modPow(b, p, m int32) int32 {
    pow := int64(1)
    b64 := int64(b)
    m64 := int64(m)
    bit := uint(30)
    for 1<<bit&p == 0 {
        bit--
    }
    for {
        pow *= pow
        if 1<<bit&p != 0 {
            pow *= b64
        }
        pow %= m64
        if bit == 0 {
            break
        }
        bit--
    }
    return int32(pow)
}

implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.


package main

import (
	"encoding/xml"
	"fmt"
	"log"
	"os"
)

type Inventory struct {
	XMLName  xml.Name `xml:"inventory"`
	Title    string   `xml:"title,attr"`
	Sections []struct {
		XMLName xml.Name `xml:"section"`
		Name    string   `xml:"name,attr"`
		Items   []struct {
			XMLName     xml.Name `xml:"item"`
			Name        string   `xml:"name"`
			UPC         string   `xml:"upc,attr"`
			Stock       int      `xml:"stock,attr"`
			Price       float64  `xml:"price"`
			Description string   `xml:"description"`
		} `xml:"item"`
	} `xml:"section"`
}

// To simplify main's error handling
func printXML(s string, v interface{}) {
	fmt.Println(s)
	b, err := xml.MarshalIndent(v, "", "\t")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(b))
	fmt.Println()
}

func main() {
	fmt.Println("Reading XML from standard input...")

	var inv Inventory
	dec := xml.NewDecoder(os.Stdin)
	if err := dec.Decode(&inv); err != nil {
		log.Fatal(err)
	}

	// At this point, inv is Go struct with all the fields filled
	// in from the XML data. Well-formed XML input that doesn't
	// match the specification of the fields in the Go struct are
	// discarded without error.

	// We can reformat the parts we parsed:
	//printXML("Got:", inv)

	// 1. Retrieve first item:
	item := inv.Sections[0].Items[0]
	fmt.Println("item variable:", item)
	printXML("As XML:", item)

	// 2. Action on each price:
	fmt.Println("Prices:")
	var totalValue float64
	for _, s := range inv.Sections {
		for _, i := range s.Items {
			fmt.Println(i.Price)
			totalValue += i.Price * float64(i.Stock)
		}
	}
	fmt.Println("Total inventory value:", totalValue)
	fmt.Println()

	// 3. Slice of all the names:
	var names []string
	for _, s := range inv.Sections {
		for _, i := range s.Items {
			names = append(names, i.Name)
		}
	}
	fmt.Printf("names: %q\n", names)
}

The code executes three XPath queries on a given XML document. It retrieves the first "item" element, prints out each "price" element, and generates an array of all the "name" elements. The XML document represents an inventory of an OmniCorp Store.


package main

import "fmt"

// Define set as a type to hold a set of complex numbers.  A type
// could be defined similarly to hold other types of elements.  A common
// variation is to make a map of interface{} to represent a set of
// mixed types.  Also here the map value is a bool.  By always storing
// true, the code is nicely readable.  A variation to use less memory
// is to make the map value an empty struct.  The relative advantages
// can be debated.
type set map[complex128]bool

func main() {
    // task: set creation
    s0 := make(set)             // create empty set
    s1 := set{3: true}          // create set with one element
    s2 := set{3: true, 1: true} // create set with two elements

    // option: another way to create a set
    s3 := newSet(3, 1, 4, 1, 5, 9)

    // option: output!
    fmt.Println("s0:", s0)
    fmt.Println("s1:", s1)
    fmt.Println("s2:", s2)
    fmt.Println("s3:", s3)

    // task: element predicate
    fmt.Printf("%v ∈ s0: %t\n", 3, s0.hasElement(3))
    fmt.Printf("%v ∈ s3: %t\n", 3, s3.hasElement(3))
    fmt.Printf("%v ∈ s3: %t\n", 2, s3.hasElement(2))

    // task: union
    b := set{4: true, 2: true}
    fmt.Printf("s3 ∪ %v: %v\n", b, union(s3, b))

    // task: intersection
    fmt.Printf("s3 ∩ %v: %v\n", b, intersection(s3, b))

    // task: difference
    fmt.Printf("s3 \\ %v: %v\n", b, difference(s3, b))

    // task: subset predicate
    fmt.Printf("%v ⊆ s3: %t\n", b, subset(b, s3))
    fmt.Printf("%v ⊆ s3: %t\n", s2, subset(s2, s3))
    fmt.Printf("%v ⊆ s3: %t\n", s0, subset(s0, s3))

    // task: equality
    s2Same := set{1: true, 3: true}
    fmt.Printf("%v = s2: %t\n", s2Same, equal(s2Same, s2))

    // option: proper subset
    fmt.Printf("%v ⊂ s2: %t\n", s2Same, properSubset(s2Same, s2))
    fmt.Printf("%v ⊂ s3: %t\n", s2Same, properSubset(s2Same, s3))

    // option: delete.  it's built in.
    delete(s3, 3)
    fmt.Println("s3, 3 deleted:", s3)
}

func newSet(ms ...complex128) set {
    s := make(set)
    for _, m := range ms {
        s[m] = true
    }
    return s
}

func (s set) String() string {
    if len(s) == 0 {
        return "∅"
    }
    r := "{"
    for e := range s {
        r = fmt.Sprintf("%s%v, ", r, e)
    }
    return r[:len(r)-2] + "}"
}

func (s set) hasElement(m complex128) bool {
    return s[m]
}

func union(a, b set) set {
    s := make(set)
    for e := range a {
        s[e] = true
    }
    for e := range b {
        s[e] = true
    }
    return s
}

func intersection(a, b set) set {
    s := make(set)
    for e := range a {
        if b[e] {
            s[e] = true
        }
    }
    return s
}

func difference(a, b set) set {
    s := make(set)
    for e := range a {
        if !b[e] {
            s[e] = true
        }
    }
    return s
}

func subset(a, b set) bool {
    for e := range a {
        if !b[e] {
            return false
        }
    }
    return true
}

func equal(a, b set) bool {
    return len(a) == len(b) && subset(a, b)
}

func properSubset(a, b set) bool {
    return len(a) < len(b) && subset(a, b)
}

The code demonstrates various set operations including set creation, checking if an element is in a set, union, intersection, difference, subset, and equality of two sets. It also optionally shows additional set operations and methods to modify a mutable set. The implementation could be done using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the efficiency of different implementations. It mentions the use of Go maps and big.Int type for specific use cases.


package main

import "fmt"
import "time"

func main() {
    for year := 2008; year <= 2121; year++ {
        if time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC).Weekday() ==
            time.Sunday {
            fmt.Printf("25 December %d is Sunday\n", year)
        }
    }
}

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


package main

import (
    "fmt"
    "math"

    "github.com/skelterjohn/go.matrix"
)

func sign(s float64) float64 {
    if s > 0 {
        return 1
    } else if s < 0 {
        return -1
    }
    return 0
}

func unitVector(n int) *matrix.DenseMatrix {
    vec := matrix.Zeros(n, 1)
    vec.Set(0, 0, 1)
    return vec
}

func householder(a *matrix.DenseMatrix) *matrix.DenseMatrix {
    m := a.Rows()
    s := sign(a.Get(0, 0))
    e := unitVector(m)
    u := matrix.Sum(a, matrix.Scaled(e, a.TwoNorm()*s))
    v := matrix.Scaled(u, 1/u.Get(0, 0))
    // (error checking skipped in this solution)
    prod, _ := v.Transpose().TimesDense(v)
    β := 2 / prod.Get(0, 0)

    prod, _ = v.TimesDense(v.Transpose())
    return matrix.Difference(matrix.Eye(m), matrix.Scaled(prod, β))
}

func qr(a *matrix.DenseMatrix) (q, r *matrix.DenseMatrix) {
    m := a.Rows()
    n := a.Cols()
    q = matrix.Eye(m)

    last := n - 1
    if m == n {
        last--
    }
    for i := 0; i <= last; i++ {
        // (copy is only for compatibility with an older version of gomatrix)
        b := a.GetMatrix(i, i, m-i, n-i).Copy()
        x := b.GetColVector(0)
        h := matrix.Eye(m)
        h.SetMatrix(i, i, householder(x))
        q, _ = q.TimesDense(h)
        a, _ = h.TimesDense(a)
    }
    return q, a
}

func main() {
    // task 1: show qr decomp of wp example
    a := matrix.MakeDenseMatrixStacked([][]float64{
        {12, -51, 4},
        {6, 167, -68},
        {-4, 24, -41}})
    q, r := qr(a)
    fmt.Println("q:\n", q)
    fmt.Println("r:\n", r)

    // task 2: use qr decomp for polynomial regression example
    x := matrix.MakeDenseMatrixStacked([][]float64{
        {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}})
    y := matrix.MakeDenseMatrixStacked([][]float64{
        {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}})
    fmt.Println("\npolyfit:\n", polyfit(x, y, 2))
}

func polyfit(x, y *matrix.DenseMatrix, n int) *matrix.DenseMatrix {
    m := x.Cols()
    a := matrix.Zeros(m, n+1)
    for i := 0; i < m; i++ {
        for j := 0; j <= n; j++ {
            a.Set(i, j, math.Pow(x.Get(0, i), float64(j)))
        }
    }
    return lsqr(a, y.Transpose())
}

func lsqr(a, b *matrix.DenseMatrix) *matrix.DenseMatrix {
    q, r := qr(a)
    n := r.Cols()
    prod, _ := q.Transpose().TimesDense(b)
    return solveUT(r.GetMatrix(0, 0, n, n), prod.GetMatrix(0, 0, n, 1))
}

func solveUT(r, b *matrix.DenseMatrix) *matrix.DenseMatrix {
    n := r.Cols()
    x := matrix.Zeros(n, 1)
    for k := n - 1; k >= 0; k-- {
        sum := 0.
        for j := k + 1; j < n; j++ {
            sum += r.Get(k, j) * x.Get(j, 0)
        }
        x.Set(k, 0, (b.Get(k, 0)-sum)/r.Get(k, k))
    }
    return x
}

q:
 {-0.857143,  0.394286,  0.331429,
 -0.428571, -0.902857, -0.034286,
  0.285714, -0.171429,  0.942857}
r:
 { -14,  -21,   14,
    0, -175,   70,
    0,    0,  -35}

polyfit:
 {1,
 2,
 3}

package main

import (
    "fmt"

    "github.com/gonum/matrix/mat64"
)

func main() {
    // task 1: show qr decomp of wp example
    a := mat64.NewDense(3, 3, []float64{
        12, -51, 4,
        6, 167, -68,
        -4, 24, -41,
    })
    var qr mat64.QR
    qr.Factorize(a)
    var q, r mat64.Dense
    q.QFromQR(&qr)
    r.RFromQR(&qr)
    fmt.Printf("q: %.3f\n\n", mat64.Formatted(&q, mat64.Prefix("   ")))
    fmt.Printf("r: %.3f\n\n", mat64.Formatted(&r, mat64.Prefix("   ")))

    // task 2: use qr decomp for polynomial regression example
    x := []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    y := []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}
    a = Vandermonde(x, 2)
    b := mat64.NewDense(11, 1, y)
    qr.Factorize(a)
    var f mat64.Dense
    f.SolveQR(&qr, false, b)
    fmt.Printf("polyfit: %.3f\n",
        mat64.Formatted(&f, mat64.Prefix("         ")))
}

func Vandermonde(a []float64, degree int) *mat64.Dense {
    x := mat64.NewDense(len(a), degree+1, nil)
    for i := range a {
        for j, p := 0, 1.; j <= degree; j, p = j+1, p*a[i] {
            x.Set(i, j, p)
        }
    }
    return x
}

The code demonstrates the QR decomposition of a given matrix using the method of Householder reflections. It first decomposes a given matrix into an orthogonal and an upper triangular matrix. Then, it applies Householder matrices on the matrix to zero all subdiagonal elements of the first column and transform it into an upper triangular matrix. The product of all the Householder matrices will yield the orthogonal matrix. The code also handles the case when the upper triangular matrix is not square by cutting off the zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.


package main

import "fmt"

func uniq(list []int) []int {
	unique_set := make(map[int]bool, len(list))
	for _, x := range list {
		unique_set[x] = true
	}
	result := make([]int, 0, len(unique_set))
	for x := range unique_set {
		result = append(result, x)
	}
	return result
}

func main() {
	fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) // prints: [3 4 1 2] (but in a semi-random order)
}

package main

import "fmt"

func uniq(list []int) []int {
	unique_set := make(map[int]int, len(list))
	i := 0
	for _, x := range list {
		if _, there := unique_set[x]; !there {
			unique_set[x] = i
			i++
		}
	}
	result := make([]int, len(unique_set))
	for x, i := range unique_set {
		result[i] = x
	}
	return result
}

func main() {
	fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) // prints: [1 2 3 4]
}

package main

import (
	"fmt"
	"math"
)

func uniq(list []float64) []float64 {
	unique_set := map[float64]int{}
	i := 0
	nan := false
	for _, x := range list {
		if _, exists := unique_set[x]; exists {
			continue
		}
		if math.IsNaN(x) {
			if nan {
				continue
			} else {
				nan = true
			}
		}
		unique_set[x] = i
		i++
	}
	result := make([]float64, len(unique_set))
	for x, i := range unique_set {
		result[i] = x
	}
	return result
}

func main() {
	fmt.Println(uniq([]float64{1, 2, math.NaN(), 2, math.NaN(), 4})) // Prints [1 2 NaN 4]
}

package main

import (
	"fmt"
	"math"
	"reflect"
)

func uniq(x interface{}) (interface{}, bool) {
	v := reflect.ValueOf(x)
	if !v.IsValid() {
		panic("uniq: invalid argument")
	}
	if k := v.Kind(); k != reflect.Array && k != reflect.Slice {
		panic("uniq: argument must be an array or a slice")
	}
	elemType := v.Type().Elem()
	intType := reflect.TypeOf(int(0))
	mapType := reflect.MapOf(elemType, intType)
	m := reflect.MakeMap(mapType)
	i := 0
	for j := 0; j < v.Len(); j++ {
		x := v.Index(j)
		if m.MapIndex(x).IsValid() {
			continue
		}
		m.SetMapIndex(x, reflect.ValueOf(i))
		if m.MapIndex(x).IsValid() {
			i++
		}
	}
	sliceType := reflect.SliceOf(elemType)
	result := reflect.MakeSlice(sliceType, i, i)
	hadNaN := false
	for _, key := range m.MapKeys() {
		ival := m.MapIndex(key)
		if !ival.IsValid() {
			hadNaN = true
		} else {
			result.Index(int(ival.Int())).Set(key)
		}
	}

	return result.Interface(), hadNaN
}

type MyType struct {
	name  string
	value float32
}

func main() {
	intArray := [...]int{5, 1, 2, 3, 2, 3, 4}
	intSlice := []int{5, 1, 2, 3, 2, 3, 4}
	stringSlice := []string{"five", "one", "two", "three", "two", "three", "four"}
	floats := []float64{1, 2, 2, 4,
		math.NaN(), 2, math.NaN(),
		math.Inf(1), math.Inf(1), math.Inf(-1), math.Inf(-1)}
	complexes := []complex128{1, 1i, 1 + 1i, 1 + 1i,
		complex(math.NaN(), 1), complex(1, math.NaN()),
		complex(math.Inf(+1), 1), complex(1, math.Inf(1)),
		complex(math.Inf(-1), 1), complex(1, math.Inf(1)),
	}
	structs := []MyType{
		{"foo", 42},
		{"foo", 2},
		{"foo", 42},
		{"bar", 42},
		{"bar", 2},
		{"fail", float32(math.NaN())},
	}

	fmt.Print("intArray: ", intArray, " → ")
	fmt.Println(uniq(intArray))
	fmt.Print("intSlice: ", intSlice, " → ")
	fmt.Println(uniq(intSlice))
	fmt.Print("stringSlice: ", stringSlice, " → ")
	fmt.Println(uniq(stringSlice))
	fmt.Print("floats: ", floats, " → ")
	fmt.Println(uniq(floats))
	fmt.Print("complexes: ", complexes, "\n → ")
	fmt.Println(uniq(complexes))
	fmt.Print("structs: ", structs, " → ")
	fmt.Println(uniq(structs))
	// Passing a non slice or array will compile put
	// then produce a run time panic:
	//a := 42
	//uniq(a)
	//uniq(nil)
}

implement three methods to remove duplicate elements from an array. The first method uses a hash table, the second method sorts the array and removes consecutive duplicates, and the third method iterates through the list and discards any element if it appears again. The code also includes a functionality to preserve the order of elements and handle special cases like NaNs. It uses Go's reflect package to work on almost any array or slice type, and handles map keys that contain a NaN.


package main

import "fmt"

func main() {
    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
    fmt.Println("unsorted:", list)

    quicksort(list)
    fmt.Println("sorted!  ", list)
}

func quicksort(a []int) {
    var pex func(int, int)
    pex = func(lower, upper int) {
        for {
            switch upper - lower {
            case -1, 0: // 0 or 1 item in segment.  nothing to do here!
                return
            case 1: // 2 items in segment
                // < operator respects strict weak order
                if a[upper] < a[lower] {
                    // a quick exchange and we're done.
                    a[upper], a[lower] = a[lower], a[upper]
                }
                return
            // Hoare suggests optimized sort-3 or sort-4 algorithms here,
            // but does not provide an algorithm.
            }

            // Hoare stresses picking a bound in a way to avoid worst case
            // behavior, but offers no suggestions other than picking a
            // random element.  A function call to get a random number is
            // relatively expensive, so the method used here is to simply
            // choose the middle element.  This at least avoids worst case
            // behavior for the obvious common case of an already sorted list.
            bx := (upper + lower) / 2
            b := a[bx]  // b = Hoare's "bound" (aka "pivot")
            lp := lower // lp = Hoare's "lower pointer"
            up := upper // up = Hoare's "upper pointer"
        outer:
            for {
                // use < operator to respect strict weak order
                for lp < upper && !(b < a[lp]) {
                    lp++
                }
                for {
                    if lp > up {
                        // "pointers crossed!"
                        break outer
                    }
                    // < operator for strict weak order
                    if a[up] < b {
                        break // inner
                    }
                    up--
                }
                // exchange
                a[lp], a[up] = a[up], a[lp]
                lp++
                up--
            }
            // segment boundary is between up and lp, but lp-up might be
            // 1 or 2, so just call segment boundary between lp-1 and lp.
            if bx < lp {
                // bound was in lower segment
                if bx < lp-1 {
                    // exchange bx with lp-1
                    a[bx], a[lp-1] = a[lp-1], b
                }
                up = lp - 2
            } else {
                // bound was in upper segment
                if bx > lp {
                    // exchange
                    a[bx], a[lp] = a[lp], b
                }
                up = lp - 1
                lp++
            }
            // "postpone the larger of the two segments" = recurse on
            // the smaller segment, then iterate on the remaining one.
            if up-lower < upper-lp {
                pex(lower, up)
                lower = lp
            } else {
                pex(lp, upper)
                upper = up
            }
        }
    }
    pex(0, len(a)-1)
}

implement the Quicksort algorithm to sort an array or list. The elements in the array must have a strict weak order. The algorithm works by choosing a pivot and dividing the rest of the elements into two partitions based on their relation to the pivot. It then recursively sorts the partitions and joins them together. The code also includes an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The choice of pivot and whether to allocate new arrays or sort in place is not specified. The code also compares Quicksort with other sorting algorithms like merge sort and heap sort.


package main

import "time"
import "fmt"

func main() {
    fmt.Println(time.Now().Format("2006-01-02"))
    fmt.Println(time.Now().Format("Monday, January 2, 2006"))
}

display the current date in the formats "2007-11-23" and "Friday, November 23, 2007", based on a specified date and time format. The task description and examples have been reviewed for clarity and accuracy.


package main

import (
    "fmt"
    "strconv"
    "strings"
)

// types needed to implement general purpose sets are element and set

// element is an interface, allowing different kinds of elements to be
// implemented and stored in sets.
type elem interface {
    // an element must be distinguishable from other elements to satisfy
    // the mathematical definition of a set.  a.eq(b) must give the same
    // result as b.eq(a).
    Eq(elem) bool
    // String result is used only for printable output.  Given a, b where
    // a.eq(b), it is not required that a.String() == b.String().
    fmt.Stringer
}

// integer type satisfying element interface
type Int int

func (i Int) Eq(e elem) bool {
    j, ok := e.(Int)
    return ok && i == j
}

func (i Int) String() string {
    return strconv.Itoa(int(i))
}

// a set is a slice of elem's.  methods are added to implement
// the element interface, to allow nesting.
type set []elem

// uniqueness of elements can be ensured by using add method
func (s *set) add(e elem) {
    if !s.has(e) {
        *s = append(*s, e)
    }
}

func (s *set) has(e elem) bool {
    for _, ex := range *s {
        if e.Eq(ex) {
            return true
        }
    }
    return false
}

func (s set) ok() bool {
    for i, e0 := range s {
        for _, e1 := range s[i+1:] {
            if e0.Eq(e1) {
                return false
            }
        }
    }
    return true
}

// elem.Eq
func (s set) Eq(e elem) bool {
    t, ok := e.(set)
    if !ok {
        return false
    }
    if len(s) != len(t) {
        return false
    }
    for _, se := range s {
        if !t.has(se) {
            return false
        }
    }
    return true
}

// elem.String
func (s set) String() string {
    if len(s) == 0 {
        return "∅"
    }
    var buf strings.Builder
    buf.WriteRune('{')
    for i, e := range s {
        if i > 0 {
            buf.WriteRune(',')
        }
        buf.WriteString(e.String())
    }
    buf.WriteRune('}')
    return buf.String()
}

// method required for task
func (s set) powerSet() set {
    r := set{set{}}
    for _, es := range s {
        var u set
        for _, er := range r {
            er := er.(set)
            u = append(u, append(er[:len(er):len(er)], es))
        }
        r = append(r, u...)
    }
    return r
}

func main() {
    var s set
    for _, i := range []Int{1, 2, 2, 3, 4, 4, 4} {
        s.add(i)
    }
    fmt.Println("      s:", s, "length:", len(s))
    ps := s.powerSet()
    fmt.Println("   𝑷(s):", ps, "length:", len(ps))

    fmt.Println("\n(extra credit)")
    var empty set
    fmt.Println("  empty:", empty, "len:", len(empty))
    ps = empty.powerSet()
    fmt.Println("   𝑷(∅):", ps, "len:", len(ps))
    ps = ps.powerSet()
    fmt.Println("𝑷(𝑷(∅)):", ps, "len:", len(ps))

    fmt.Println("\n(regression test for earlier bug)")
    s = set{Int(1), Int(2), Int(3), Int(4), Int(5)}
    fmt.Println("      s:", s, "length:", len(s), "ok:", s.ok())
    ps = s.powerSet()
    fmt.Println("   𝑷(s):", "length:", len(ps), "ok:", ps.ok())
    for _, e := range ps {
        if !e.(set).ok() {
            panic("invalid set in ps")
        }
    }
}

The code defines a function that takes a set S as input and returns the power set of S. It uses either a built-in set type or a defined set type with necessary operations. The function ensures the uniqueness of elements in the set. It also handles edge cases such as the power set of an empty set and a set containing only the empty set. The code does not use native set type in Go, but uses a slice as a set representation and an equality method to ensure uniqueness. The power set method computes the result directly without using the add method.


package main

import "fmt"

var (
    m0 = []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
    m1 = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
    m2 = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
    m3 = []string{"", "M", "MM", "MMM", "I̅V̅",
        "V̅", "V̅I̅", "V̅I̅I̅", "V̅I̅I̅I̅", "I̅X̅"}
    m4 = []string{"", "X̅", "X̅X̅", "X̅X̅X̅", "X̅L̅",
        "L̅", "L̅X̅", "L̅X̅X̅", "L̅X̅X̅X̅", "X̅C̅"}
    m5 = []string{"", "C̅", "C̅C̅", "C̅C̅C̅", "C̅D̅",
        "D̅", "D̅C̅", "D̅C̅C̅", "D̅C̅C̅C̅", "C̅M̅"}
    m6 = []string{"", "M̅", "M̅M̅", "M̅M̅M̅"}
)

func formatRoman(n int) (string, bool) {
    if n < 1 || n >= 4e6 {
        return "", false
    }
    // this is efficient in Go.  the seven operands are evaluated,
    // then a single allocation is made of the exact size needed for the result.
    return m6[n/1e6] + m5[n%1e6/1e5] + m4[n%1e5/1e4] + m3[n%1e4/1e3] +
        m2[n%1e3/1e2] + m1[n%100/10] + m0[n%10],
        true
}

func main() {
    // show three numbers mentioned in task descriptions
    for _, n := range []int{1990, 2008, 1666} {
        r, ok := formatRoman(n)
        if ok {
            fmt.Println(n, "==", r)
        } else {
            fmt.Println(n, "not representable")
        }
    }
}

<output> define a function that converts a positive integer into its equivalent Roman numeral representation. The function handles integers greater than 3999 by using the Unicode overbar as a factor of 1000.