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

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →