Department numbers: Difference between revisions
Content deleted Content added
Recombinant (talk | contribs) →Zig using an iterator: Adjusted formatting |
Recombinant (talk | contribs) m →Zig using an iterator: introduce init() method for structure intialisation |
||
Line 4,918:
{{works with|Zig|0.11.0}}
Using a Zig ''struct'' to create an iterator is a common pattern in Zig.
<syntaxhighlight lang="zig"
const std = @import("std");
<syntaxhighlight lang="zig">pub fn main() !void {▼
const stdout = std.io.getStdOut().writer();
Line 4,925 ⟶ 4,927:
try stdout.writeAll("------ ---------- ----\n");
var it = SolutionIterator
while (it.next()) |solution| {
try stdout.print(
Line 4,947 ⟶ 4,949:
const SolutionIterator = struct {
// police is initialized to
// with the result .police == 2 (an even number) on the first pass.
u: DepartmentsUnion = .{ .departments = .{ .police =
/// init() returns an initialised structure.
/// Using init() is a common Zig pattern.
fn init() SolutionIterator {
return SolutionIterator{};
}
fn next(self: *SolutionIterator) ?Departments {
Line 4,971 ⟶ 4,980:
if (self.u.departments.sanitation == self.u.departments.fire) continue;
if (self.u.departments.fire == self.u.departments.police) continue;
// Must
const p = @as(u5, self.u.departments.police);
const s = @as(u5, self.u.departments.sanitation);
|