An Efficient Implementation of Tower of Hanoi using Gray Codes

Similar documents
Enumerative Combinatoric Algorithms. Gray code

Let start by revisiting the standard (recursive) version of the Hanoi towers problem. Figure 1: Initial position of the Hanoi towers.

ECS 20 (Spring 2013) Phillip Rogaway Lecture 1

PUZZLES ON GRAPHS: THE TOWERS OF HANOI, THE SPIN-OUT PUZZLE, AND THE COMBINATION PUZZLE

Mathematics Competition Practice Session 6. Hagerstown Community College: STEM Club November 20, :00 pm - 1:00 pm STC-170

An Optimal Algorithm for a Strategy Game

Puzzling Math, Part 2: The Tower of Hanoi & the End of the World!

Games of Skill ANSWERS Lesson 1 of 9, work in pairs

6 RULE BASED EXPERT SYSTEM APPROACH TOWARDS THE RESOLUTION OF THE TOWER OF HANOI

Graphs of Tilings. Patrick Callahan, University of California Office of the President, Oakland, CA

Two-Player Tower of Hanoi

Directed Towers of Hanoi

The Apprentices Tower of Hanoi

Games of Skill Lesson 1 of 9, work in pairs

NANYANG TECHNOLOGICAL UNIVERSITY SEMESTER II EXAMINATION MH1301 DISCRETE MATHEMATICS. Time Allowed: 2 hours

NOTES ON SEPT 13-18, 2012

Module 7 Solving Complex Problems

New Sliding Puzzle with Neighbors Swap Motion

LAMC Junior Circle January 22, Oleg Gleizer. The Hanoi Tower. Part 2

18.204: CHIP FIRING GAMES

Implementation of Recursively Enumerable Languages in Universal Turing Machine

Topspin: Oval-Track Puzzle, Taking Apart The Topspin One Tile At A Time

RESTRICTED PERMUTATIONS AND POLYGONS. Ghassan Firro and Toufik Mansour Department of Mathematics, University of Haifa, Haifa, Israel

Module 7 Solving Complex Problems

Lesson Plan for Teachers

Coding Theory on the Generalized Towers of Hanoi

Reflections on the N + k Queens Problem

God s Number and the Robotic Turn Metric

The Tilings of Deficient Squares by Ribbon L-Tetrominoes Are Diagonally Cracked

CS 32 Puzzles, Games & Algorithms Fall 2013

Odd king tours on even chessboards

Mathematical Analysis of 2048, The Game

Magnetic Towers of Hanoi and their Optimal Solutions

Greedy Flipping of Pancakes and Burnt Pancakes

((( ))) CS 19: Discrete Mathematics. Please feel free to ask questions! Getting into the mood. Pancakes With A Problem!

arxiv: v1 [cs.ds] 17 Jul 2013

Numan Sheikh FC College Lahore

Struct: Finding Structure in Permutation Sets

Figure 1. Maximal nonoverlapping triangles with 3-6 lines.

CS103 Handout 25 Spring 2017 May 5, 2017 Problem Set 5

MAGIC SQUARES KATIE HAYMAKER

Gray code and loopless algorithm for the reflection group D n

Olympiad Combinatorics. Pranav A. Sriram

Mysterious number 6174

Water Gas and ElectricIty Puzzle. The Three Cottage Problem. The Impossible Puzzle. Gas

Tribute to Martin Gardner: Combinatorial Card Problems

Bibliography. S. Gill Williamson

Conway s Soldiers. Jasper Taylor

Closed Almost Knight s Tours on 2D and 3D Chessboards

CSE 20 DISCRETE MATH. Fall

PERMUTATIONS AS PRODUCT OF PARALLEL TRANSPOSITIONS *

Graph Application in The Strategy of Solving 2048 Tile Game

5.1 State-Space Search Problems

The Classification of Quadratic Rook Polynomials of a Generalized Three Dimensional Board

Playing with Permutations: Examining Mathematics in Children s Toys

Evacuation and a Geometric Construction for Fibonacci Tableaux

132-avoiding Two-stack Sortable Permutations, Fibonacci Numbers, and Pell Numbers

ActivArena TEMPLATES TEACHER NOTES FOR ACTIVARENA RESOURCES BLANK WORKING SPACE SPLIT (WITH TITLE SPACE) About this template

Checkpoint Questions Due Monday, October 7 at 2:15 PM Remaining Questions Due Friday, October 11 at 2:15 PM

lecture notes September 2, Batcher s Algorithm

Module 3 Greedy Strategy

Heuristic Search with Pre-Computed Databases

Winning Strategies for Hexagonal Polyomino Achievement

Fractal Designs for Quilts, Mosaics, and Other Decorated Surfaces, Part 1

The Place of Group Theory in Decision-Making in Organizational Management A case of 16- Puzzle

arxiv: v1 [cs.cc] 21 Jun 2017

Extended Introduction to Computer Science CS1001.py

An O(1) Time Algorithm for Generating Multiset Permutations

Grade 6 Math Circles February 21/22, Patterns - Solutions

ON THE PERMUTATIONAL POWER OF TOKEN PASSING NETWORKS.

A GRAPH THEORETICAL APPROACH TO SOLVING SCRAMBLE SQUARES PUZZLES. 1. Introduction

Pure Versus Applied Informatics

THE ASSOCIATION OF MATHEMATICS TEACHERS OF NEW JERSEY 2018 ANNUAL WINTER CONFERENCE FOSTERING GROWTH MINDSETS IN EVERY MATH CLASSROOM

10/5/2015. Constraint Satisfaction Problems. Example: Cryptarithmetic. Example: Map-coloring. Example: Map-coloring. Constraint Satisfaction Problems

Grade 6 Math Circles February 21/22, Patterns

THE ENUMERATION OF PERMUTATIONS SORTABLE BY POP STACKS IN PARALLEL

Mistilings with Dominoes

Three of these grids share a property that the other three do not. Can you find such a property? + mod

Once you get a solution draw it below, showing which three pennies you moved and where you moved them to. My Solution:

Q(A) - Balance Super Edge Magic Graphs Results

CS256 Applied Theory of Computation

Fig 1: Error Diffusion halftoning method

On uniquely k-determined permutations

FPGA implementation of DWT for Audio Watermarking Application

California 1 st Grade Standards / Excel Math Correlation by Lesson Number

arxiv: v1 [math.gm] 29 Mar 2015

Restricted Permutations Related to Fibonacci Numbers and k-generalized Fibonacci Numbers

THE use of balanced codes is crucial for some information

From a Ball Game to Incompleteness

Coin-Moving Puzzles. arxiv:cs/ v1 [cs.dm] 31 Mar Introduction. Erik D. Demaine Martin L. Demaine Helena A. Verrill

T H E M A T H O F S U D O K U

Heuristics, and what to do if you don t know what to do. Carl Hultquist

An Analytical Study in Connectivity of Neighborhoods for Single Round Robin Tournaments

Binary trees. Application: AVL trees and the golden ratio. The golden ratio. φ 1=1/φ 1. φ =1+

Generating indecomposable permutations

Week 1. 1 What Is Combinatorics?

#A13 INTEGERS 15 (2015) THE LOCATION OF THE FIRST ASCENT IN A 123-AVOIDING PERMUTATION

Search then involves moving from state-to-state in the problem space to find a goal (or to terminate without finding a goal).

Evaluation of CORDIC Algorithm for the processing of sine and cosine functions

@CRC Press. Discrete Mathematics. with Ducks. sarah-marie belcastro. let this be your watchword. serious mathematics treated with levity

Transcription:

GRD Journals Global Research and Development Journal for Engineering National Conference on Computational Intelligence Systems (NCCIS 17) March 2017 e-issn: 2455-5703 An Efficient Implementation of Tower of Hanoi using Gray Codes 1 Hari Krishnan.V 2 Sandhya.M.K 3 Monica Jenefer.B 1 UG Student 2,3 Associate Professor 1,2,3 Department of CSE 1,2,3 Meenakshi Sundararajan Engineering College Chennai, India Abstract The Tower of Hanoi Puzzle finds its applications ranging from robotics to psychological research. This puzzle is a classic case of recursive algorithm in programming. However, this puzzle can also be implemented using iterative programming, by using binary codes or gray codes. Various applications require an optimized solution for this puzzle. In this paper, an efficient implementation of Tower of Hanoi using Gray codes for n disks and three rods is presented. This focuses only on minimizing storage and reducing running time as required by many applications. The proposed implementation using Gray code system consumes lesser memory and slightly reduced running time compared to the conventional recursive methodology. Keyword- Tower of Hanoi; Gray Codes; Recursion; Non-recursive algorithm I. INTRODUCTION The Tower of Hanoi, a mathematical game or puzzle, was invented by E. Lucas in 1883 [1, 3]. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The disks in a stack are arranged in ascending order of size on one rod, the smallest at the top, thus making a conical shape [4]. The objective of this puzzle is to move the entire stack from one rod to another rod using an intermediate rod, following the three rules: (i) Only one disk can be moved at a time, (ii) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e., a disk can only be moved if it is the uppermost disk on a stack and (iii) No larger disk may be placed on top of a smaller disk. Figure 1 represents the initial and final positions of Tower of Hanoi. The minimum number of moves required to solve a Tower of Hanoi puzzle is (2n 1), where n is the number of disks. With three disks, the puzzle can be solved in seven moves. The problem is isomorphic to finding a Hamiltonian path on an n-hypercube [5, 6]. The Tower of Hanoi puzzle is used in different applications [7]. It is used as a backup rotation scheme for performing computer data backups where multiple tapes or media are involved. It provides a good standardized test bed to evaluate integration of high-level reasoning capabilities of robots together with their manipulation and perception aspects. It is frequently used in psychological research on problem solving. The Tower of Hanoi is also used as a test by neuropsychologists trying to evaluate frontal lobe deficits [7]. (a) Initial Position (b) Final Position Fig. 1: Tower of Hanoi Puzzle 71

The rest of the paper is organised as follows: Section II presents the existing recursive methology and its pitfalls. Section III presents the proposed solution using Gray codes. Section IV discusses on the performance of the proposed solution. Section V gives the concluding remarks and future scope of this work. II. RELATED WORK Recursive algorithm is the preferred solution for this puzzle. There are also other solutions which are based on non-recursive algorithms, binary codes and gray codes. Iterative solution alternates the moves between the smallest disk and a non-smallest disk. Recursive solution breaks the problem into a collection of smaller problems and further breaking those problems down into even smaller problems until a solution is reached [1, 4, 7]. This is carried out by the following the steps: 1) move n 1 disks from source peg A to intermediate peg B, 2) move disk n from peg A to the destination peg C and 3) move n 1 disks from peg B to peg C such that they are placed on disk n. Start Procedure Hanoi(disk, source, dest, aux) if disk == 0 then move disk from source to dest else Hanoi(disk - 1, source, aux, dest) move disk from source to dest Hanoi(disk - 1, aux, dest, source) end if end Procedure STOP Fig. 2: Algorithm for the Recursive Implementation The algorithm for recursive implementation is given in Figure 2. The recursive solution is the easiest to comprehend, but fails to accommodate as number of disks increases. In the binary solution, the disk positions are determined directly from the binary (base 2) representation of the move number (the initial state being move 0, with all digits 0, and the final state being, with all digits 1). The proposed solution using Gray code gives an alternative way of solving the puzzle [2, 4, 7]. All these solutions aim at minimizing the number of moves. III. METHODOLOGY The aim of this work is to implement Tower of Hanoi puzzle using Gray codes with lesser memory and lesser running time compared to the recursive algorithm for three rods and n disks. In the Gray code system, numbers are expressed in a binary combination of 0s and 1s, but rather than being a standard positional numeral system, Gray code operates on the premise that each value differs from its predecessor by exactly one bit changed [2,4,7]. 1. for step no i 2. Stop. 1.1 Compute i th and (i+1) th grey number. 1.2 XOR the two numbers and note which bit changes. 1.3 Let the bit change occur at position j 1.3.1 if j is equal to n, GOTO 2 1.4 Compute the FROM_PEG and TO_PEG using the formula FROM_PEG = (i & (i-1)) % 3 TO_PEG = ((i i-1) +1) % 3 1.5 if the number of disks is even then swap the peg 2 with peg 3. 1.6 Move disk j from FROM_PEG to TO_PEG. 1.7 GOTO step 1.1 Fig. 3: Algorithm for the Gray Code Implementation The number of bits present in Gray code is important, and leading zeros are not optional, unlike in positional systems. If one counts in Gray code of a bit size equal to the number of disks in Tower of Hanoi, begins at zero, and counts up, then the bit changed each move corresponds to the disk to move, where the least-significant-bit is the smallest disk and the most-significant- 72

bit is the largest. Counting moves from 1 and identifying the disks by numbers starting from 0 in order of increasing size, the ordinal of the disk to be moved during move m is the number of times m can be divided by 2 [7]. This implementation is for n disks and 3 rods. The algorithm for the Gray code methodology is presented in Figure 3. IV. DISCUSSION The implementation of tower of Hanoi puzzle using Gray code is analysed based on: (i) running time and (ii) memory. Its performance is compared with the conventional recursive algorithm. The impact of number of disks on running time is presented as graph in Figure 4. In Figure 4 (a), the number of disks is less than or equal to 5 and in Figure 4 (b), the number of disks ranges from 6 to 10. From the Figure 4(a), it is evident that the running time for disks lesser than or equal to 5 is almost the same for Gray Code implementation and recursive method. But as the number of disks increases the running time of the recursive method is slightly higher than the Gray code implementation. It is seen from Figure 4 (b) that the running time is higher for recursive method for more than 6 disks. (a) Less than or equal to 5 disks (b) 6 to 10 disks Fig. 4: Impact of number of disks on running time 73

Fig. 5: Impact of number of disks on memory The impact of number of disks on memory requirement for the recursive method increases as the number of disks increases. But the Gray code implementation consumes lesser memory irrespective of the number of disks. This is evident from Figure 5. The number of moves m n required to solve the puzzle of n disks on three rods is given by the recurrence relation With M 1=1 and solving the recurrence relation we get, M n =2M (n-1)+1 (1) M n=2 n -1 (2) For three rods, the proof that the above solution is minimal can be achieved using the Lucas correspondence which relates Pascal's triangle to the Hanoi graph. While algorithms are known for transferring disks on four rods, none has been proved minimal. As the number of disks is increases (for three rods), an infinite sequence is obtained, the first few of them are presented in Table 1. This is exactly the binary carry sequence plus one. The number of disks moved after the kth step is the same as the element which needs to be added or deleted in the kth value of the Ryser formula [2, 8-10]. Number of Disks (n) Sequence of Moves (Sn) 1 1 2 1, 2, 1 3 1, 2, 1, 3, 1, 2, 1 4 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1 Table 1: Sequence of Moves A Hanoi graph can be constructed whose graph vertices correspond to legal configurations of n towers of Hanoi, where the graph vertices are adjacent if the corresponding configurations can be obtained by a legal move. The puzzle itself can be solved using a binary Gray code. Poole and Rangel-Mondragón give Wolfram Language routines for solving the Hanoi towers problem [2, 8, 11-13]. Poole's algorithm works for an arbitrary disk configuration, and provides the solution in the fewest possible moves [8, 11-12]. V. CONCLUSION This paper presents an efficient implementation of Tower of Hanoi using Gray Codes for three rods and n disks. The proposed solution focuses at reducing the memory requirement and running time compared to conventional recursive methodology. As a future work, this work can be extended to provide solution to the tower of Hanoi puzzle greater than three rods. 74

REFERENCES [1] https://en.wikipedia.org/wiki/tower_of_hanoi [2] http://mathworld.wolfram.com/towerofhanoi.html [3] Lucas, É. Récréations mathématiques, Vol. 3. Paris: Gauthier-Villars, 1891-1894. (Reprinted Albert Blanchard, 1960). [4] Anany Levitin, Introduction to the Design and Analysis of Algorithms, Third Edition, Pearson Education, 2012. [5] Gardner, M. "Mathematical Games: About the Remarkable Similarity between the Icosian Game and the Towers of Hanoi." Sci. Amer., 150-156, May 1957. [6] Gardner, M. "The Icosian Game and the Tower of Hanoi." Ch. 6 in Hexaflexagons and Other Mathematical Diversions: The First Scientific American Book of Puzzles and Games. New York: Simon and Schuster, pp. 55-62, 1959. [7] https://en.wikipedia.org/wiki/tower_of_hanoi [8] Weisstein, Eric W. "Tower of Hanoi." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/towerofhanoi.html. [9] R. J. Gardner and P. Gritzmann, Discrete tomography: Determination of finite sets by X-rays, Trans. Amer. Math. Soc. 349 (1997), 2271 2295. [10] Vardi, I. Computational Recreations in Mathematica. Reading, MA: Addison-Wesley, pp. 111-112, 1991 [11] Poole, D. G. "The Towers and Triangles of Professor Claus (or, Pascal Knows Hanoi)." Math. Mag., 323-344, 1994. [12] http://mathworld.wolfram.com/packages/hanoi.m. [13] http://library.wolfram.com/infocenter/mathsource/4861 75