Jim and the Orders

  • + 0 comments

    I am starting a new journey, and doing coding challenges in ZigLang. IAW the rules of this platform, I will not post the solution in the editorial.

    const std = @import("std");
    const expectEqualSlices = std.testing.expectEqualSlices;
    
    const CompareOrder = struct {
        fn compare(_: void, lhs: [2]i32, rhs: [2]i32) bool {
            if (lhs[0] < rhs[0]) return true;
            if (lhs[0] > rhs[0]) return false;
            return lhs[1] < rhs[1];
        }
    };
    pub fn jimOrders(allocator: std.mem.Allocator, orders: []const [2]i32) ![]i32 {
        // Assign
        const count = orders.len;
    
        // Allocate
        var queue = try allocator.alloc([2]i32, count);
        var result = try allocator.alloc(i32, count);
    
        // Aftermath
        defer allocator.free(queue);
    
        return result;
    }
    test "all orders done at same time" {
        const allocator = std.testing.allocator;
        const orders = [_][2]i32{ .{ 1, 2 }, .{ 2, 3 }, .{ 3, 3 } };
        const output = [_]i32{ 1, 2, 3 };
        const result = try jimOrders(allocator, orders[0..]);
        defer allocator.free(result);
        try expectEqualSlices(i32, result, output[0..]);
    }