tag:blogger.com,1999:blog-17564325933806039742017-06-25T18:55:00.695-07:00Intelligence In GamingAshoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.comBlogger15125tag:blogger.com,1999:blog-1756432593380603974.post-71015277625283765552011-09-18T03:48:00.000-07:002011-12-09T03:04:52.615-08:00Battles at Google Ai ChallengeIt has been quite some time since the last post...<br /><br />I got busy in Google AI challenge. Thought of sharing few of interesting games from there.<br /><br /><br />This list will be updated regularly. Have a look... if you are not already challenging your coding skills in here, after seeing at some of these battles, you might want to check it out!<br /><br />Few things to note :<br />1) Use the green filter at your left hand side to view the game as the bot would have seen it. Even though we can see the whole map, bots can see areas only within a radius from their own ants.<br /><br />2) 2 Points are awarded for every kill while only 1 point for a new spawn. No bonus for remaining with the larger army at the end! <br /><br />3) List seems to getting longer, I will crop away most of these games and will leave only the most elegant ones here.<br /><br />4) If you have any beautiful games, feel free to comment the links and I will include them in here. :-)<br /><br />5) Note on Dec 9th. Old games were taken out from the beta site now that the official tournament is on. So I removed those links and including real games from the official competition.Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com1tag:blogger.com,1999:blog-1756432593380603974.post-78030869132462925572011-05-24T00:02:00.000-07:002011-05-24T00:02:54.295-07:00Bringing Down Towers of Hanoi - part10So we have come to the final part of this series! As promised, we will be ending the series with the source code which solves 4 tower case (can be generalized to more towers)<br /><br /><br />For those who are new and like to give it a try before looking at the solutions, <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part4.html">part4</a> is probably a good place to start, unless you are really new to Towers of Hanoi, in which case it should be <a href="http://iq-games.blogspot.com/2011/02/planet-wars-my-first-ai-contest.html">part1</a>.<br /><br />I haven't yet seen a java code to solve the general case for towers of hanoi for 4 towers. If you see a code let me know. I will try to format this nicely and add some comments too later. Since <a href="http://iq-games.blogspot.com/2011/04/bringing-down-towers-of-hanoi-part9.html">earlier</a> posts contained all explanations needed, I hope you will be able to figure out the algorithm easily. Enjoy!<br /><br />package com.araaya.hanoitowers;<br /><br />import java.util.ArrayList;<br />import java.util.Hashtable;<br />import java.util.StringTokenizer;<br /><br />/**<br /> *@author Ashoka Ekanayaka<br /> * www.it-front.net, www.araaya.com<br /> */<br />public class HanoiTowers4 {<br /> //ArrayList<Integer> source1, target1, middle1, middle2;<br /> //int steps = -1;<br /> static Hashtable<Integer, HeightInfo> table = new Hashtable<Integer, HeightInfo>();<br /> static {<br /> table.put(1, new HeightInfo(1,0,1));<br /> }<br /><br /> public static void main(String[] args) {<br /> int height = Integer.parseInt(args[0]);<br /> ArrayList<String> towers = new ArrayList<String>(4);<br /> String s = "";<br /> for (int i=height; i>0; i--) {<br /> s = s + i;<br /> if (i != 1) {<br /> s= s + ",";<br /> }<br /> }<br /> towers.add(s);<br /> towers.add("");<br /><br /> //s = "";<br /> //for (int i=2; i>0; i--) {<br /> // s = s + i;<br /> // if (i != 1) {<br /> // s= s + ",";<br /> // }<br /> //}<br /> towers.add("");<br /><br /> towers.add("");<br /> String moveList = HanoiTowers4.getSolution(height, 4, towers);<br /> String[] moves = moveList.split(",");<br /> System.out.println(moves.length + " Moves");<br /> System.out.println(moveList);<br /> }<br /><br /> public static String getSolution(int diskCount, int towerCount, ArrayList<String> towerContents) {<br /> ArrayList<ArrayList<Integer>> towers = new ArrayList<ArrayList<Integer>>(towerCount);<br /> for (int i=0; i<towerCount; i++) {<br /> String s = towerContents.get(i);<br /> ArrayList<Integer> tower = new ArrayList<Integer>(diskCount);<br /><br /> if (!s.equals("")) {<br /> String[] disks = s.split(",");<br /> for (int j=0; j<disks.length; j++) {<br /> tower.add(Integer.parseInt(disks[j]));<br /> }<br /> }<br /> towers.add(tower);<br /> }<br /><br /> StringBuilder moveList = new StringBuilder();<br /> if (towerCount == 3) {<br /> return buildTower3(diskCount, 0, 0, 2, 1, towers, moveList).toString();<br /> } else if (towerCount == 4) {<br /> return buildTower4(diskCount, 0, 3, 1, 2, towers, moveList).toString();<br /> } else {<br /> return null;<br /> }<br /> }<br /><br /> public static StringBuilder buildTower4(int height, int source, int target, int middle1, int middle2, ArrayList<ArrayList<Integer>> towers, StringBuilder moveList) {<br /> if (height == 0) {<br /> return moveList;<br /> }<br /><br /> ArrayList<Integer> targetTower = towers.get(target);<br /> if (targetTower.contains(Integer.valueOf(height))) {<br /> buildTower4(height-1, source, target, middle1, middle2, towers, moveList);<br /> } else {<br /> ArrayList<Integer> middle1Tower = towers.get(middle1);<br /> ArrayList<Integer> middle2Tower = towers.get(middle2);<br /> if (middle1Tower.contains(Integer.valueOf(height))) {<br /> int temp = middle1;<br /> middle1 = source;<br /> source = temp;<br /> }<br /> if (middle2Tower.contains(Integer.valueOf(height))) {<br /> int temp = middle2;<br /> middle2 = source;<br /> source = temp;<br /> }<br /><br /> int newHeight = getSteps(height).t4Height;<br /><br /> buildTower4(newHeight, source, middle1, middle2, target, towers, moveList);<br /> if (height > 2) {<br /> buildTower3(height-1, newHeight, source, middle2, target, towers, moveList);<br /> }<br /> move(source, target, towers, moveList);<br /> print(towers);<br /> if (height > 2) {<br /> buildTower3(height-1, newHeight, middle2, target, source, towers, moveList);<br /> }<br /> buildTower4(newHeight, middle1, target, middle2, source, towers, moveList);<br /> }<br /><br /> return moveList;<br /> }<br /><br /> public static StringBuilder buildTower3(int height, int ceiling, int source, int target, int middle, ArrayList<ArrayList<Integer>> towers, StringBuilder moveList) {<br /> if (height == ceiling) {<br /> return moveList;<br /> }<br /><br /> ArrayList<Integer> targetTower = towers.get(target);<br /> if (targetTower.contains(Integer.valueOf(height))) {<br /> buildTower3(height-1, ceiling, source, target, middle, towers, moveList);<br /> } else {<br /> ArrayList<Integer> middleTower = towers.get(middle);<br /> if (middleTower.contains(Integer.valueOf(height))) {<br /> int temp = middle;<br /> middle = source;<br /> source = temp;<br /> }<br /> buildTower3(height-1, ceiling, source, middle, target, towers, moveList);<br /> move(source, target, towers, moveList);<br /> print(towers);<br /> buildTower3(height-1, ceiling, middle, target, source, towers, moveList);<br /> }<br /><br /> return moveList;<br /> }<br /><br /> public static HeightInfo getSteps(int height) {<br /> if (table.containsKey(height)) {<br /> return table.get(height);<br /> }<br /><br /> boolean optimalFound = false;<br /> int optimalSteps = Integer.MAX_VALUE;<br /><br /> int t4 = 0;<br /> int steps = 0;<br /> for (int t4Height = height-1; !optimalFound && t4Height>0; t4Height--) {<br /> int t3Height = (height - 1) - t4Height;<br /> steps = 1 + 2*(getSteps(t4Height).steps) + 2*((1 << t3Height) - 1);<br /> if (steps < optimalSteps) {<br /> optimalSteps = steps;<br /> t4 = t4Height;<br /> System.out.println("current minimum steps for height " + height + " is : " + steps + " with " + t4Height + "-" + t3Height);<br /> } else {<br /> optimalFound = true; // no point searching beyond this. current steps are the optimal<br /> }<br /> }<br /><br /> System.out.println("putting => " + height + ":" + optimalSteps + ":" + t4);<br /> HeightInfo info = new HeightInfo(height, t4, optimalSteps);<br /> table.put(height, info);<br /><br /> return info;<br /> }<br /><br /> private static void print(ArrayList<ArrayList<Integer>> towers) {<br /> for (ArrayList<Integer> tower : towers) {<br /> for (Integer i : tower) {<br /> System.out.print(i+",");<br /> }<br /> System.out.print(" : ");<br /> }<br /> System.out.println();<br /> }<br /><br /> private static void move(int source, int target, ArrayList<ArrayList<Integer>> towers, StringBuilder strB) {<br /> ArrayList<Integer> targetTower = towers.get(target);<br /> ArrayList<Integer> sourceTower = towers.get(source);<br /> targetTower.add(sourceTower.get(sourceTower.size()-1)); // add the top most element in source to the top of target<br /> sourceTower.remove(sourceTower.size()-1);<br /> strB.append(source + 1);<br /> strB.append("-");<br /> strB.append(target + 1);<br /> strB.append(",");<br /> }<br />}Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com7tag:blogger.com,1999:blog-1756432593380603974.post-42361170843205039642011-04-29T04:09:00.000-07:002011-04-29T04:09:18.040-07:00Bringing Down Towers of Hanoi - part9As we promised in <a href="http://iq-games.blogspot.com/2011/04/towers-of-hanoi-part-8.html">part8</a> of this series, In this post we are going to see few sample outputs from Tower4 program in action. Also we will discuss the algorithm behind how to determine the best breakdown of middle towers. (Remember, in four tower case, we have choices on how to distribute the disks between tower 2 and 3 when we want to move disks from tower 1 to 4)<br /><br />Let's see the case of 5 disks :<br /><br />6,5,4,3,2, : : 1, : <br />6,5,4,3, : : 1, : 2, <br />6,5,4, : 3, : 1, : 2, <br />6,5,4, : 3,2, : 1, : <br />6,5,4, : 3,2,1, : : <br />6,5, : 3,2,1, : : 4, <br />6, : 3,2,1, : 5, : 4, <br /><span style="color: blue;">6, : 3,2,1, : 5,4, : </span><br /> : 3,2,1, : 5,4, : 6, <br />4, : 3,2,1, : 5, : 6, <br />4, : 3,2,1, : : 6,5, <br /> : 3,2,1, : : 6,5,4, <br /> : 3,2, : 1, : 6,5,4, <br />2, : 3, : 1, : 6,5,4, <br />2, : : 1, : 6,5,4,3, <br /> : : 1, : 6,5,4,3,2, <br /> : : : 6,5,4,3,2,1, <br />17 Moves<br /><br />If we look at step 8 above (in blue), we will see that the program has distributed top 5 disks as 3 : 2 in the middle 2 towers. It has then moved the 6th disk to 4th tower. It could have distributed them as 4 : 1, but has found that it will be more costly. Mini tower 3-2-1 it has created on tower2 was created using all 4 towers but the Mini tower it has created on tower3 (which has disks 4 and 5) was created using only 3 towers while keeping the already buildup content at tower 2 intact.<br /><br />Once the biggest disk (disk 6) was moved to tower 4, program has created a mini tower 4-5 at top of tower4 while keeping tower 2 intact. After that step it has created a mini tower 3-2-1 on tower4 using all 4 towers.<br /><br />Let's have a good look at again and make sure we understand the process! <br /><br />In general, to solve 4 tower case for n disks, we need to follow these steps :<br /><b>1) find optimal numbers for x and y such that x+y=n-1</b><br /><br /><b>2) build a tower of hight x in tower2 using all 4 towers</b><br /><br /><b>3) build a tower of height y (starting from disk x+1) in tower3 while using only 3 towers (since the content we built on tower2 need to be preserved) </b><br /><br /><b>4) move the largest disk (which is n) from tower 1 to tower4</b><br /><br /><b>5) build a tower of height y on top of tower4 (starting from disk x+1) while using only 3 towers and keeping the content on tower2 intact.</b><br /><br /><b>6) build a tower of height x in tower4 using all 4 towers.</b><br /><br /><br />Above is a recursive algorithm because to build a tower of n using all 4 towers, we will have to build a tower of x using all 4 towers!<br /><br />Now, only one problem remaining.<br /> How to decide on the best distribution between tower2 and 3 (in the example it was 3:2 and not 4:1), that is x was 3 and y was 2 how to find x and y ?<br /><br />Here too we could use recursion! <br /><br /><br /><br /><i>Following recursive algorithm and the program is something I have come up with and haven't seen in anywhere else yet. If any of you find a similar algorithm or a better one to solve this puzzle please inform me by putting a comment here with your finding. The code for this will appear in the next post</i><br /><br /><br />We need some notations here to make things clearer :<br />Let T4(n) = 'steps to make a tower of height n using 4 towers'<br />Let T3(n) = 'steps to make a tower of height n using 3 towers' <br /><br />Then we can express the steps needed for above 6 steps in this form :<br /><b>T4(n) = 2*(T4(x)+T3(y)) +1</b><br /><br />For instance, T4(6) = 2* (T4(3)+T3(2)) + 1 <br /><br />but we know <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part4.html">T3(m) is 2<sup>m</sup>-1</a>, hence T3(2) above is 2<sup>2</sup>-1 = 3<br />So, <b>T4(6) = 2*T4(3)+7</b><br /><br /><br /><br /><br />To build a tower of height 1, we need just 1 step.<br /><br />According to above algorithm (steps 1 to 6 given above), building a tower of 2 will need 3 steps, since n=2, x=1 and y=0 in this case. (you can work out how we arrived at number 3 as home work!)<br /><br />Now that we know steps needed to build a tower of 1 and a tower of 2, can we find the steps needed to create a tower of 3 ?<br /><br />We have 2 choices<br />n =3, x=1,y=1 and<br />n=3, x=2, y=0<br /><br />In the first case, steps needed will be 5. (home work for readers) In the second, it will be 7! (more home work) So we go with option 1. That means T4(3) =5 !!<br /><br />Now we could revisit the problem of T4(6).<br />Earlier we found <b>T4(6) = 2 * T4(3) + 7</b><br />then T4(6) = 2*5 + 7 = 17 Which is exactly the number of steps our program has taken to solve!<br /><br />So we could recursively find best <b>x</b> and <b>y</b> for any <b>n</b><br /><br />All we need now is to write the nice recursive code. We will give the readers few days to come up with that code before unraveling it in our last post of Towers Hanoi series.<br /><br />After that we will move to a new game and a new problem !<br /><br />Your feedback on the Hanoi Towers series so far will be greatly welcome!Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-5080306838028252222011-04-19T07:56:00.000-07:002011-04-19T07:56:29.391-07:00Arrival of the Java Killer ?<div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/-fJEhBj4rAf8/Ta2iSGkpjUI/AAAAAAAAAH0/lrurRw59FQs/s1600/tea.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-fJEhBj4rAf8/Ta2iSGkpjUI/AAAAAAAAAH0/lrurRw59FQs/s1600/tea.jpg" /></a></div><br />The remarkable news of the impending arrival of the new programming language which is already tipped to be the Java Killer is just out.<br /><br />I had a entire post covering this in araaya blog. What's more the new language is named as Ceylon !! Find out the reasons behing that naming and a pragmatic forcast of things in <a href="http://araaya.blogspot.com/2011/04/ceylon-new-programming-language-to-take.html">here</a>. <br /><br /><span class="Apple-style-span" style="border-collapse: separate; color: black; font-family: 'Times New Roman'; font-size: small; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px;"><span class="Apple-style-span" style="color: #222222; font-family: Arial,Tahoma,Helvetica,FreeSans,sans-serif; font-size: 13px; line-height: 18px;">(Image source http:/www.decidetostayfit.com)</span></span>Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-34842282474531433062011-04-14T02:53:00.000-07:002011-04-18T23:27:11.867-07:00Towers of Hanoi - part 8In the <a href="http://iq-games.blogspot.com/2011/03/bringing-down-towers-of-hanoi-part7.html">earlier post</a>, we learned that still, (surprisingly) there is no mathematical formula for the minimum number of steps needed to solve a Tower of Hanoi puzzle where there can be towers more than 3 and any number of rings. That is no formula exists which gives the number of steps as a function of rings and towers.<br /><br />In this post, we will do away with mathematical aspects of this puzzle and focus on what we know better. Yea, the algorithm!<br /><br />Suppose we have 10 rings (all in the 1st tower) there are 4 towers and you want to move all to the 4th tower.<br /><br />1) We have to place first 9 rings in the 2 middle towers (tower2 and tower3).<br />2) Move the 10th towers from tower 1 to tower 4<br />3) build a tower of 9 in tower4 by using the rings in 2 middle towers.<br /><br />This will lead to a recursive algorithm. Trick is to get the step 1 above right, how best to distribute the first 9 rings among two middle towers ?<br /><br />What I did was to write a separate method to determine just that! In that method I will calculate steps needed achieve to each of different distribution of 9 rings. Distributions goes like this :<br />tower2 have first 8 rings, tower 3 have the ring 9 Or <br />tower2 have first 6 rings, tower 3 has 7 to 9<br />tower2 have first 5, tower 3 has 6 to 9<br />and so on....<br /><br />So my method will calculate steps needed to create each of that distribution and then find the distribution which will need the least number of steps to create. Once we know that, we just call our recursion function to build towers. For instance, if the best configuration is 1-6 in tower2 and 7-9 in tower3, our recursive function will look like this.<br /><br /><b>buildtower4(tower1,tower2,tower3,tower4,6)</b> // use all 4 towers and build a tower of 1-6 in tower2)<br /><b>buildtower3(tower1,tower4,tower3,9,7) </b>// use only the give 3 towers and create a tower with rings 9 to 7 in the third tower)<br /><b>moveRing(tower1, 10, tower4)</b> // ok, we created the optimal distribution of first 9 rings, now move the 10th ring to final destination)<br /><b>buildTower3(tower3,tower1,tower4,9,7)</b> // build a tower of 9-7 in tower4. don't touch tower2)<br /><b>buildTower4(tower1,tower4,tower2,tower3,6)</b> // use all 4 towers and build a tower of 1-6 on top of tower4 <br /><br />Implement something like that in any language and you will have a working code which solves the 4 tower puzzle!<br /><br />Now, 3 challenges from today's post :<br />1) Write the algorithm to determine the optimal combination to distribute N rings in the two middle towers.<br />2) Implement that algorithm in code.<br />3) implement the given algorithm today to solve the 4 tower puzzle once and for all!<br /><br />In the next post we will see few sample outputs from my code... and few screen shots to ram in what we discussed today, for those who have already got the message from today's post, good luck with the code!<br /><br /><br />See you soon.....Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-24418981133974965752011-03-08T02:25:00.000-08:002011-03-08T22:34:02.592-08:00Bringing Down Towers of Hanoi - part7In last post, we planned to discuss more about the problem of multi towers in hanoi and give some hints on the algorithm.<br /><br />Interestingly, for multiple towers, no one has still come up with a general formula to express the number of steps as a function of number of towers and number of rings. Some general cases have been figured out though. For instance, we don't need to be mathematicians to say whats the number of steps would be for a problem with more towers than there are rings. Say, 11 towers and only 10 rings! what would be the number of steps to solve this ?<br /><br />Of course, it would take 9 steps to remove top 9 rings into 9 different towers. Then 10 steps to put all rings in the target tower. 19 steps in all. In other words, 2n-1 ! However, people have found that coming up with a general formula when the number of rings are greater than number of towers (which is greater than 3) is little bit harder than that.<br /><br />In an earlier post we have seen it takes exactly 2n-1 to solve the 3 tower case (worse case) for n rings.<br /><br />We have just saw that it takes 2n-1 to solve the m tower case for n rings where m > n (best case)<br /><br />What happens when m =n, Here is my result. I will intentionally leave out the explanations so you can arrive at that independently.<br /><br />When <span style="font-weight: bold;">m = n</span>, it takes (n-1) + 1 + (n-2) + 3 = <span style="font-weight: bold;">2n+1</span> steps to solve the puzzle!<br /><br />Similarly, when <span style="font-weight: bold;">m = n-1</span>, it becomes <span style="font-weight: bold;">2n+3</span><br /><br />It appears like we could express number of steps as (2n-1) + 2*(n-(m+1)) = 4n - 2m + 1<br /><br />However, these are true only when number of towers are closer to number of rings. When number of towers become less compared to number of rigs, it get complicated. Say, 10 rings in 4 towers. However, solving such a puzzle manually is much easier (in terms of number of steps needed) than solving a similar number of rings with 3 towers. Problem is when we try to find the optimal strategy.<br /><br />I could display few graphical outputs from the program I currently have but before that, wouldn't you want to give it a try yourself ? Remember, number of steps needed is drastically reduced now. We will still need a recursive solution as the nature of the problem commands....Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-51479935861734722082011-02-27T21:09:00.000-08:002011-03-09T21:35:36.468-08:00Bringing Down Towers of Hanoi - part6Today, we are going to see the magic code which solves Towers of Hanoi <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part-4.html">General Problem</a>. Those who still (bravely) want to give it an own try before looking at the code. Can go through these <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part-5.html">hints</a> and do so.<br /><br />Before going to the code, I have something else to show you. This mathematical proof I found from web, which basically gives a formula for the average number of steps for the general case.<br /><br /><img style="width: 510px; height: 53px;" class="tex" alt=" \frac{466}{885}\cdot 2^n - \frac{1}{3} - \frac{3}{5}\cdot \left(\frac{1}{3}\right)^n + \left(\frac{12}{29} + \frac{18}{1003}\sqrt{17}\right)\left(\frac{5+\sqrt{17}}{18}\right)^n + \left(\frac{12}{29} - \frac{18}{1003}\sqrt{17}\right)\left(\frac{5-\sqrt{17}}{18}\right)^n" src="http://upload.wikimedia.org/math/2/2/9/2292b95c032dfba111ab01b9849dcbf8.png" /><br /><br />wow, that's some formula for you!<br /><br />Anyway, as you can see, the code below is the simplicity itself! The solution we propose is bounded by 2n-1, and never exceeds that, also when we present a half done problem, it actually solves it optimally. When you look at the code you get the intuitive feeling that this has to be the optimal solution, wish we could device a mathematical proof too for that fact!<br /><br />private static void buildTower(int height, ArrayList<integer> source,<br /> ArrayList<integer> target, ArrayList<integer> middle) {<br /> if (height < 0) {<br /> return;<br /> }<br /><br /><span style="font-weight: bold;"> if (target.contains(Integer.valueOf(height))) {</span><br /><span style="font-weight: bold;"> buildTower(height -1, source, target, middle);</span><br /><span style="font-weight: bold;"> } else {</span><br /><span style="font-weight: bold;"> if (middle.contains(Integer.valueOf(height))) {</span><br /><span style="font-weight: bold;"> ArrayList<integer> temp = middle;</integer></span><br /><span style="font-weight: bold;"> middle = source;</span><br /><span style="font-weight: bold;"> source = temp;</span><br /><span style="font-weight: bold;"> }</span><br /> buildTower(height-1, source, middle, target);<br /> move(source, target);<br /> print();<br /> buildTower(height-1, middle, target, source);<br /> }<br />}<br /><br />Bolded are the lines we added to the <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part-3.html">last solution.</a> (specific case where all rings are in first tower at the beginning.) Now, isn't this simple ?<br /><br />One more thing : I havn't yet seen this code (or the algorithm) anywhere in the internet. If some one come across this in anywhere else, please post a comment with the link.<br /><br />In next post, we will discuss few hints on how to solve the 4 tower case.<br /><br />Have a nice day!</integer></integer></integer>Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-26141770015863666562011-02-26T04:27:00.000-08:002011-02-26T05:09:20.947-08:00Bringing Down Towers of Hanoi - part 5In the <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part4.html">last post</a>, I promised you to give more hints on how to solve (find the algorithm that is) general case of towers of Hanoi. Those who are new to this Hanoi business, can get up to date from earlier parts of the series.<br /><br /><a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part1.html">part1</a><br /><a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part2.html">part2</a><br /><a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part3.html">part3</a> <br /><br />Let's consider the following scenario we have a tower of height 5, instead of having all stacked up neatly in the 1st tower, we have the largest ring already in tower3.<br /><br /><br /><br /><br /><br /><br />Here's what a run of my code produced.<br /><br />Step 0 -> 3,2,1,0, : : 4,<br /><br />Step 1 -> 3,2,1, : 0, : 4,<br />Step 2 -> 3,2, : 0, : 4,1,<br />Step 3 -> 3,2, : : 4,1,0,<br />Step 4 -> 3, : 2, : 4,1,0,<br />Step 5 -> 3,0, : 2, : 4,1,<br />Step 6 -> 3,0, : 2,1, : 4,<br />Step 7 -> 3, : 2,1,0, : 4,<br />Step 8 -> : 2,1,0, : 4,3,<br />Step 9 -> : 2,1, : 4,3,0,<br />Step 10 -> 1, : 2, : 4,3,0,<br />Step 11 -> 1,0, : 2, : 4,3,<br />Step 12 -> 1,0, : : 4,3,2,<br />Step 13 -> 1, : 0, : 4,3,2,<br />Step 14 -> : 0, : 4,3,2,1,<br />Step 15 -> : : 4,3,2,1,0,<br /><br />wow! it found the biggest ring is already in where it wanted to be so finished off with the optimal solution. How do we know that was the optimal ? well, because it took exactly 15 steps, which isthe expected to solve a tower with height 4. Since 5th tile is already there for us, it is like solving a tower of height 4!<br /><br />Now, then, let's make it little difficult for the computer and see. we pit the biggest ring in the MIDDLE tower at start and let's see what will happen.<br /><br /><br /><br /><br /><br /><br />Step 0 -> 3,2,1,0, : 4, :<br /><br />Step 1 -> 3,2,1,0, : : 4,<br />Step 2 -> 3,2,1, : 0, : 4,<br />Step 3 -> 3,2, : 0, : 4,1,<br />Step 4 -> 3,2, : : 4,1,0,<br />Step 5 -> 3, : 2, : 4,1,0,<br />Step 6 -> 3,0, : 2, : 4,1,<br />Step 7 -> 3,0, : 2,1, : 4,<br />Step 8 -> 3, : 2,1,0, : 4,<br />Step 9 -> : 2,1,0, : 4,3,<br />Step 10 -> : 2,1, : 4,3,0,<br />Step 11 -> 1, : 2, : 4,3,0,<br />Step 12 -> 1,0, : 2, : 4,3,<br />Step 13 -> 1,0, : : 4,3,2,<br />Step 14 -> 1, : 0, : 4,3,2,<br />Step 15 -> : 0, : 4,3,2,1,<br />Step 16 -> : : 4,3,2,1,0,<br /><br />aha! not so difficult again. Code was smart enough to know it should just move the biggest ring to the 3rd tower and it was exactly as the earlier problem.<br /><br />What if we make things seriously wrong and ask it to solve ? In the normal solution path, after first 3 moves, we should be having the two smallest rings stacked in the middle tower. Let's put them on tower 3 and see.<br /><br /><br /><br /><br /><br /><br />Step 0 -> 4,3,2, : : 1,0,<br /><br />Step 1 -> 4,3,2,0, : : 1,<br />Step 2 -> 4,3,2,0, : 1, :<br />Step 3 -> 4,3,2, : 1,0, :<br />Step 4 -> 4,3, : 1,0, : 2,<br />Step 5 -> 4,3,0, : 1, : 2,<br />Step 6 -> 4,3,0, : : 2,1,<br />Step 7 -> 4,3, : : 2,1,0,<br />Step 8 -> 4, : 3, : 2,1,0,<br />Step 9 -> 4, : 3,0, : 2,1,<br />Step 10 -> 4,1, : 3,0, : 2,<br />Step 11 -> 4,1,0, : 3, : 2,<br />Step 12 -> 4,1,0, : 3,2, :<br />Step 13 -> 4,1, : 3,2, : 0,<br />Step 14 -> 4, : 3,2,1, : 0,<br />Step 15 -> 4, : 3,2,1,0, :<br />Step 16 -> : 3,2,1,0, : 4,<br />Step 17 -> 0, : 3,2,1, : 4,<br />Step 18 -> 0, : 3,2, : 4,1,<br />Step 19 -> : 3,2, : 4,1,0,<br />Step 20 -> 2, : 3, : 4,1,0,<br />Step 21 -> 2, : 3,0, : 4,1,<br />Step 22 -> 2,1, : 3,0, : 4,<br />Step 23 -> 2,1,0, : 3, : 4,<br />Step 24 -> 2,1,0, : : 4,3,<br />Step 25 -> 2,1, : : 4,3,0,<br />Step 26 -> 2, : 1, : 4,3,0,<br />Step 27 -> 2, : 1,0, : 4,3,<br />Step 28 -> : 1,0, : 4,3,2,<br />Step 29 -> 0, : 1, : 4,3,2,<br />Step 30 -> 0, : : 4,3,2,1,<br />Step 31 -> : : 4,3,2,1,0,<br /><br />great! it didn't exceed 31 steps.<br /><br />Now, can you come up with the code to produce this ? give it a try.... I have a one last hint. Solving is not so difficult. it will only add just few extra lines to the earlier code we have discussed.<br /><br />Meanwhile, for those who have already come up with the code (but shy to post it to us on comments), we have the next stage of the challenge!<br /><br />What about 4 Towers ? Solving this is easy when we do it manually and takes lesser number of steps. How about coming up with an algorithm to do that ?<br /><br />This is a very interesting challenge to contemplate on......Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-45062631116923270172011-02-23T02:13:00.000-08:002011-03-08T04:07:16.764-08:00Bringing Down Towers of Hanoi - part4<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-Y8bDebNJ_eY/TXYbkzr2n_I/AAAAAAAAACY/I-mlB4lqDf0/s1600/300px-Tower_of_Hanoi.jpeg"><img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 300px; height: 132px;" src="http://2.bp.blogspot.com/-Y8bDebNJ_eY/TXYbkzr2n_I/AAAAAAAAACY/I-mlB4lqDf0/s320/300px-Tower_of_Hanoi.jpeg" alt="" id="BLOGGER_PHOTO_ID_5581679107335692274" border="0" /></a><br /><div>In <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part3.html">last post</a>, we wondered what on earth the number 2<sup>n-1 </sup>doing (regardless of how many N rings we used!) in our little towers problem, for all the values of N. </div><div><sup></sup></div><div><br /></div>We need to look at the recursion little deep to answer that question. As discussed earlier, solving N rings is exactly equal to do the following :<div><br />1) make a tower N-1 on the transit tower<br />2) move ring N from source to the final destination<br />3) make a tower N-1 on final destination<br /><br />That involved 2 towers with height N-1 and moving of one ring. Similarly making a tower of N-1 will be equal to making 2 towers of N-2 and moving a ring. if we expand this for 3 ring case:<br /><br /><span style="font-weight: bold;">tower of 3</span> = 2 * (<span style="font-weight: bold;">tower of 2</span>) + 1 = 2 * (2*(<span style="font-weight: bold;">tower of 1</span>) +1) + 1 = 2 * (2*(<span style="font-weight: bold;">1</span>) +1) + 1 =<span style="font-weight: bold;"> 7 </span>= <span style="font-weight: bold;">2</span><sup style="font-weight: bold;">3</sup><span style="font-weight: bold;"> - 1 </span><br />(since making a tower of 1 always takes one move)<br /><br />so, making a <span style="font-weight: bold;">tower of 3</span> involved making 2 <span style="font-weight: bold;">towers of 2</span> and 1 move.<br />that is, 4 <span style="font-weight: bold;">towers of 1</span> and 2 + 1 moves.<br />that is, 2<sup>(3-1)</sup> <span style="font-weight: bold;">towers of 1</span> and 2<sup>1</sup> + 2<sup>0</sup> moves. (making a <span style="font-weight: bold;">tower of 1 </span>takes just 1 move) <integer><integer><integer></integer></integer></integer><br />that is, 2<sup>n-1</sup> + (2<sup>n-2 + </sup>2<sup>n-3</sup> + 2<sup>n-4</sup> + ... + 2<sup>0)<br /><br /></sup>Total Steps = 2<sup>n-1</sup> + (2<sup>n-2 + </sup>2<sup>n-3</sup> + 2<sup>n-4</sup> + ... + 1)<br /><sup><br /></sup>but the sum of sequence (2<sup>n-2 + </sup>2<sup>n-3</sup> + 2<sup>n-4</sup> + ... + 1) = 2<sup>n-1 </sup>- 1<br /><br />Hence total steps = 2<sup>n-1 </sup>+ 2<sup>n-1 </sup>- 1 = 2 * (2<sup>n-1 </sup>) - 1 = <span style="font-weight: bold;">2</span><sup style="font-weight: bold;">n</sup>-1 !!<br /><br />Wow, now we know why it has to be <span style="font-weight: bold;">2</span><sup style="font-weight: bold;">n</sup>-1 always !!<br /></div><div><br /></div><div>Our series is only just starting to get interesting! Now to the today's challenge :</div><div><br /></div><div>We can now write a nice recursive function to solve the puzzle. However, what we are solving is actually a subset of the problem. We have so far considered cases where all the rings are in tower 1. How about we removing that restriction, how about letting the rings to be anywhere on 3 towers (as long as a bigger ring is not upon a smaller). Can we come up with the code to resolve that ?</div><div><br /></div><div>In fact, this can be considered as the general case in Towers of Hanoi. What we have discussed in earlier posts was just a specific subset of it. In the next post, we will come with few more hits on how to approach that.</div><div><br /></div><div>Meanwhile, try it out yoursef! </div>Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-19518217816952803952011-02-22T20:29:00.000-08:002011-02-23T22:05:00.839-08:00Bringing Down Towers of Hanoi - part3Today, we will see the code to solve Towers of Hanoi. A simple recursive function which does following... (If we have 10 rings, N would be 10)<br /><br />1) build a tower of height N-1 on tower2 (from tower1)<br />2) move the ring N from tower1 into tower3<br />3) build a tower of height N-1 (again) but this time on top of tower3 (from tower2)<br /><br />but we have to do it recursive for N-1 (that is 9) too then also for 8 etc .. For those who are new to the series or like to give another attempt to write the code on their own, you can visit <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part1.html">here</a> and <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part2.html">here</a> for details and motivation.<br /><br />The Complete Java code can be found at the end of this post. (it would be straightforward to write this in any other language)<integer><integer><integer><span><span> You can run it passing the number of rings as a parameter for the main method. ie : <span style="font-weight: bold; font-style: italic;">java HanoiTowers 5</span> and it will display the proceedings in a text base command line display.</span><span><br /><br /></span><span>This is the output I got for 5 rings :<br />Step 0 -> 4,3,2,1,0, : :<br />Step 1 -> 4,3,2,1, : : 0,<br />Step 2 -> 4,3,2, : 1, : 0,<br />Step 3 -> 4,3,2, : 1,0, :<br />Step 4 -> 4,3, : 1,0, : 2,<br />Step 5 -> 4,3,0, : 1, : 2,<br />Step 6 -> 4,3,0, : : 2,1,<br />Step 7 -> 4,3, : : 2,1,0,<br />Step 8 -> 4, : 3, : 2,1,0,<br />Step 9 -> 4, : 3,0, : 2,1,<br />Step 10 -> 4,1, : 3,0, : 2,<br />Step 11 -> 4,1,0, : 3, : 2,<br />Step 12 -> 4,1,0, : 3,2, :<br />Step 13 -> 4,1, : 3,2, : 0,<br />Step 14 -> 4, : 3,2,1, : 0,<br />Step 15 -> 4, : 3,2,1,0, :<br />Step 16 -> : 3,2,1,0, : 4,<br />Step 17 -> 0, : 3,2,1, : 4,<br />Step 18 -> 0, : 3,2, : 4,1,<br />Step 19 -> : 3,2, : 4,1,0,<br />Step 20 -> 2, : 3, : 4,1,0,<br />Step 21 -> 2, : 3,0, : 4,1,<br />Step 22 -> 2,1, : 3,0, : 4,<br />Step 23 -> 2,1,0, : 3, : 4,<br />Step 24 -> 2,1,0, : : 4,3,<br />Step 25 -> 2,1, : : 4,3,0,<br />Step 26 -> 2, : 1, : 4,3,0,<br />Step 27 -> 2, : 1,0, : 4,3,<br />Step 28 -> : 1,0, : 4,3,2,<br />Step 29 -> 0, : 1, : 4,3,2,<br />Step 30 -> 0, : : 4,3,2,1,<br />Step 31 -> : : 4,3,2,1,0,</span></span><span style="font-style: italic;"><span style="font-style: italic;"><br /><br /></span></span><span><span>Step 0 above was the starting state of 3 towers (separated by ":" s). To solve the entire problem, it took only 4 lines of code! </span></span><span style="font-style: italic;"><span><br /><br /></span></span></integer></integer></integer><span style="font-style: italic;">private void buildTower(int height, ArrayList</span><integer><span style="font-style: italic;"> source, ArrayList</span><integer><span style="font-style: italic;"> target, ArrayList</span><integer><span style="font-style: italic;"> middle) {</span><br /><span style="font-style: italic;"> if (height < 0) return;</span></integer></integer></integer><span style="font-style: italic;"><span style="font-style: italic;"><br /></span></span><span style="font-style: italic;"><span style="font-style: italic;"> </span></span><span style="font-style: italic;"><span style="font-style: italic;">buildTower(height-1, source, middle, target);</span><br /></span><span style="font-style: italic;"><span style="font-style: italic;"> </span></span><span style="font-style: italic;"><span style="font-style: italic;"> </span></span><span style="font-style: italic;"><span style="font-style: italic;">move(source, target); // just moves the top ring from source into top of target</span><br /><span style="font-style: italic;"> </span></span><span style="font-style: italic;"><span style="font-style: italic;"> </span></span><span style="font-style: italic;"><span style="font-style: italic;"> </span></span><span style="font-style: italic;"><span style="font-style: italic;">buildTower(height-1, middle, target, source);</span><br /><span style="font-style: italic;">}<br /><br /></span></span><span><span>That was all which took for solving the whole puzzle, Now, that's the power of recursion!</span></span><span style="font-style: italic;"><span style="font-style: italic;"><br /></span></span><br /><integer><integer><integer><span><span>Now to the second part of the challenge : </span></span><span><span> The puzzle above took exactly 31 moves. Similarly you would see puzzle with 10 will take 1023. 4 rings will take 15. N rings will take exactly </span></span></integer></integer></integer><span style="font-weight: bold;">2</span><sup style="font-weight: bold;">n</sup><span style="font-weight: bold;"> - 1</span> steps.<br /><br />How did that happen ? can we explain how on earth the value 2<sup>n</sup> - 1 comes in for all values of N ? what is the significance of 2 there ? Try to figure it out, we will discuss the explanation in the next post.<br /><br />Meanwhile...<div><br />Following is the complete Java code for today's post. Enjoy!<br /><br /><br /><div><pre><br />package com.araaya.hanoitowers;</pre></div><div>import java.util.ArrayList;</div><div><br /></div><div>/**</div><div> *@author Ashoka Ekanayaka</div><div> * www.it-front.net, www.araaya.com</div><div> */</div><div>public class HanoiTowers {</div><div> static ArrayList<integer> source1, target1, middle1;</integer></div><div> static int steps = -1;</div><div><br /></div><div> public static void main(String[] args) {</div><div> int height = Integer.parseInt(args[0]);</div><div> source1 = new ArrayList<integer>(height);</integer></div><div> target1 = new ArrayList<integer>(height);</integer></div><div> middle1 = new ArrayList<integer>(height);</integer></div><div> for (int i=height-1; i >= 0; i--) {</div><div> source1.add(i);</div><div> }</div><div> print();</div><div> buildTower(height-1, source1, target1, middle1);</div><div> }</div><div><br /></div><div> private static void buildTower(int height, ArrayList<integer> source,</integer> ArrayList<integer> target,<br /> ArrayList<integer> middle) {</integer></integer></div><div> if (height < 0) return;<br /><span style="font-style: italic;"><span style="font-style: italic;"> </span></span>buildTower(height-1, source, middle, target);</div><div> move(source, target);</div><div> <span style="font-style: italic;"><span style="font-style: italic;"> </span></span>print();</div><div> <span style="font-style: italic;"><span style="font-style: italic;"> </span></span>buildTower(height-1, middle, target, source);</div><div> }</div><div><br /></div><div> private static void print() {</div><div> steps++;</div><div> System.out.print("Step " + steps + " -> ");</div><div><br /></div><div> for (Integer i : source1) {</div><div> System.out.print(i+",");</div><div> }</div><div> System.out.print(" : ");</div><div><br /></div><div> for (Integer i : middle1) {</div><div> System.out.print(i+",");</div><div> }</div><div> System.out.print(" : ");</div><div><br /></div><div> for (Integer i : target1) {</div><div> System.out.print(i+",");</div><div> }</div><div> System.out.println();</div><div> }</div><div><br /></div><div> private static void move(ArrayList<integer> source, ArrayList<integer> target) {</integer></integer></div><div> <span style="font-style: italic;"><span style="font-style: italic;"> </span></span>target.add(source.get(source.size()-1)); // move top element in source to top of target</div><div> <span style="font-style: italic;"><span style="font-style: italic;"> </span></span>source.remove(source.size()-1);</div><div> }</div><div><br />}<br /><br /></div><div><br /></div></div>Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-4814219742509535472011-02-22T02:24:00.000-08:002011-02-22T20:32:48.568-08:00Bringing Down Towers of Hanoi - part2Ok, Here we would discuss the solution and the code to implement it for our little tower puzzle. Those who are new to the series or those who like to give one last try at the puzzle before looking at the answer. Can do so by going back to <a href="http://iq-games.blogspot.com/2011/02/bringing-down-towers-of-hanoi-part1.html">part1</a>.<br /><br />Let's imagine we have a simple tower of 5 rings.<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-DU4nk0vemvM/TWSJByeiP1I/AAAAAAAAABw/ZlL6R-Q3GDI/s1600/1.jpg"><img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 320px; height: 149px;" src="http://4.bp.blogspot.com/-DU4nk0vemvM/TWSJByeiP1I/AAAAAAAAABw/ZlL6R-Q3GDI/s320/1.jpg" alt="" id="BLOGGER_PHOTO_ID_5576732902414237522" border="0" /></a>To move the rings in first tower to 3rd tower, we need to move the larger ring to 3rd tower first since we can not place it above any other rings. (remember the rule : there can never be a larger ring on top of a smaller one) However, to move the largest ring from tower 1, we need to move all the other out of it first so that we can lift it. At the same time we have to keep the tower1 empty so that we can put the largest ring there. That means we need to have this position.<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-asTZo5eMQVo/TWSJXLLp2CI/AAAAAAAAAB4/2L4sMfOgiWg/s1600/2.jpg"><img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 320px; height: 149px;" src="http://4.bp.blogspot.com/-asTZo5eMQVo/TWSJXLLp2CI/AAAAAAAAAB4/2L4sMfOgiWg/s320/2.jpg" alt="" id="BLOGGER_PHOTO_ID_5576733269823182882" border="0" /></a>Aha! now we can move the largest ring to tower3, then we will have to build a tower from 1-4 on top of tower 3 to complete the puzzle.<br /><br />In other words, to build a tower of height N on tower3 (from tower1), we need to :<br /><br />1) build a tower of height N-1 on tower2 (from tower1)<br />2) move the ring N from tower1 into tower3<br />3) build a tower of height N-1 (again) but this time on top of tower3 (from tower2)<br /><br />Let's go back to the diagram where we have cleared tower1 to lift the largest ring (5th ring) :<br />To lift that, we had to create a tower of 1-4 on tower2, but to do that we need to move the ring 4 into tower2, this means we need to remove rings 1-3 from tower 1 first so that we can move ring4 into the middle one...<br /><br /> <a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-do9YrRFDCI0/TWSJXchoYKI/AAAAAAAAACA/3hwUm7oWSmI/s1600/3.jpg"><img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 320px; height: 149px;" src="http://4.bp.blogspot.com/-do9YrRFDCI0/TWSJXchoYKI/AAAAAAAAACA/3hwUm7oWSmI/s320/3.jpg" alt="" id="BLOGGER_PHOTO_ID_5576733274478764194" border="0" /></a><br />Hmm, so we needed to build a tower 1-3 on tower3 in order to move 4 into tower2! (in order to move ring 5 to the ultimate goal, tower3) Similarly, we would first have to build a tower 1-2 on tower2 to move the ring3 to tower3. To do that, we need to move 1 into tower3 so that we can move 2 into tower 2. So our first move should be :<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-0Z16I3e4VgA/TWSJXW0DacI/AAAAAAAAACI/5vCdfceF200/s1600/4.jpg"><img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 320px; height: 149px;" src="http://3.bp.blogspot.com/-0Z16I3e4VgA/TWSJXW0DacI/AAAAAAAAACI/5vCdfceF200/s320/4.jpg" alt="" id="BLOGGER_PHOTO_ID_5576733272945420738" border="0" /></a><br />Thus, moving the smallest ring to tower2 as the first move will be wrong! ring1 has to be on tower 3 because : (hold your breadth now, see whether you can follow this in your head till the end)<br /><br />We needed to move 2 into tower2 (to build 1-2 on tower2), that was because<br />We needed to move 3 into tower3 (to build 1-3 on tower3), that was because<br />We needed to move 4 into tower2 (to build 1-4 on tower2), that was because<br />We needed to move 5 into tower3 (to build1-5 on tower3), that was because<br />It was the end goal of the puzzle!<br /><br />Simple isn't it ? Solving the case of 10 rings would have the exact same logic. There we will have to move ring 1 into tower2 as our first move. (follow the same logic in your mind for 10 steps and you will see why)<br /><br />Now to the code. Earlier we deduced that,<br /><br />Building a tower of height N on tower3 (from tower1), is as same as saying :<br />1) build a tower of height N-1 on tower2 (from tower1)<br />2) move the ring N from tower1 into tower3<br />3) build a tower of height N-1 (again) but this time on top of tower3 (from tower2)<br /><br />that included building a tower of N-1 on tower2, but in the same logic, we can define building a tower of N-1 as :<br />1) build a tower of height N-2 on tower3 (from tower1)<br />2) move the ring N-1 from tower1 into tower2<br />3) build a tower of height N-2 (again) but this time on top of tower2 (from tower3)<br /><br />and so on until we build a tower of 1. Now, can write the small little recursive function to solve the entire puzzle?<br /><br />Hint : it has only 3 lines.<br /><br />In the next post, we will see the code and we will also investigate why that it always take 2<sup>n</sup> - 1 steps to solve a Tower of Hanoi problem with N rings.<br /><br />Challenge 1 : write the code to solve Towers of Hanoi puzzle for a given N.<br /><br />Challenge 2 : in the above solving algorithm, prove that it always takes exactly 2<sup>n</sup> - 1 steps to solve the puzzle.Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-45274534786397963172011-02-22T00:55:00.000-08:002011-03-08T04:07:07.131-08:00Bringing Down Towers of Hanoi - part1<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://upload.wikimedia.org/wikipedia/commons/6/60/Tower_of_Hanoi_4.gif"><img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 320px; height: 125px;" src="http://upload.wikimedia.org/wikipedia/commons/6/60/Tower_of_Hanoi_4.gif" alt="" border="0" /></a><br />Hope this post will not bring as much destruction as it's title suggests. In fact, we are not interested in bringing down any single tower in Hanoi, not even in any where else for that matter. What we would be doing is to <span style="font-style: italic;">brining down the problem of Towers of Hanoi into the levels we can understand it</span>. Of course, if that was the title, we wouldn't probably be in here reading this right now would we ?<br /><br />Towers of Hanoi is a popular puzzle, first introduced by the French mathematician <a style="color: rgb(0, 0, 0);" href="http://en.wikipedia.org/wiki/%C3%89douard_Lucas">Ă‰douard Lucas</a> in 1883. (However, some do maintain that the puzzle is much older than that) Those who are not familiar with the puzzle can learn all about it from <a href="http://en.wikipedia.org/wiki/Tower_of_Hanoi">here</a>. There is a particular interest on this puzzle by the hacker (programmer, developer, coder) community mainly due to the fact that it has been taught in many 1st year CS courses throughout the world. The puzzle is a great example to demonstrate the power of recursion.<br /><br />However, Towers of Hanoi is a deep enough problem that one can do it for a PhD. It could go many levels in depth and complexity. The most simplest version, I guess most of our readers have already studied in first year. Let's approach the problem step by step. If you are not a programmer and/or haven't done this problem before consider yourself lucky! you got an opportunity to have a fresh look at a very interesting problem and reap all the satisfaction of finding the solution on your own! Oh boy, this series gonna be a bit longer one....<br /><br />Ready to jump in ? Ok, let's bring them down then!<br /><br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-P0-51a4VPb4/TWONIP3SkPI/AAAAAAAAABo/OP1hg4TZNME/s1600/300px-Tower_of_Hanoi.jpeg"><img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 300px; height: 132px;" src="http://4.bp.blogspot.com/-P0-51a4VPb4/TWONIP3SkPI/AAAAAAAAABo/OP1hg4TZNME/s320/300px-Tower_of_Hanoi.jpeg" alt="" id="BLOGGER_PHOTO_ID_5576455936451711218" border="0" /></a><br />Problem is to move all the rings from first tower into the third tower, one buy one. Here's the catch : you can not ever put a bigger ring on top of a smaller ring. That's why you have been provided with a middle tower, to transit.<br /><br />Can you solve this your self ? of course you can. (animation at top of the page) All it need is some patience...<br /><br />Now can we design a computer program to solve this. let's give it a try ....<br /><br />Hint :<br />1) Solve it by hand for fewer number of rings and think recursively.<br />2) Consider three towers as three arrays. One has digits 0 to 9 in that order at start. At the end of the program execution, we need to have all digits in the 3rd array in the proper order.<br /><br />We will see the answer to this basic version of the problem in the next article by the form of a peace of small, executable code. Remember, we would be upping the ante a bit in the next article and things would get more and more challenging and fun as we go on.....<br /><br />So, do try it! give it a shot if you haven't already wrote a program to solve this by your self!Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-88145677919846415242011-02-20T19:41:00.000-08:002011-09-24T22:46:59.877-07:00Planet Wars - My First AI Contest (part 2)First <a href="http://iq-games.blogspot.com/2011/02/planet-wars-my-first-ai-contest.html">part</a> of this post described how I missed the actual competition but still managed to have loads of fun and come up with my own bot thanks to nice people who have published their bots and made it possible for me to conduct a local tournament. Those who wondering what the Planet Wars is and what the big deal behind this so called AI competition, you can get up to date with all that from <a href="http://ai-contest.com/">here</a>.<br /><br />In this post, I will mainly discuss the strategies and path I took when designing my bot and the lessons learned.<br /><br />One of main lessons I learned from this experience is that the precious calculations are always way better than heuristic guesses. Sometimes when the problem is complicated, we tend to invent an obvious looking heuristic ("if my planet's ships are greater than enemy planet ships, attack the enemy with 50% of my strength" for instance) even though it may be the easier option, in the long run, investing our time on preciously calculating and picking our choice is always superior. It was particularly interested to note how heuristics disappeared from my algorithm and replaced by calculations as it was evolving.<br /><br />Mainly I had 5 steps in my code :<br />1) Attack : if one or more of my planets can send ships to capture another planet even temporarily, do so. After considering all incoming fleets for the enemy planet, enemy growth over the attacking distance and possible reinforcements enemy can receive from it friends, (if those friends are nearer than my attacking planet that is), if it seems like I can capture the planet, I usually did so. My Planet will not hesitate to even attack with full strength if the enemy planet has a higher growth than itself, Otherwise it will use just the excess ships.<br /><br />2) Defense : if one of my planets has incoming enemy fleets, I would assemble ships from my nearby planets and reinforce the planet which is under threat. Again all the incoming fleets, my own growth over the enemy attacking distance and reinforcements I can find were included in calculations. Nearby planets were given priority when selecting defenders.<br /><br />3) Sniping : If an enemy is moving towards a neutral planet, I would try to reach there just after enemy has landed. That way enemy will do all the hard work of destroying the neutral defenders while I will have to fight only with it's depleted remaining forces.<br /><br />4) Neutral planet hunting : if there are unoccupied planets which are nearer to me than to the enemy and if it is desirable (hear I used a heuristic) to take them, do so.<br /><br />5) reinforcements : far away planets sending their ships to planets which are nearer to enemy planets.<br /><br />Beside above, I tried to maintain a minimum force on planets which are nearby to enemy. Amount of that force was calculated by the attacking strength of the nearest enemy and defensive strength of my planets which were nearer to me than the enemy. Any excess above this limit was used in attacks. In defense, defenders trying their best to send enough ships to defend a planet by using their excess forces only.<br /><br />Some bots were passing there chance on very first turn hoping for sniping chances on their second turn or in fear of being sniped themselves, I guess. I never liked that strategy. In initial moves, I took only the planets which are nearer to me than the enemy. In case of planets which fell in the middle, I chose not to attack them on the very first turn and to leave them for the enemy take, then I tried sniping on 2nd turn. This strategy gave me mixed results. When attacking a neutral planet or when doing a sniping, I did try to calculate the impact of "future planets" on them. That is planets which are not being claimed by either party but very soon will belong to one side. This could be easily deduced by the fleets in motion. Code would explain how this is done. I got few extra rating points after implementing this feature.<br /><br />Another gray area for me was to decide whether I should change my behavior according to the game status. That is, should I attack less when I'm ahead in growth, should I attack more when I'm behind etc. Experiments on those always gave me mixed results. I eventually concluded that attack whenever it can be done with accuracy is best in most situations. This increased my score against stronger bots.<br /><br />Few things I haven't implemented : Ideally the bot should compare advantages and disadvantages between an attack and defense. Should I let my planet fall and try to take that enemy planet etc... If I saw a sure attack I always took it and then tried to defend planets with available ships. It would have been cool to have a comparison though.<br /><br />I gave lowest priority to attacking neutrals at the later stages of the game.<br /><br />my functions to determine what is the minimum force to take an enemy planet and the minimum force required to defend an own planet was the same. It considered all fleets bound towards that planet, growth and reinforcements from friends. However I did not have any game tree and a mechanism to decide what if I do this, he do that and then I do this etc... I thought that sort of a min max tree approach is not so suitable for something like Planet Wars where problem space was huge and we had to come up with a move within a second. However, I have noted others talking about this any apparently getting some good results as well. I never tried that approach. If we are sensibly reinforced, well defended and always on the look for weaknesses of the enemy while being aggressive at the early stages on neutral hunting, I thought that will be good enough to be within first 100. may be I was correct in that, but then again that may also explain why my bot couldn't reach first 60, for instance.<br /><br />One very interesting thing I noted was that even some of the stronger bots were not defending themselves properly at times. For instance, when in the opening where both parties have only one planet each, I managed to take the enemy by directly attacking it while it was busy sending fleets for neutrals. This was an easy check to do and guard against, yet most haven't done it and I scored few quick victories with that.<br /><br />There are lot of finer details I like to discuss but that will grow this post to insane levels. Anyway the shared code should explain lot of things adequately. If anyone has questions/criticisms/suggestions, I would be glad to reply.Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com2tag:blogger.com,1999:blog-1756432593380603974.post-54924105838615978392011-02-20T03:08:00.000-08:002011-09-24T22:47:35.717-07:00Planet Wars - My First AI Contest (part 1)I can't believe I wasted 2 months on this. I can't believe I comprehensively wasted 2 moths on this at all! (those who have red the blog of the winner, <span style="font-weight: bold;">Bocsimacko</span> The Brilliant, will find that phrase little familiar :-) )<br /><br />It was late when I got to know about Google's AI <a href="http://ai-contest.com/">contest</a>. I have missed the first contest as well, I got to know about the second contest, "Planet Wars" just few days before it ended. Considering the competition was running for over 2 months, that didn't give me much chance to compete effectively. To make the matters even worse, I was to find out (foolishness of me, should have checked that out before everything else!) about the submission deadline just a day before it!<br /><br />So I ended ended up hurriedly submitting not even the best code I have written in those few days. And the competition was of course a disaster for my <a href="http://www.ai-contest.com/profile.php?user_id=14058">Bot</a>. May be I should have satisfied with the results (1200 out of 6000 competitors) of what was made in just 4 days, but something else happened during the final competition.....<br /><br />I really began to get carried away by the beauty of the game, and the challenge it offered. I just continued development of my bot hoping that the competition server will keep running even after the official competition so that I could still evaluate my bot by playing it against others. Unfortunately, official server was never started after the actual competition. Can't blame the organizers for that. They have provided a wonderful experience and organized a hugely successful competition. What's more, they have made the server software open source. Few people were already running their own TCP servers where others could compete. However, after the competition, even the players seemed they are tired after a competition which ran for over 2 months, and no one was so keen on playing on TCP servers. Even the servers were not available after few days. At least all my attempts to connect to one was ended in failure.<br /><br />My only remaining option was to download the bots published by others after the competition and play my bot against them in locally arranged tournaments. By this time my bot was improving fast and I was in a hurry to implement all my ideas and see how they would fair up against other bots. So I didn't look into downloaded code as that would influence my thoughts and I wouldn't be able to test my bot in a fair manner. A big big thank for those who published their code. I downloaded the java bots I came across, so my special thanks goes to <span style="font-weight: bold;">GreenTea(ZerlingRush), Smloh, Manwe56, Deccan, Exaide, Eburnette, Ludakris, zvold(krokokrusa), InvaderZim.</span> Without you guys it won't be possible for me to test my bot at all and you helped me to improve myself a lot. Looking forward to compete with you in a real tournament soon.<br /><br />GreenTea was always a tough opponent for my bot, so was Smloh1. At initial stages almost all bots were very difficult to beat. I implemented features one after other, attack first, defense, neutral planet hunting etc and things improved dramatically. specially after proper defense and optimized neutral hunting. As for attacking, less attacking the better it was top bots were very quick to punish incorrect attacks. I thought Ludakris was a better bot than it's rating suggested, specially in close quarter battles. Manwe56 was little slower than other bots for some reason but was stronger than my one in most cases. Exaide has a random behavior as it was getting different results against the same bot on same map! it was a mysterious bot for me in the beginning. I felt I was bit luckier against Mkemp, zvold and eburnette and may be bit unlucky against Deccan whom I couldn't reach on ratings even though individual matches against that bot went close. Smloh1 was slow initially until I had to investigate and eliminate system.outs from the code :-) <br /><br />It took about 2 months before this craziness <a href="http://www.ai-contest.com/forum/viewtopic.php?f=21&t=1168&start=60#p8665">ended</a> and I had enough improving my very first AI bot. If the competitions I locally arranged is to be trusted and ELO tables do a good job in measuring performances and translating them into ratings, then I think I could be somewhat satisfied with my efforts. My final bot performed around 3280, (it got very close ratings in 2 different sets of maps against same opponents, so I guess the performance rating calculation is fairly accurate) which would mean had it managed to compete in the real competition, it may (arguably) have ranked somewhere between 60 - 70. I may have got an advantage since I have few good bots at hand to test my bot against with, but then again in the real tournament preparation, competitors may have had the privilege of playing against others on TCP servers as well as in the live server.<br /><br />I didn't do fine tunings targeting the final tournament maps since my interest in the game dried down after solving the challenge of implementing all my game strategies and getting them to work. Some fine tuning would have helped to snatch up few more rating points... but my main interest was to get the algorithms right.<br /><br />Now that the initial goal is achieved (to build a decent bot on my own), I can now go visit others code and analysis, learn something new and have a laugh at clumsier ways I may have achieved certain things in my code.<br /><br />Source code of the final bot can be found in <a href="https://github.com/ashokae/planet-wars-bot">here</a>. Excel with all tournament statistics and rating calculations along with ELO tables used is also there. I'm planning to explain my code, strategies and lessons learned in a future article if the time permits. Meanwhile, apologies if the code lacks enough comments.<br /><br />All the best for all contestants in the upcoming contest! those who haven't get involved in this fun, do sign up!! trust me, you won't be regretting this. (specially if you like AI programming and/or problem solving in general)<br /><br /><a href="http://iq-games.blogspot.com/2011/02/planet-wars-my-first-ai-contest-part-2.html">Part 2</a>Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0tag:blogger.com,1999:blog-1756432593380603974.post-6748749206022977892011-02-18T22:27:00.000-08:002011-02-22T00:54:53.756-08:00Welcome !!Welcome to our blog!<br /><br />Here we will discuss and analyze the use of artificial intelligence in gaming, Game Theory, IQ enhancing games and puzzles, AI algorithms used in them etc...<br /><br />Creating games for PC and smart phones (iphone, android, windows mobile) is our hobby. We intend to share our experience and passion with our readers.<br /><br />Stay tuned for up coming articles on :<br /><br /><a href="http://ai-contest.com/">Planet Wars</a> (ai contest from Google) and our experience.<br /><br />Towers of Hanoi : this is covered in many 1st year CS courses on AI. Here we intend to go little deeper, one step at a time ..<br /><br />MasterMind : The classic board game.<br /><br />Dual : An addictive yet simple board and puzzle game developed as a new and own concept.<br /><br />15 Puzzle : you know it! most simplest of board games out there. or is it ?<br /><br />and many more.....<br /><br />If you have interesting thoughts, ideas games and algorithms to share, you are welcome to comment in here.Ashoka Ekanayakahttps://plus.google.com/101962849021603505204noreply@blogger.com0