2

I have seen this code on stack overflow post. I didn't understand what is the function of this line int Other = 3 - Startpeg - Endpeg; Can anyone explain

//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);
    }
}

Can anyone explain this line int Other = 3 - Startpeg - Endpeg; what is doing here and explain this line of code, what's going on here, Is it subtracting the endpeg from start and then then whole from 3 ?

Prune
  • 76,765
  • 14
  • 60
  • 81
Muhammad Hamza
  • 213
  • 1
  • 4
  • 14
  • 2
    `Other` gives the index of the tower which is *neither* `Startpeg` *nor* `Endpeg`. E.g. for `Startpeg = 2`, `Endpeg = 0`, the only other peg is at index `1`, which is indeed the value of `Other`. – meowgoesthedog Aug 23 '17 at 10:28

1 Answers1

0

Perhaps Otherpeg or Thirdpeg would clarify a little. As meowgoesthedog already showed in an example, this is a way of finding the third peg, the one other than the start or end peg.

The algebra behind this is simple: if we have three pegs with any numbering -- use a, b, c here -- then the sum of all three is a + b + c. If we know two of the peg values, we can get the third by subtracting from that sum. For instance,

total = a + b + c
// if we already know a and c, find the other peg value ...
other = total - a - c

More simply, this gives us other = b.

In the specific case, we've numbered the pegs 0, 1, 2 -- the total is 3, which is hard-coded into the program.

Does that beat the topic to death? :-)

Prune
  • 76,765
  • 14
  • 60
  • 81