# 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 :

```                            ```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 = { -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) {
if (r < r || r < 0) {
moves[*movesCount] = state | (1 << (r * 2));
*movesCount += 1;
}
if (r < r || r < 0) {
moves[*movesCount] = state | (2 << (r * 2));
*movesCount += 1;
}
if (r < r || r < 0) {
moves[*movesCount] = state | (3 << (r * 2));
*movesCount += 1;
}
}
if (r >= 0) {
if (r < r || r < 0) {
moves[*movesCount] = state & (~(1 << (r * 2)));
*movesCount += 1;
}
if (r < r || r < 0) {
moves[*movesCount] = state & (~(1 << (r * 2)));
moves[*movesCount] |= (2 << (r * 2));
*movesCount += 1;
}
if (r < r || r < 0) {
moves[*movesCount] = state | (3 << (r * 2));
*movesCount += 1;
}
}
if (r >= 0) {
if (r < r || r < 0) {
moves[*movesCount] = state & (~(2 << (r * 2)));
*movesCount += 1;
}
if (r < r || r < 0) {
moves[*movesCount] = state & (~(2 << (r * 2)));
moves[*movesCount] |= (1 << (r * 2));
*movesCount += 1;
}
if (r < r || r < 0) {
moves[*movesCount] = state | (3 << (r * 2));
*movesCount += 1;
}
}
if (r >= 0) {
if (r < r || r < 0) {
moves[*movesCount] = state & (~(3 << (r * 2)));
*movesCount += 1;
}
if (r < r || r < 0) {
moves[*movesCount] = state & (~(3 << (r * 2)));
moves[*movesCount] |= (1 << (r * 2));
*movesCount += 1;
}
if (r < r || r < 0) {
moves[*movesCount] = state & (~(3 << (r * 2)));
moves[*movesCount] |= (2 << (r * 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;
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;
forn (i, n) {
int k;
cin >> k;
mask |= ((k - 1) << (2 * i));
}
forn (i, 1 << 20)
d[i] = inf;
queue<int> o;
while (!o.empty()) {
o.pop();
break;
vector<int> b;
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;
o.push(to);
}
}
cout << d << '\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();
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();
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);
} else {
//                                        System.out.print("Already seen position "); printScore(newTest, n);
}
}
}
}
}
}
}

currentTests = nextTests;
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();

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)```
```

## Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

## Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

## Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

## Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

## Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

## Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your \$inOrder* func