Solve a Hidato puzzle: Difference between revisions
m
no edit summary
m (→{{header|Tailspin}}: update to stricter typing) |
mNo edit summary |
||
(4 intermediate revisions by 4 users not shown) | |||
Line 26:
* [[N-queens problem]]
* [[Solve a Holy Knight's tour]]
* [[
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
Line 35:
{{trans|Python}}
<
[Int] given
V start = (-1, -1)
Line 102:
solve(start[0], start[1], 1)
print()
print_board()</
{{out}}
Line 126:
=={{header|AutoHotkey}}==
<
if (R&&C) ; if neighbors (not first iteration)
{
Line 192:
}
return StrReplace(map, ">")
}</
Examples:<
Grid := [[ "Y" , 33 , 35 , "Y" , "Y"]
,[ "Y" , "Y" , 24 , 22 , "Y"]
Line 216:
;--------------------------------
MsgBox, 262144, ,% SolveHidato(Grid, Locked, Max, row, col)
return</
Outputs:<pre>32 33 35 36 37
31 34 24 22 38
Line 228:
=={{header|Bracmat}}==
<
( hidato
= Line solve lowest Ncells row column rpad
Line 340:
: ?board
& out$(hidato$!board)
);</
Output:
<pre>
Line 364:
=={{header|C}}==
Depth-first graph, with simple connectivity check to reject some impossible situations early. The checks slow down simpler puzzles significantly, but can make some deep recursions backtrack much earilier.
<
#include <stdlib.h>
#include <string.h>
Line 530:
return 0;
}</
{{out}}
<pre> Before:
Line 558:
If there are cells that require more characters, then a 2-dimensional array of ints must be used. Any number < 0 indicates a no-go.<br/>
The puzzle can be made circular (the end cell must connect to the start cell). In that case, no start cell needs to be given.
<
using System.Collections.Generic;
using static System.Console;
Line 685:
}
}</
{{out}}
<pre>
Line 699:
=={{header|C++}}==
<
#include <iostream>
#include <sstream>
Line 852:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
Output:
<pre>
Line 878:
{{Works with|PAKCS}}
Probably not efficient.
<
import Constraint (andC, anyC)
import Findall (unpack)
Line 931:
] = success
main = unpack hidato</
{{Output}}
<pre>Execution time: 1440 msec. / elapsed: 2270 msec.
Line 941:
This version retains some of the characteristics of the original C version. It uses global variables, it doesn't enforce immutability and purity. This style is faster to write for prototypes, short programs or less important code, but in larger programs you usually want more strictness to avoid some bugs and increase long-term maintainability.
{{trans|C}}
<
int[][] board;
Line 1,021:
solve(start[0], start[1], 1);
printBoard;
}</
{{out}}
<pre> . . . . . . . . . .
Line 1,051:
With this coding style the changes in the code become less bug-prone, but also more laborious. This version is also faster, its total runtime is about 0.02 seconds or less.
<
std.algorithm, std.exception, std.range, std.typetuple;
Line 1,265:
. . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ ."
);
}</
{{out}}
<pre>Problem:
Line 1,309:
=={{header|Elixir}}==
{{trans|Ruby}}
<
#
defmodule HLPsolver do
Line 1,386:
end)
end
end</
'''Test:'''
<
"""
Line 1,415:
. . 0 0 0 . 0 0 0 . 0 0 0 . 0 0 0 . 0 0 0 . 0 0 0 . 0
"""
|> HLPsolver.solve(adjacent)</
{{out}}
Line 1,462:
=={{header|Erlang}}==
To simplify the code I start a new process for searching each potential path through the grid. This means that the default maximum number of processes had to be raised ("erl +P 50000" works for me). The task takes about 1-2 seconds on a low level Mac mini. If faster times are needed, or even less performing hardware is used, some optimisation should be done.
<syntaxhighlight lang="erlang">
-module( solve_hidato_puzzle ).
Line 1,567:
store( {Key, Value}, Dict ) -> dict:store( Key, Value, Dict ).
</syntaxhighlight>
{{out}}
<pre>
Line 1,595:
=={{header|Go}}==
{{trans|Java}}
<
import (
Line 1,712:
solve(start[0], start[1], 1, 0)
printBoard()
}</
{{out}}
Line 1,741:
=={{header|Haskell}}==
<
{-# LANGUAGE Rank2Types #-}
Line 1,851:
, ". . . . 0 7 0 0"
, ". . . . . . 5 0"
]</
{{Out}}
<pre> 0 33 35 0 0
Line 1,875:
This is an Unicon-specific solution but could easily be adjusted to work in Icon.
<
record Pos(r,c)
Line 1,979:
QMouse(puzzle, goWest(), self, val)
QMouse(puzzle, goNW(), self, val)
end</
Sample run:
Line 2,013:
{{trans|D}}
{{works with|Java|7}}
<
import java.util.Collections;
import java.util.List;
Line 2,117:
}
}
}</
Output:
Line 2,146:
=={{header|Julia}}==
This solution utilizes a Hidato puzzle solver module which is also used for the Hopido and knight move tasks.
<
export hidatosolve, printboard, hidatoconfigure
Line 2,202:
end # module
</
hidat = """
Line 2,220:
hidatosolve(board, maxmoves, kingmoves, fixed, starts[1][1], starts[1][2], 1)
printboard(board)
</
__ 33 35 __ __
__ __ 24 22 __
Line 2,242:
=={{header|Kotlin}}==
{{trans|Java}}
<
lateinit var board: List<IntArray>
Line 2,316:
solve(start[0], start[1], 1, 0)
printBoard()
}</
{{out}}
Line 2,345:
=={{header|Mathprog}}==
<
Find a solution to a Hidato problem
Line 2,408:
;
end;</
Using the data in the model produces the following:
{{out}}
Line 2,654:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This implements a solver that works based on various techniques, i.e. not brute-forcing:
<
NakedN, HiddenN, ChainSearch, HidatoSolve, Cornering, ValidPuzzle, \
GapSearch, ReachDelete, GrowNeighbours]
Line 3,000:
VisualizeHidato[cells, candidates]
out = HidatoSolve[cells, candidates];
VisualizeHidato[cells, out]</
{{out}}
Outputs a graphical version of the solved hidato.
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
string.splitBySpaces = function
s = self.split
while s.indexOf("") != null
s.remove(s.indexOf(""))
end while
return s
end function
Hidato = {"board": [], "given": [], "start": [], "maxNum": 0}
Hidato.__emptyBoard = function(nRows, nCols)
self.board = []
emptyRow = []
for c in range(1,nCols + 2)
emptyRow.push(-1)
end for
for r in range(1,nRows + 2)
self.board.push(emptyRow[:])
end for
end function
Hidato.setup = function(s)
lines = s.split(char(13))
cols = lines[0].splitBySpaces.len
rows = lines.len
// create empty board with room
// for the wall at the edge
self.__emptyBoard(rows,cols)
board = self.board
// fill board with start puzzle
for r in range(0, rows - 1)
for c in range(0, cols - 1)
cell = (lines[r].splitBySpaces)[c]
if cell == "__" then
board[r+1][c+1] = 0 // unknown
else if cell == "." then
continue // -1 for blocked
else
num = cell.val
board[r+1][c+1] = num
self.given.push(num)
if num == 1 then
self.start = [r+1,c+1]
end if
if num > self.maxNum then self.maxNum = num
end if
end for
end for
self.given.sort
end function
Hidato.solve = function(n, pos = null, next = 0)
if n > self.given[-1] then return true
if pos == null then pos = self.start
r = pos[0]
c = pos[1]
board = self.board
if board[r][c] and board[r][c] != n then return false
if board[r][c] == 0 and self.given[next] == n then return false
back = 0
if board[r][c] == n then
next += 1
back = n
end if
board[r][c] = n
for i in range(-1, 1)
for j in range(-1,1)
if self.solve(n + 1, [r + i, c + j], next) then return true
end for
end for
board[r][c] = back
return false
end function
Hidato.print = function
board = self.board
maxLen = str(self.maxNum).len + 1
padding = " " * maxLen
for row in board[1:-1]
s = ""
for cell in row[1:-1]
c = padding + "__" * (cell == 0) + str(cell) * (cell > 0)
s += c[-maxLen:]
end for
print s
end for
end function
puzzle = "__ 33 35 __ __ . . ." + char(13)
puzzle += "__ __ 24 22 __ . . ." + char(13)
puzzle += "__ __ __ 21 __ __ . ." + char(13)
puzzle += "__ 26 __ 13 40 11 . ." + char(13)
puzzle += "27 __ __ __ 9 __ 1 ." + char(13)
puzzle += " . . __ __ 18 __ __ ." + char(13)
puzzle += " . . . . __ 7 __ __" + char(13)
puzzle += " . . . . . . 5 __"
Hidato.setup(puzzle)
print "The initial puzzle board:"
Hidato.print
print
Hidato.solve(1)
print "The puzzle solved:"
Hidato.print</syntaxhighlight>
{{out}}
<pre>
The initial puzzle board:
__ 33 35 __ __
__ __ 24 22 __
__ __ __ 21 __ __
__ 26 __ 13 40 11
27 __ __ __ 9 __ 1
__ __ 18 __ __
__ 7 __ __
5 __
The puzzle solved:
32 33 35 36 37
31 34 24 22 38
30 25 23 21 12 39
29 26 20 13 40 11
27 28 14 19 9 10 1
15 16 18 8 2
17 7 6 3
5 4</pre>
=={{header|Nim}}==
<
type Hidato = object
Line 3,083 ⟶ 3,214:
echo("Found:")
discard hidato.solve(hidato.start[0], hidato.start[1], 1)
hidato.print()</
{{out}}
<pre> . . . . . . . . . .
Line 3,109 ⟶ 3,240:
=={{header|Perl}}==
<
use List::Util 'max';
Line 3,192 ⟶ 3,323:
print "\033[2J";
try_fill(1, $known[1]);</
32 33 35 36 37
31 34 24 22 38
Line 3,203 ⟶ 3,334:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">board</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">warnsdorffs</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">knownx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">knowny</span>
Line 3,379 ⟶ 3,510:
__ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. .."""</span>
<span style="color: #000000;">Hidato</span><span style="color: #0000FF;">(</span><span style="color: #000000;">board6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">46</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">82</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre style="font-size: 8px">
Line 3,427 ⟶ 3,558:
=={{header|Picat}}==
<
main =>
Line 3,472 ⟶ 3,603:
R1 >= 1, R1 =< MaxR, C1 >= 1, C1 =< MaxC,
(R1,C1) != (R,C), M[R1,C1] !== 0].
</syntaxhighlight>
{{out}}
<pre>
Line 3,486 ⟶ 3,617:
=={{header|PicoLisp}}==
<
(de hidato (Lst)
Line 3,530 ⟶ 3,661:
(disp Grid 0
'((This)
(if (: val) (align 3 @) " ") ) ) ) )</
Test:
<
(quote
(T 33 35 T T)
Line 3,541 ⟶ 3,672:
(NIL NIL T T 18 T T)
(NIL NIL NIL NIL T 7 T T)
(NIL NIL NIL NIL NIL NIL 5 T) ) )</
Output:
<pre> +---+---+---+---+---+---+---+---+
Line 3,565 ⟶ 3,696:
Works with SWI-Prolog and library(clpfd) written by '''Markus Triska'''.<br>
Puzzle solved is from the Wilkipedia page : http://en.wikipedia.org/wiki/Hidato
<
hidato :-
Line 3,664 ⟶ 3,795:
my_write_1(X) :-
writef('%3r', [X]).</
{{out}}
<pre>?- hidato.
Line 3,678 ⟶ 3,809:
=={{header|Python}}==
<
given = []
start = None
Line 3,746 ⟶ 3,877:
solve(start[0], start[1], 1)
print
print_board()</
{{out}}
<pre> __ 33 35 __ __
Line 3,772 ⟶ 3,903:
immediately when tested with custom 2d vector library.
<syntaxhighlight lang="racket">
#lang racket
(require math/array)
Line 3,842 ⟶ 3,973:
;main function
(define (hidato board) (put-path board (hidato-path board)))
</syntaxhighlight>
{{out}}
<pre>
Line 3,863 ⟶ 3,994:
essentially the neighbourhood function.
<
(require "hidato-family-solver.rkt")
Line 3,882 ⟶ 4,013:
#( _ _ _ _ 0 7 0 0)
#( _ _ _ _ _ _ 5 0)))))
</syntaxhighlight>
{{out}}
Line 3,905 ⟶ 4,036:
* [[Solve the no connection puzzle#Raku|Solve the no connection puzzle]]
<syntaxhighlight lang="raku"
[ 0, -1], [ 0, 1],
[ 1, -1], [ 1, 0], [ 1, 1];
Line 4,002 ⟶ 4,133:
say "$tries tries";
}</
=={{header|REXX}}==
Line 4,011 ⟶ 4,142:
''Hidato'' and ''Numbrix'' are registered trademarks.
<
maxR=0; maxC=0; maxX=0; minR=9e9; minC=9e9; minX=9e9; cells=0; @.=
parse arg xxx; PZ='Hidato puzzle' /*get the cell definitions from the CL.*/
Line 4,065 ⟶ 4,196:
say _
end /*r*/
say; return</
'''output''' when using the following as input:
<br> <tt> 1 7 5 .\2 5 . 7 . .\3 3 . . 18 . .\4 1 27 . . . 9 . 1\5 1 . 26 . 13 40 11\6 1 . . . 21 . .\7 1 . . 24 22 .\8 1 . 33 35 . .</tt>
Line 4,094 ⟶ 4,225:
===Without Warnsdorff===
The following class provides functionality for solving a hidato problem:
<
#
class Hidato
Line 4,148 ⟶ 4,279:
(msg ? [msg] : []) + str + [""]
end
end</
'''Test:'''
<
board1 = <<EOS
. 4
Line 4,180 ⟶ 4,311:
t0 = Time.now
Hidato.new(board3).solve
puts " #{Time.now - t0} sec"</
{{out}}
Line 4,229 ⟶ 4,360:
===With Warnsdorff===
I modify method as follows to implement [[wp:Knight's_tour#Warnsdorff|Warnsdorff]] like
<
#
class HLPsolver
Line 4,296 ⟶ 4,427:
(msg ? [msg] : []) + str + [""]
end
end</
Which may be used as follows to solve Hidato Puzzles:
<
ADJACENT = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
Line 4,343 ⟶ 4,474:
t0 = Time.now
HLPsolver.new(board3).solve
puts " #{Time.now - t0} sec"</
Which produces:
Line 4,413 ⟶ 4,544:
=={{header|Rust}}==
<
use std::cmp::{max, min};
use std::fmt;
Line 4,608 ⟶ 4,739:
}
</syntaxhighlight>
{{out}}
<pre>
Line 4,631 ⟶ 4,762:
</pre>
=={{header|Seed7}}==
<
var set of integer: given is {};
Line 4,730 ⟶ 4,861:
printBoard;
end if;
end func;</
{{out}}
Line 4,760 ⟶ 4,891:
=={{header|Tailspin}}==
{{trans|Java}}
<
def input:
'__ 33 35 __ __ . . .
Line 4,770 ⟶ 4,901:
. . . . __ 7 __ __
. . . . . . 5 __';
templates hidato
composer setup
data givenInput <n´1:[<´{}´ ={}|{row: <row>, col: <col>}>*]> local
@: {row: 1, col: 1, givenInput:n´1:[]};
{ board: row´1:[ <line>+ ], given: $@.givenInput -> \[i](<~´{}´ ={}> { n: $i, $...} !\) }
rule line: col´1:[ <cell>+ ] (<'\n '>?) (..|@: {row: $@.row::raw + 1, col: 1};)
rule cell: <open|blocked|given> (<' '>?) (@.col: $@.col::raw + 1;)
rule open: <'__'> -> n´0
rule blocked: <' \.'> -> n´-1
rule given: (<' '>?) (def given: <n´INT>;)
($given -> ..|@.givenInput: $@.givenInput::length+1..$::raw -> {};)
($given -> @.givenInput($): { row: $@.row, col: $@.col };)
$given
end setup
templates solve
when <~{row: <1..$@hidato.board::length>, col: <1..$@hidato.board(row´1)::length>}> do !VOID
when <{ n: <=$@hidato.given(last).n>, row: <=$@hidato.given(last).row>, col: <=$@hidato.given(last).col> }> do $@hidato.board !
when <?($@hidato.board($.row; $.col) <~=n´0|=$.n
when <?($@hidato.board($.row; $.col) <=n´0>)?($@hidato.given($.next) <{n: <=$.n
otherwise
def guess: $;
def back: $@hidato.board($.row; $.col);
def next: $ -> \(when <{n: <=$back>}> do n´($.next::raw + 1)! otherwise $.next!\);
@hidato.board($.row; $.col): $.n
0..8 -> { next: $next, n: $guess.n::raw + 1, row: $guess.row::raw + $ ~/ 3 - 1, col: $guess.col::raw + $ mod 3 - 1 } -> #
@hidato.board($.row; $.col): $back;
end solve
@: $ -> setup;
{ next: n´1, $@.given(
end hidato
$input -> hidato -> '$... -> '$... -> ' $ -> \(when <=n´-1> do ' .' ! when <n´10..> do '$;' ! otherwise ' $;' !\);';
';
' ->!OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 4,821 ⟶ 4,952:
=={{header|Tcl}}==
<
global grid max filled
set max 1
Line 4,930 ⟶ 5,061:
puts ""
printgrid
}</
Demonstrating (dots are “outside” the grid, and zeroes are the cells to be filled in):
<
0 33 35 0 0 . . .
0 0 24 22 0 . . .
Line 4,941 ⟶ 5,072:
. . . . 0 7 0 0
. . . . . . 5 0
"</
{{out}}
<pre>
Line 4,972 ⟶ 5,103:
{{libheader|Wren-sort}}
{{libheader|Wren-fmt}}
<
import "./fmt" for Fmt
var board = []
Line 5,050 ⟶ 5,181:
System.print("\nFound:")
solve.call(start[0], start[1], 1, 0)
printBoard.call()</
{{out}}
Line 5,080 ⟶ 5,211:
=={{header|zkl}}==
{{trans|Python}}
<
#<<<
"0 33 35 0 0 X X X
Line 5,096 ⟶ 5,227:
solve(board,given, start.xplode(), 1);
println();
print_board(board);</
<
d:=D(-1," ", 0,"__");
foreach r in (board[1,-1]){
Line 5,133 ⟶ 5,264:
board[r][c]=back;
False
}</
{{out}}
<pre>
|