河内的塔了解

时间:2017-08-23 09:23:46

标签: recursion towers-of-hanoi

我在堆栈溢出帖子上看到过这段代码。我不明白这行的功能是什么 int Other = 3 - Startpeg - Endpeg; 任何人都可以解释

//Pegs are counted 0 to 2

void Tower(int Disk, int Startpeg, int Endpeg)
{
    if(Disc <= 0)  //Sanity check
        return;

    if(Disc == 1)
        cout << "Move disk from "<<Startpeg<<" to "<<Endpeg<<endl;
    else
    {
        int Other = 3 - Startpeg - Endpeg;
        Tower(Disc-1, Startpeg,  Other);
        Tower(1, Startpeg, Endpeg); //Inline output would do here... Calling for message consistency.
        Tower(Disc-1, Other, Endpeg);
    }
}

任何人都可以解释这一行int Other = 3 - Startpeg - Endpeg;在这里做什么并解释这行代码,这里发生了什么,它是从开始减去endpeg然后从3减去整个?

1 个答案:

答案 0 :(得分:0)

或许 Otherpeg Thirdpeg 会澄清一点。正如meowgoesthedog在一个例子中已经显示的那样,这是一种找到第三个挂钩的方式,除了开始或结束钉之外的其他方式。

这背后的代数很简单:如果我们有三个任何编号的钉子 - 在这里使用 a,b,c - 那么这三个的总和是2017-01-01 18:02:03。如果我们知道两个peg值,我们可以从该总和中减去第三个。   例如,

a + b + c

更简单地说,这给了我们total = a + b + c // if we already know a and c, find the other peg value ... other = total - a - c

在特定情况下,我们将第0,1,2号钉编号 - 为3,这是硬编码到程序中。

这会让这个话题成功吗? : - )

相关问题