by pieguy · 11y ago · 0 comments
void iterative(int n)
{
int from[2][3] = {{0,1,2},{0,2,1}};
int to[2][3] = {{1,2,0},{2,1,0}};
for(int i=1; i<1<<n; i++)
{
int disk = __builtin_ctz(i);
int count = (i>>(1+disk))%3;
int parity = (disk^n)&1;
move(from[parity][count], to[parity][count]);
}
} g++ -o hanoi hanoi.cpp -O2 -lrtSo I'm seeing similar results as you. Your iterative implementation is about 3x faster than the author's, but still not as fast as the recursive version. I'm surprised!