Department numbers: Difference between revisions
Content deleted Content added
Department numbers in Chipmunk Basic |
Recombinant (talk | contribs) Add Zig solution |
||
Line 4,823: | Line 4,823: | ||
6 5 1 |
6 5 1 |
||
</pre> |
</pre> |
||
=={{header|Zig}}== |
|||
{{works with|Zig|0.11.0dev}} |
|||
<syntaxhighlight lang="zig">const std = @import("std");</syntaxhighlight> |
|||
<syntaxhighlight lang="zig">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 }); |
|||
}; |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Police Sanitation Fire |
|||
------ ---------- ---- |
|||
2 3 7 |
|||
2 4 6 |
|||
2 6 4 |
|||
2 7 3 |
|||
4 1 7 |
|||
4 2 6 |
|||
4 3 5 |
|||
4 5 3 |
|||
4 6 2 |
|||
4 7 1 |
|||
6 1 5 |
|||
6 2 4 |
|||
6 4 2 |
|||
6 5 1</pre> |
|||
===Creating and using an iterator=== |
|||
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">pub fn main() !void { |
|||
const stdout = std.io.getStdOut().writer(); |
|||
_ = try stdout.writeAll("Police Sanitation Fire\n"); |
|||
_ = try stdout.writeAll("------ ---------- ----\n"); |
|||
var it = SolutionIterator{}; |
|||
while (it.next()) |solution| { |
|||
_ = try stdout.print(" {d} {d} {d}\n", .{ solution.police, solution.sanitation, solution.fire }); |
|||
} |
|||
}</syntaxhighlight> |
|||
<syntaxhighlight lang="zig">const SolutionIterator = struct { |
|||
// 5 bit unsigned (u5) allows addition up to 31 |
|||
p: u5 = 2, |
|||
s: u5 = 1, |
|||
f: u5 = 0, |
|||
/// 3 bit unsigned (u3) limits 0 <= department <= 7 |
|||
fn next(self: *SolutionIterator) ?struct { police: u3, sanitation: u3, fire: u3 } { |
|||
if (self.p > 7) return null; // already completed |
|||
while (true) { |
|||
self.f += 1; // fire |
|||
if (self.f > 7) { |
|||
self.f = 1; |
|||
self.s += 1; // sanitation |
|||
if (self.s > 7) { |
|||
self.s = 1; |
|||
self.p += 2; // police |
|||
if (self.p > 7) { |
|||
return null; // completed |
|||
} |
|||
} |
|||
} |
|||
if (self.p + self.f + self.s == 12) |
|||
return .{ |
|||
.police = @truncate(u3, self.p), |
|||
.sanitation = @truncate(u3, self.s), |
|||
.fire = @truncate(u3, self.f), |
|||
}; |
|||
} |
|||
} |
|||
};</syntaxhighlight> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |