Solve a Hidato puzzle: Difference between revisions

Content added Content deleted
Line 1,913: Line 1,913:
function hidatoconfigure(str)
function hidatoconfigure(str)
lines = split(str, "\n")
lines = split(str, "\n")
nrows, ncols = length(lines), length(split(strip(lines[1]), r"\s+"))
nrows, ncols = length(lines), length(split(lines[1], r"\s+"))
board = fill(-1, (nrows, ncols))
board = fill(-1, (nrows, ncols))
presets = Vector{Int}()
presets = Vector{Int}()
starts = Vector{CartesianIndex{2}}()
starts = Vector{CartesianIndex{2}}()
blanks = 0
maxmoves = 0
for (i, line) in enumerate(lines), (j, s) in enumerate(split(strip(line), r"\s+"))
for (i, line) in enumerate(lines), (j, s) in enumerate(split(strip(line), r"\s+"))
c = s[1]
c = s[1]
if c == '_' || (c == '0' && length(s) == 1)
if c == '_' || (c == '0' && length(s) == 1)
board[i, j] = 0
board[i, j] = 0
blanks += 1
maxmoves += 1
elseif c == '.'
elseif c == '.'
continue
continue
Line 1,931: Line 1,931:
push!(starts, CartesianIndex(i, j))
push!(starts, CartesianIndex(i, j))
end
end
maxmoves += 1
end
end
end
end
board, blanks, sort!(presets), length(starts) == 1 ? starts : findall(x -> x == 0, board)
board, maxmoves, sort!(presets), length(starts) == 1 ? starts : findall(x -> x == 0, board)
end
end


function hidatosolve(board, movematrix, fixed, row, col, sought, next, maxmove)
function hidatosolve(board, maxmoves, movematrix, fixed, row, col, sought, next)
if sought > maxmove
if sought > maxmoves
return true
return true
elseif (0 != board[row, col] != sought) || (board[row, col] == 0 && sought in fixed)
elseif (0 != board[row, col] != sought) || (board[row, col] == 0 && sought in fixed)
Line 1,951: Line 1,952:
i, j = row + move[1], col + move[2]
i, j = row + move[1], col + move[2]
if (0 < i <= size(board)[1]) && (0 < j <= size(board)[2]) &&
if (0 < i <= size(board)[1]) && (0 < j <= size(board)[2]) &&
hidatosolve(board, movematrix, fixed, i, j, sought + 1, next, maxmove)
hidatosolve(board, maxmoves, movematrix, fixed, i, j, sought + 1, next)
return true
return true
end
end
Line 1,965: Line 1,966:
end
end


end # module
end # modules
</lang><lang julia>using .Hidato

using .Hidato


hidat = """
hidat = """
Line 1,981: Line 1,981:
const kingmoves = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
const kingmoves = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]


board, empties, fixed, starts = hidatoconfigure(hidat)
board, maxmoves, fixed, starts = hidatoconfigure(hidat)
printboard(board)
printboard(board)
hidatosolve(board, kingmoves, fixed, starts[1][1], starts[1][2], 1, 1, fixed[end])
hidatosolve(board, maxmoves, kingmoves, fixed, starts[1][1], starts[1][2], 1, 1)
printboard(board)
printboard(board)
</lang>{{output}}<pre>
</lang>{{output}}<pre>