Solve a Hidato puzzle: Difference between revisions

Line 1,906:
 
=={{header|Julia}}==
This solution utilizes a module which is loosely based on the Python version, and is also used for the Hopido task.
{{trans|Python}}
<lang julia>functionmodule hidatoconfigure(str)Hidato
 
lines = map(x -> x * " ", split(str, "\n"))
export hidatosolve, printboard, hidatoconfigure
nrows, ncols = length(lines), length(lines[1])
 
board = fill(-1, (nrows, div(ncols, 3)))
board, fixed, start =function hidatoconfigure(hidatstr)
lines = map(x -> x * " ", split(str, "\n"))
nrows, ncols = length(lines), length(split(strip(lines[1]), r"\s+"))
board = fill(-1, (nrows, div(ncols, 3)))
presets = Vector{Int}()
starts = Vector{CartesianIndex{2}}()
startpos= [0, 0]
blanks = 0
for i in 1:nrows, j in 1:div(ncols, 3)
for (i, line) in if enumerate(ch = lines[i][3 *), (j-1, s) +in 2]enumerate(split(strip(line), == '_'r"\s+"))
c = s[1]
if c == '_' || (c == '0' && length(s) == 1)
board[i, j] = 0
elseif ch = blanks += '.'1
elseif c == '.'
continue
else # numeral, get 2 digits
board[i, j] = parse(Int, lines[i][3*(j-1)+1:3*(j-1)+2]s)
push!(presets, board[i, j])
if board[i, j] == 1
startpos =push!(starts, [CartesianIndex(i, j]))
end
end
end
board, blanks, sort!(presets), startposlength(starts) == 1 ? starts : findall(x -> x == 0, board)
end
 
function hidatosolve(board, movematrix, fixed, row, col, sought, next, maxmove)
if sought > fixed[end]maxmove
return true
elseif (board[row, col] != 0 && board[row, col] != sought) || (board[row, col] == 0 && fixed[next] == sought)
(length(fixed) > 1 && board[row, col] == 0 && fixed[next] == sought)
return false
end
Line 1,941 ⟶ 1,949:
end
board[row, col] = sought # try board with this cell set to next number
maxrow,for maxcolmove =in size(board)movematrix
for i in max(row - 1i, 1):min(j = row + move[1], maxrow), j in max(col -1, 1):min(col + 1, maxcol)move[2]
if !(i0 ==< row && ji =<= colsize(board)[1]) && hidatosolve(board,0 fixed, i,< j, sought<= +size(board)[2]) 1, next)&&
hidatosolve(board, movematrix, fixed, i, j, sought + 1, next, maxmove)
return true
end
Line 1,951 ⟶ 1,960:
end
 
function printboard(board, emptysquare= "__ ", blocked = " ")
d = Dict(-1 => " "blocked, 0 => "__ "emptysquare, -2 => "\n")
map(x -> d[x] = rpad(lpad(string(x), 2), 3), 1:maximum(board))
println(join([d[i] for i in hcat(board, fill(-2, size(board)[1]))'], ""))
end
 
end # module
 
using .Hidato
 
hidat = """
Line 1,967 ⟶ 1,980:
. . . . . . 5 __"""
 
const kingmoves = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
board, fixed, start = hidatoconfigure(hidat)
 
board, empties, fixed, starts = hidatoconfigure(hidat)
printboard(board)
hidatosolve(board, kingmoves, fixed, startstarts[1][1], startstarts[1][2], 1, 1, fixed[end])
printboard(board)
</lang>{{output}}<pre>
4,102

edits