17

规则

河内塔是一个谜,如果你不是很熟悉它,这里是它的工作原理:

游戏场由 3 根杆和x个圆盘组成,下一个比上一个大。这些圆盘可以放在杆上,规则如下:

  • 一次只能移动一个磁盘,并且必须在另一个杆的顶部移动
  • 必须从杆的顶部取出磁盘
  • 磁盘可以移动到某个地方,只有当目标杆上最上面的磁盘大于要移动的磁盘时

最后 - 比赛场地这样开始的:

  • 一根带有x 个圆盘的棒,排序后最大的在底部,最小的在顶部
  • 一根空棒
  • 一根空棒

游戏的目标是将原始的“堆叠”磁盘移动到另一根杆上,即 - 将所有磁盘放在另一根杆上,因此(再次)最大的在底部,最小的在顶部

执行

您的目标是使用您选择的编程语言编写一个程序,该程序接受输入(如下所述)并输出解决位置所需的步骤。

与往常一样,尽量缩短它。

输入

示例输入:

4-3,7-6-5,2-1

输入是一个字符串,由 3 部分组成,用逗号分隔。这些零件是 3 根杆中每根杆上的磁盘列表。它们也是分开的,这次用连字符( - ),每个子部分都是一个数字,数字越大,磁盘越大。

所以 - 对于上述输入,这将是一个视觉表示:

       .               .               .
       |          =====|=====          |
    ===|===      ======|======        =|=
   ====|====    =======|=======      ==|==

     ROD 1           ROD 2           ROD 3

输出

正如您在上面的表示中看到的 - 输入的最左侧部分是一号杆,中间是二号杆,最后一个是三号杆。

您的程序的输出应如下所示:

12,23,31,12,23,13

一个数字列表,用逗号分隔,定义了应该取出磁盘的杆,以及应该放置磁盘的杆。只有 3 个杆,所以只有 6 种可能的组合(因为必须将磁盘移动到另一个杆,而不是同一个杆):

12
13
21
23
31
32

笔记

输入不必描述处于“原始”状态的字段 - 它可以是中间解决的。

您的程序不能产生空输出。如果输入处于原始状态,只需将磁盘放在不同的杆上。

输入可以有一个空棒,如下所示:

2-1,3,
,,1
4-3,,2-1

如果输入不是这种格式,您的程序可能会产生未定义的行为。因此,如果输入无效(例如较小的磁盘上的较大磁盘,丢失磁盘,无法解决),它可以。输入将始终有效

确保解决方案尽可能快(尽可能少转弯)-也就是说,不要浪费“12,21,12”的转弯......

测试

所以,我为你准备了这个小闪存,你可以用它来测试你的程序是否产生了一个好的解决方案,而无需写下它或任何东西。

这里是:Hanoi AlgoTest(等待它加载然后刷新——死链接:|)

要使用它,请将程序的输入粘贴到INPUT字段,并将程序产生的输出粘贴到PROCESS字段。它将以您也可以更改的速度运行模拟,并以视觉表示形式打印出底部的任何错误。

希望能帮助到你。

4

4 回答 4

4

这是 Scala 中的 10 首发,经过多次修改。不知道有什么问题,也没有其他的进一步减少招式的想法

作为 Scala 脚本运行。

这部分非常优雅(IMO),但其他部分是丑陋的黑客

最短的代码(但非最佳移动),跟踪磁盘的位置而不是棒上的磁盘列表(从 Perl 解决方案中无耻地窃取的想法)

 val r=args(0).split(",",-1);var d=Map{{for(q<-0 to 2 if""!=r(q);n<-r(q).split('-').map{_.toInt})yield(n,q+1)}:_*};val n=d.max._1;var m="";def s(f:Int,t:Int,n:Int):Unit=if(n!=0&&f!=t){s(f,6-f-t,n-1);d=d+(n->t);m=m+","+f+t;s(6-f-t,t,n-1)};for(c<- 2 to n)s(d(1),d(c),c-1);if(m=="")s(d(1),d(1)%3+1,n);println(m.tail.replaceAll("(.),?\\1",""))

谜题取自命令行。

338 字节。不太破旧,因为这是一种静态类型的语言,并且仍然相对易读(如果您将 ; 替换为换行符)

可读版本如下(有更优化的动作)

val rods = args(0).split(",", -1);
var diskLocation = Map{
  {
    for (rod <-0 to 2 if rods(rod).nonEmpty;
         n <-rods(rod).split('-').map{_.toInt})
      yield(n, rod + 1)
  }:_*
}

val nDisks = diskLocation.max._1

var moves = ""

def moveTower(start:Int, end:Int, n:Int):Unit = 
  if (n != 0) {
    val other = 6 - start - end
    moveTower(start, other, n - 1)
    moveDisk(n, end)
    moveTower(other, end, n - 1)
  }

def moveDisk(n:Int, end:Int) = {
  moves = moves + "," + diskLocation(n) + end
  diskLocation = diskLocation.updated(n, end);
}

for (c <- 2 to nDisks) {
  var firstLocation = diskLocation(1)
  var nextLocation = diskLocation(c)
  if (firstLocation != nextLocation) {
    if (c != nDisks) {
      val diskAfter = diskLocation(c + 1)
      if (diskAfter != firstLocation && diskAfter != nextLocation) {
        moveDisk(c, diskAfter)
        nextLocation = diskAfter
      }
    }
    moveTower(diskLocation(1), diskLocation(c), c - 1);
  }
}

if (moves == "")
  moveTower(diskLocation(1), diskLocation(1)%3 + 1, nDisks)

println(moves.tail.replaceAll("(.),?\\1",""))
于 2010-12-04T11:16:27.263 回答
4

Perl,209 (203) 字符

重写以跟踪每个磁盘的位置,而不是每个棒上包含的磁盘列表。

删除不必要的空格后306 291 263 244 236 213 209 个字符。

sub M{my($r,$s)=@_;if(--$m){M($r,$r^$s);$_.=",$r$s";M($r^$s,$s)}s/(.),?\1//;
$R[++$m]=$p}map@R[/\d+/g]=(++$i)x99,split/,/,<>;do{1until
($n=$R[1])-($p=$R[++$m]||$n-1|2);M$n,$p}while 1<grep@R~~$_,1..3;s/^,//;print

$R[j]: 磁盘 j 的位置

$n: 磁盘 #1 的位置

$m:要移动的磁盘数量

$p:将磁盘移动到的位置

&M(r,s): 将$m-1磁盘从 r 移动到 s。追加$_和设置@R

内部的替换sub M优化了输出,去除了多余的步骤。它可以被删除(12 个字符)并且输出仍然有效。

如果使用命令行开关调用 perl 解释器,则可以删除另外 12 个字符-apF,。使用命令行开关的额外 6 个字符,这使我们减少到净 203 个字符:

# invoke as   perl -apF, ...
sub M{my($r,$s)=@_;if(--$m){M($r,$r^$s);$_=$a.=",$r$s";M($r^$s,$s)}
s/(.),\1//;$R[++$m]=$p}map@R[/\d+/g]=(++$i)x99,@F;
do{1until($n=$R[1])-($p=$R[++$m]||$n-1|2);M$n,$p}while 1<grep@R~~$_,1..3;s/^,//
于 2010-12-06T22:19:53.587 回答
1

Perl 241 字符

当然不是最有效的方法,但它确实有效。

更新以抑制最后一个逗号。

map{map$g[$_]=$i|0,/\d/g;$i++}split$,=',',<>;shift@g;@G=(0)x@g;@u=(1)x10;while(!$G[@g]){$G="@G";$_="@g";$i=0;$j=$G[0]+$u[0];while($j>2||$j<0){$u[$i++]*=-1;$j=$u[$i]+$G[$i]}$r=1+$G[$i].$j+1;$G[$i]=$j;$p=1if/$G/;push@o,$r if$p&&$i++<@g}print@o

与空格相同:

map{
  map $g[$_]=$i|0, /\d/g;
  $i++
}split$,=',',<>;
shift@g;
@G=(0)x@g;
@u=(1)x10;
while(!$G[@g]){
  $G="@G";
  $_="@g";
  $i=0;
  $j=$G[0]+$u[0];
  while($j>2||$j<0){
    $u[$i++]*=-1;
    $j=$u[$i]+$G[$i]
  }
  $r=1+$G[$i].$j+1;
  $G[$i]=$j;
  $p=1if/$G/;
  push@o,$r if$p&&$i++<@g
}
print@o

用法:

echo 5-2,3-1,4 | perl hanoi.pl

输出:

21,23,12,23,12,32,21,23,12,23,12,32,21,32,12,23,21,32,21,32,12,23,12,32,21, 23,12,23,21,32,21,32,12,23,21,32,21,32,12,23,12,32,21,23,12,23,12,32,21,32, 12,23,21,32,21,23,12,23,12,32,21,23,12,23,21,32,21,32,12,23,21,32,21,32,12, 23,12,32,21,23,12,23,21,32,21,32,12,23,21,32,21,23,12,23,12,32,21,23,12,23, 12,32,21,32,12,23,21,32,21,23,12,23,12,32,21,23,12,23,12,32,21,32,12,23,21, 32,21,32,12,23,12,32,21,23,12,23,21,32,21,32,12,23,21,32,21,23,12,23,12,32, 21,23,12,23,12,32,21,32,12,23,21,32,21,23,12,23,12,32,21,23,12,23

于 2010-12-07T16:37:24.953 回答
0

尝试 Lua 我尝试从wikipedia实现迭代解决方案,但它并没有真正起作用,但我花在它上面的时间已经到了,所以我希望这能激发人们适应它。它确实可以很好地解析所有内容,包括空列。额外的好东西:它可以很好地打印堆栈,就像问题中的视觉表示一样。

-- Input "rod1,rod2,rod3" where rod? = a - seperated list of numbers, representing the disks.
p,q,r=io.read():match'([^,]*),([^,]*),([^,]*)'
print(p,q,r)
i=table.insert
u=unpack
function gen(t)
    return function(v)i(t,tonumber(v)) end
end

function basic(t,n) 
    for k,v in pairs(t) do
        print(k,"----")
        for kk,vv in pairs(v) do print("\t",kk,vv) end
    end
    print'================'
end
function pretty(t,n)
    local out={}
    for k=1,n do out[k]={} end
    for k=1,n do                -- K is each row
        local line=out[k]
        for l=1,3 do            -- L is each rod
            local d=t[l][k]
            if d~=1e9 then -- TODO Check if metahack necesarry
                line[#line+1]=(" "):rep(n-d+1)
                line[#line+1]=("="):rep(d)
                line[#line+1]="|"
                line[#line+1]=("="):rep(d)
                line[#line+1]=(" "):rep(n-d+1)
                line[#line+1]=" "
            else
                line[#line+1]=(" "):rep(2*n+4)
            end
        end
        out[k]=table.concat(line)
    end
    for k=n,1,-1 do
        io.write(out[k],"\n")
    end
end
function T(f,...)
    w=0
    for k=1,3 do
        l=({...})[k]
        w=#l==0 and w or f(w,u(l))
    end
    return w
end

Stat=pretty
t={{},{},{}} --rods 1 - 3, discs ordered 1 = bottom
for k,v in pairs{p,q,r}do -- loop over strings
    v:gsub('%d+',gen(t[k])) -- add decimal to rod
end
n=T(math.max,t[1],t[2],t[3]) -- Biggest disc = number of discs
--for k=1,3 do c=1*t[k][1] if n==c then A=k elseif m==c then C=k else B=k end end -- Rod where the biggest disc is (A)
for k=1,3 do setmetatable(t[k],{__index = function() return 1e9 end}) c=t[k] if c[#c]==1 then one=k end end -- locate smallest disc, and set index for nonexistant discs to 1e9
-- Locate second biggest disc (B), smallest stack = C -> move C to B
-- Algorithm:
-- uneven : move to the left, even: move to the right
-- move smallest, then move non-smallest.
-- repeat until done
--
-- For an even number of disks:
--
--     * make the legal move between pegs A and B
--     * make the legal move between pegs A and C
--     * make the legal move between pegs B and C
--     * repeat until complete
--
-- For an odd number of disks:
--
--     * make the legal move between pegs A and C
--     * make the legal move between pegs A and B
--     * make the legal move between pegs B and C
--     * repeat until complete
--
-- In each case, a total of 2n-1 moves are made.
d={{2,3,1},{3,1,2}}
s=d[math.fmod(n,2)+1] -- sense of movement -1 left (uneven # of discs), 1 right (even # of discs)
Stat(t,n)
for qqq=1,10 do
    -- move smallest
    d=s[one]
    print(one,d)
    if #t[d]==0 then print("skip rod",d,"next rod",s[d]) d=s[d] end-- if rod is empty, move to next in same direction
    table.insert(t[d],table.remove(t[one])) --TODO Problem
    print("Moved",one,"to",d)
    one=d -- track the small disc
    Stat(t,n)
    if #t[d]==n then break end -- destination stack reached number of discs, break off.
    -- find next valid move (compare the two non-previous-destination rod) to see which has the smallest disc, move disc to other rod.
    z=0
    for k=1,3 do
        print("-- k="..k)
        if k~=one then
            if z>0 then
                if t[k][#t[k]] > t[z][#t[z]] then   -- disc at rod z (source) is smaller than at k (destination)
                    d=k                                 -- destination = k 
                    print("-- t["..k.."]>t["..z.."], d="..d..", z="..z)
                else                                    -- disc at rod z (source) is bigger than at k (destination
                    d,z=z,k                             -- switch destination and source, so d will be z, and z will be the current rod
                    print("-- t["..k.."]<t["..z.."], d="..d..", z="..z)
                end
            else -- first of rods to compare
                z=k
                print("-- First rod to compare z="..z)
            end
        else
            print("-- disc one at this location, skipping",k)
        end
    end
    print("Will move from",z,"to",d)
    table.insert(t[d],table.remove(t[z]))
    Stat(t,n)
    if #t[d]==n then break end -- destination stack reached number of discs, break off.
end
于 2010-12-04T19:33:09.367 回答