Gena Playing Hanoi


Problem Statement :


The Tower of Hanoi is a famous game consisting of  rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:

Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has  rods and  disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod .

Note: Gena's rods are numbered from  to . The radius of a disk is its index in the input array, so disk  is the smallest disk with a radius of , and disk  is the largest with a radius of .

Function Description

Complete the hanoi function below.

hanoi has the following parameters:

int posts[n]:  is the location of the disk with radius 
Returns

int: the minimum moves to reset the game to its initial state
Input Format

The first line contains a single integer, , the number of disks.
The second line contains  space-separated integers, where the  integer is the index of the rod where the disk with diameter  is located.



Solution :



title-img


                            Solution in C :

In  C  :






#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

typedef struct _QueueElement {
    int move;
    int state;
} QueueElement;


int N;


#define QUEUE_SIZE (1024*1024*16)
QueueElement queue[QUEUE_SIZE];
char enqueued[QUEUE_SIZE];
int queueCount = 0;
int queueStart = 0;

int emptyQueue()
{
    return (queueCount == 0);
}


void pushQueue(int move, int state)
{
    int index = queueStart + queueCount;
    if (index >= QUEUE_SIZE) {
        index -= QUEUE_SIZE;
    }
    if (enqueued[state] != move) {
        queue[index].move  = move;
        queue[index].state = state;
        enqueued[state] = move;
        queueCount += 1;
    }
}


int popQueue(int *move)
{
    int res = queue[queueStart].state;
    *move = queue[queueStart].move;
    queueStart += 1;
    if (queueStart >= QUEUE_SIZE) {
        queueStart -= QUEUE_SIZE;
    }
    queueCount -= 1;
    return res;
}


void genMoves(int state, int *moves, int *movesCount)
{
    int rod;
    int i = 0;
    int r[4] = { -1, -1, -1, -1 };
    int tmp = state;
    while (tmp) {
        rod = tmp & 0x3;
        if (r[rod] < 0) {
            r[rod] = i;
        }
        tmp >>= 2;
        i += 1;
    }
    *movesCount = 0;
    if (r[0] >= 0) {
        if (r[0] < r[1] || r[1] < 0) {
            moves[*movesCount] = state | (1 << (r[0] * 2));
            *movesCount += 1;
        }
        if (r[0] < r[2] || r[2] < 0) {
            moves[*movesCount] = state | (2 << (r[0] * 2));
            *movesCount += 1;
        }
        if (r[0] < r[3] || r[3] < 0) {
            moves[*movesCount] = state | (3 << (r[0] * 2));
            *movesCount += 1;
        }
    }
    if (r[1] >= 0) {
        if (r[1] < r[0] || r[0] < 0) {
            moves[*movesCount] = state & (~(1 << (r[1] * 2)));
            *movesCount += 1;
        }
        if (r[1] < r[2] || r[2] < 0) {
            moves[*movesCount] = state & (~(1 << (r[1] * 2)));
            moves[*movesCount] |= (2 << (r[1] * 2));
            *movesCount += 1;
        }
        if (r[1] < r[3] || r[3] < 0) {
            moves[*movesCount] = state | (3 << (r[1] * 2));
            *movesCount += 1;
        }
    }
    if (r[2] >= 0) {
        if (r[2] < r[0] || r[0] < 0) {
            moves[*movesCount] = state & (~(2 << (r[2] * 2)));
            *movesCount += 1;
        }
        if (r[2] < r[1] || r[1] < 0) {
            moves[*movesCount] = state & (~(2 << (r[2] * 2)));
            moves[*movesCount] |= (1 << (r[2] * 2));
            *movesCount += 1;
        }
        if (r[2] < r[3] || r[3] < 0) {
            moves[*movesCount] = state | (3 << (r[2] * 2));
            *movesCount += 1;
        }
    }
    if (r[3] >= 0) {
        if (r[3] < r[0] || r[0] < 0) {
            moves[*movesCount] = state & (~(3 << (r[3] * 2)));
            *movesCount += 1;
        }
        if (r[3] < r[1] || r[1] < 0) {
            moves[*movesCount] = state & (~(3 << (r[3] * 2)));
            moves[*movesCount] |= (1 << (r[3] * 2));
            *movesCount += 1;
        }
        if (r[3] < r[2] || r[2] < 0) {
            moves[*movesCount] = state & (~(3 << (r[3] * 2)));
            moves[*movesCount] |= (2 << (r[3] * 2));
            *movesCount += 1;
        }
    }
}


int main()
{
    int i;
    for (i = 0; i < QUEUE_SIZE; ++i) {
        enqueued[i] = -1;
    }
    scanf("%d", &N);
    {
        int state = 0;
        int tmp;
        for (i = 0; i < N; ++i) {
            scanf("%d", &tmp);
            state |= (tmp - 1) << (i * 2);
        }
        pushQueue(0, state);
    }

    {
        int state;
        int move;
        int moves[6];
        int movesCount;

        while (! emptyQueue()) {
            state = popQueue(&move);
            if (! state) {
                break;
            }

            genMoves(state, moves, &movesCount);
            for (i = 0; i < movesCount; ++i) {
                pushQueue(move + 1, moves[i]);
            }
        }

        printf("%d\n", move);
    }

    return 0;
}
                        


                        Solution in C++ :

In  C++  :







#include <bits/stdc++.h>

using namespace std;

#define sz(x) ((int) (x).size())
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define forab(i,a,b) for (int i = int(a); i < int(b); ++i)

typedef long long ll;
typedef long long i64;
typedef long double ld;

const int inf = int(1e9) + int(1e5);
const ll infl = ll(2e18) + ll(1e10);

int d[1 << 20];

int main() {
    cout.precision(10);
    cout.setf(ios::fixed);
    #ifdef LOCAL
    assert(freopen("c.in", "r", stdin));
    #else
    #endif
    int n;
    cin >> n;
    int mask = 0;
    forn (i, n) {
        int k;
        cin >> k;
        mask |= ((k - 1) << (2 * i));
    }
    forn (i, 1 << 20)
        d[i] = inf;
    d[mask] = 0;
    queue<int> o;
    o.push(mask);
    while (!o.empty()) {
        int mask = o.front();
        o.pop();
        if (mask == 0)
            break;
        vector<int> b[4];
        forn (i, n)
            b[(mask >> (2 * i)) & 3].push_back(i);
        forn (i, 4)
            b[i].push_back(inf);
        forn (i, 4)
            forn (j, 4) {
                if (b[i].front() >= b[j].front())
                    continue;
                int id = b[i].front();
                int to = mask ^ ((i ^ j) << (2 * id));
                if (d[to] < inf)
                    continue;
                d[to] = d[mask] + 1;
                o.push(to);
            }
    }
    cout << d[0] << '\n';
    #ifdef LOCAL
    cerr << "Time: " << double(clock()) / CLOCKS_PER_SEC << '\n';
    #endif
}
                    


                        Solution in Java :

In  Java :







import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static int[] readIntArray3(Scanner in, int size) {
        int[] arr = new int[size];
        for (int i = 0; i < size; i++) {
            arr[i] = in.nextInt();
        }
        return arr;
    }



    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        int cases = 1;//in.nextInt();
        for (int testcase = 0; testcase < cases; testcase++) {
            int n = in.nextInt();
            int[] arr = readIntArray3(in, n);
            genahanoi(n, arr);
        }
    }

    public static void genahanoi(int n, int[] locs) {
        int[] powers = new int[]{1,4,16,64,256,1024,4096,16384,65536,262144};
        int score = 0;
        for (int i = 0; i < n; i++) {
            score += powers[i]*(locs[i]-1);
        }
        Set<Integer> allTests = new HashSet();
        Set<Integer> currentTests = new HashSet();
        currentTests.add(score);
        allTests.add(score);
        int currentMoves = 0;
//        printScore(score, n);
        while (!currentTests.contains(0)) {
            Set<Integer> nextTests = new HashSet();
            for (int test : currentTests) {
//                System.out.print("Looking at position "); printScore(test, n);
                int[] tops = new int[]{-1,-1,-1,-1};
                for (int i = n-1; i >=0; i--) {
                    int loc = (test>>(2*i))%4;
                    tops[loc] = i;
                }
                for (int j = 0; j < 4; j++) {
                    if (tops[j] >= 0) {
                        for (int k = 0; k < 4; k++) {
                            if ( k != j) {
                                if (tops[k] == -1 || tops[k] > tops[j]) {
                                    int newTest = test - (j<<(2*tops[j])) + (k<<(2*tops[j]));
                                    if (!allTests.contains(newTest)) {
//                                    System.out.print("Found new position "); printScore(newTest, n);
                                        nextTests.add(newTest);
                                    } else {
//                                        System.out.print("Already seen position "); printScore(newTest, n);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            currentTests = nextTests;
            allTests.addAll(currentTests);
            currentMoves++;
        }
        System.out.println(currentMoves);
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :








#!/bin/python3

import sys

def generate(move, N):
    next = []
    i = 0
    
    available = [1, 2, 3, 4]
    
    while (i < N):
        if len(available) == 0:
            break
        elif (move[i] in available):
            available.remove(move[i])
        else:
            i = i + 1
            continue
            
        for m in available:
            amove = list(move)
            amove[i] = m
            next.append(tuple(amove))
            
        i = i + 1
        
    return set(next);

N = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(' ')]

initial = [];
i = 0
while (i < N):
    initial.append(1)
    i = i + 1

moves = set();
moves.add(tuple(initial));

current = set(moves)
gen = 0

while True:
    next = set()
    for move in current:
        next.update(generate(move, N))
        
    gen = gen + 1    
    next.difference_update(moves)
    moves.update(next)
    
    if (tuple(a) in next):
        print(gen)
        break
    
    current = set(next)
                    


View More Similar Problems

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →