Something went wrong. Try again.
A puzzle game of bent arrows sent off a board of dots, written in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Whether a board can be cleared, and an order that clears it.//!//! The order of exits never matters. An arrow leaving only empties dots, so//! an arrow that could leave before still can afterwards. Taking any arrow//! that can leave, until none can, therefore clears the board whenever//! anything does; if arrows remain, they block one another in a loop.
const std = @import("std");const Allocator = std.mem.Allocator;
const Board = @import("Board.zig");
/// An order of exits that clears what is left of `board`, which the caller/// frees, or null if it cannot be cleared. The board is not changed.pub fn solve(gpa: Allocator, board: *const Board) Allocator.Error!?[]Board.ArrowIndex { var work = try board.clone(gpa); defer work.deinit(gpa);
const order = try gpa.alloc(Board.ArrowIndex, work.remaining); errdefer gpa.free(order);
var done: usize = 0; while (work.remaining > 0) { const before = done; for (0..work.arrowCount()) |i| { const a: Board.ArrowIndex = @intCast(i); if (!work.isPresent(a)) continue; if (work.tap(a) == .exit) { order[done] = a; done += 1; } } if (done == before) { gpa.free(order); return null; } } return order;}
const testing = std.testing;
fn d(x: u16, y: u16) Board.Dot { return .{ .x = x, .y = y };}
test "a board is cleared in an order that works" { // 0 is blocked by 1, which is blocked by 2. var board: Board = try .init(testing.allocator, 5, 5, &.{ &.{ d(0, 2), d(1, 2) }, &.{ d(3, 3), d(3, 2), d(3, 1) }, &.{ d(4, 0), d(3, 0) }, }); defer board.deinit(testing.allocator);
const order = (try solve(testing.allocator, &board)).?; defer testing.allocator.free(order); try testing.expectEqual(3, order.len); for (order) |a| try testing.expectEqual(Board.Outcome.exit, board.tap(a));}
test "arrows blocking one another in a loop cannot be cleared" { var board: Board = try .init(testing.allocator, 3, 3, &.{ // Right, at 1's tail. &.{ d(0, 1), d(0, 0), d(1, 0) }, // Round the corner and up, at 0's head. &.{ d(2, 0), d(2, 1), d(2, 2), d(1, 2), d(1, 1) }, }); defer board.deinit(testing.allocator);
try testing.expectEqual(null, try solve(testing.allocator, &board)); // The board is left as it was. try testing.expectEqual(2, board.remaining);}