Department numbers: Difference between revisions

Content deleted Content added
→‎Zig using an iterator: Adjusted formatting
m →‎Zig using an iterator: introduce init() method for structure intialisation
Line 4,918: Line 4,918:
{{works with|Zig|0.11.0}}
{{works with|Zig|0.11.0}}
Using a Zig ''struct'' to create an iterator is a common pattern in Zig.
Using a Zig ''struct'' to create an iterator is a common pattern in Zig.
<syntaxhighlight lang="zig">const std = @import("std");</syntaxhighlight>
<syntaxhighlight lang="zig">
const std = @import("std");
<syntaxhighlight lang="zig">pub fn main() !void {

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


Line 4,925: Line 4,927:
try stdout.writeAll("------ ---------- ----\n");
try stdout.writeAll("------ ---------- ----\n");


var it = SolutionIterator{};
var it = SolutionIterator.init();
while (it.next()) |solution| {
while (it.next()) |solution| {
try stdout.print(
try stdout.print(
Line 4,947: Line 4,949:


const SolutionIterator = struct {
const SolutionIterator = struct {
// police initialized to zero as adding one is the first operation for next()
// police is initialized to one as adding one is the first operation in next()
// with the result .police == 2 (an even number) on the first pass.
u: DepartmentsUnion = .{ .departments = .{ .police = 0, .sanitation = 1, .fire = 1 } },
u: DepartmentsUnion = .{ .departments = .{ .police = 1, .sanitation = 1, .fire = 1 } },

/// init() returns an initialised structure.
/// Using init() is a common Zig pattern.
fn init() SolutionIterator {
return SolutionIterator{};
}


fn next(self: *SolutionIterator) ?Departments {
fn next(self: *SolutionIterator) ?Departments {
Line 4,971: Line 4,980:
if (self.u.departments.sanitation == self.u.departments.fire) continue;
if (self.u.departments.sanitation == self.u.departments.fire) continue;
if (self.u.departments.fire == self.u.departments.police) continue;
if (self.u.departments.fire == self.u.departments.police) continue;
// Must equal twelve (maximum sum 6 + 7 + 7 = 20 requires 5 bits)
// Must total twelve (maximum sum 7 + 7 + 7 = 21 requires 5 bits)
const p = @as(u5, self.u.departments.police);
const p = @as(u5, self.u.departments.police);
const s = @as(u5, self.u.departments.sanitation);
const s = @as(u5, self.u.departments.sanitation);