indicators.zig 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const std = @import("std");
  2. const inputModule = @import("input.zig");
  3. const MachineScheme = inputModule.MachineScheme;
  4. pub const Indicators = struct {
  5. lights: []bool,
  6. scheme: MachineScheme,
  7. pub fn isComplete(self: Indicators) bool {
  8. for (0..self.lights.len) |i| {
  9. if (self.lights[i] != self.scheme.indicatorDiagram[i]) {
  10. return false;
  11. }
  12. }
  13. return true;
  14. }
  15. pub fn applyButton(self: *Indicators, buttonIndex: usize) void {
  16. for (self.scheme.buttons[buttonIndex].indicatorsConnected) |toggleIndicator| {
  17. self.lights[toggleIndicator] = !self.lights[toggleIndicator];
  18. }
  19. }
  20. pub fn applyAllButtons(self: Indicators, allocator: std.mem.Allocator,
  21. nextIndicators: *IndicatorSet) !void {
  22. for (0..self.scheme.buttons.len) |buttonIndex| {
  23. var newIndicators = try createIndicators(allocator, self.scheme);
  24. @memcpy(newIndicators.lights, self.lights);
  25. newIndicators.applyButton(buttonIndex);
  26. try nextIndicators.put(newIndicators, true);
  27. }
  28. }
  29. };
  30. pub fn createIndicators(allocator: std.mem.Allocator, scheme: MachineScheme) !Indicators {
  31. const lights = try allocator.alloc(bool, scheme.indicatorDiagram.len);
  32. for (lights) |*light| {
  33. light.* = false;
  34. }
  35. const indicators: Indicators = .{
  36. .lights = lights,
  37. .scheme = scheme,
  38. };
  39. return indicators;
  40. }
  41. const IndicatorsContext = struct {
  42. pub fn hash(ctx: IndicatorsContext, key: Indicators) u64 {
  43. _ = ctx;
  44. var hasher = std.hash.Wyhash.init(0);
  45. for (key.lights) |*light| {
  46. hasher.update(std.mem.asBytes(light));
  47. }
  48. return hasher.final();
  49. }
  50. pub fn eql(ctx: IndicatorsContext, a: Indicators, b: Indicators) bool {
  51. _ = ctx;
  52. for (0..a.lights.len) |i| {
  53. if (a.lights[i] != b.lights[i]) {
  54. return false;
  55. }
  56. }
  57. return true;
  58. }
  59. };
  60. pub const IndicatorSet = std.HashMap(Indicators, bool, IndicatorsContext, std.hash_map.default_max_load_percentage);