Solve a Hopido puzzle: Difference between revisions

Added AutoHotkey
m (Better D entry)
(Added AutoHotkey)
Line 22:
* [[Solve a Numbrix puzzle]]
* [[Knight's tour]]
 
 
=={{header|AutoHotkey}}==
<lang AutoHotkey>SolveHopido(Grid, Locked, Max, row, col, num:=1, R:="", C:=""){
if (R&&C) ; if neighbors (not first iteration)
{
Grid[R, C] := ">" num ; place num in current neighbor and mark it visited ">"
row:=R, col:=C ; move to current neighbor
}
 
num++ ; increment num
if (num=max) ; if reached end
return map(Grid) ; return solution
if locked[num] ; if current num is a locked value
{
row := StrSplit((StrSplit(locked[num], ",").1) , ":").1 ; find row of num
col := StrSplit((StrSplit(locked[num], ",").1) , ":").2 ; find col of num
if SolveHopido(Grid, Locked, Max, row, col, num) ; solve for current location and value
return map(Grid) ; if solved, return solution
}
else
{
for each, value in StrSplit(Neighbor(row,col), ",")
{
R := StrSplit(value, ":").1
C := StrSplit(value, ":").2
if (Grid[R,C] = "") ; a hole or out of bounds
|| InStr(Grid[R, C], ">") ; visited
|| Locked[num+1] && !(Locked[num+1]~= "\b" R ":" C "\b") ; not neighbor of locked[num+1]
|| Locked[num-1] && !(Locked[num-1]~= "\b" R ":" C "\b") ; not neighbor of locked[num-1]
|| Locked[num] ; locked value
|| Locked[Grid[R, C]] ; locked cell
continue
if SolveHopido(Grid, Locked, Max, row, col, num, R, C) ; solve for current location, neighbor and value
return map(Grid) ; if solved, return solution
}
}
num-- ; step back
for i, line in Grid
for j, element in line
if InStr(element, ">") && (StrReplace(element, ">") >= num)
Grid[i, j] := 0
}
;--------------------------------
;--------------------------------
;--------------------------------
Neighbor(row,col){
return Trim( ""
. "," row ":" col-3
. "," row ":" col+3
. "," row-3 ":" col
. "," row+3 ":" col
. "," row+2 ":" col+2
. "," row+2 ":" col-2
. "," row-2 ":" col+2
. "," row-2 ":" col-2
, ",")
}
;--------------------------------
map(Grid){
for i, row in Grid
{
for j, element in row
line .= (A_Index > 1 ? "`t" : "") element
map .= (map<>""?"`n":"") line
line := ""
}
return StrReplace(map, ">")
}</lang>
Examples:<lang AutoHotkey>;--------------------------------
Grid := [["",0 ,0 ,"",0 ,0 ,""]
,[0 ,0 ,0 ,0 ,0 ,0 ,0]
,[0 ,0 ,0 ,0 ,0 ,0 ,0]
,["",0 ,0 ,0 ,0 ,0 ,""]
,["","",0 ,0 ,0 ,"",""]
,["","","",0 ,"","",""]]
;--------------------------------
; find locked cells, find max value
Locked := []
max := 1
for i, line in Grid
for j, element in line
if (element >= 0)
max++ , list .= i ":" j "`n"
random, rnd, 1, %max%
loop, parse, list, `n, `r
if (A_Index = rnd)
{
row := StrSplit(A_LoopField, ":").1
col := StrSplit(A_LoopField, ":").2
Grid[row,col] := 1
Locked[1] := row ":" col "," Neighbor(row, col)
break
}
;--------------------------------
MsgBox, 262144, ,% SolveHopido(Grid, Locked, Max, row, col)
return</lang>
Outputs:<pre> 17 24 16 25
22 8 11 21 7 10 20
13 2 5 14 1 4 15
18 23 9 19 26
12 3 6
27</pre>
 
=={{header|C++}}==
299

edits