Tuesday, November 1, 2011

Sim City: Hawaii Edition

If you've ever played Sim City, you know how hard it can be to be to make those decisions as mayor to help your tiny town grow into a bustling metropolis. I'm not talking the decisions about which disasters to unleash so you can watch your virtual citizens be engulfed in its destructive glory (try the alien invasion, aliens always tear your city up good). Nay, I am talking about the legitimate decisions of balancing your city's need for utilities, the cost required to maintain them, as well as environmental concerns.

Look at this thing ruining your citizens' day
One of the utilities that your Sim City citizens craved the most (when they weren't getting blasted by alien laser beams) is, of course, electricity. Although the decision in the game was one of simply keeping citizens happy by providing them with electricity while not contaminating their breathing air with pollution, the struggle for keeping a city out of the dark is a much more complex situation in reality. There are other concerns to look out for as well, such as the depletion of non-renewable resources that threatens to spell the end of the era of taking the availability of fuel for our cars or oil to burn in generating electricity of granted.

At this point, you might be wondering what this post is doing on my software engineering blog. The answer is two-fold. First, since you are reading this blog at all, you are on an electronic device with access to the internet and the concept of power and energy should at least interest you on a superficial level even if it's not a lingering thought in the back of your mind all the time. Secondly, this is my blog and I can write whatever I see fit on here!

Having said all that, allow me to express something of importance to this entry. I live in Hawaii. This is important because Hawaii, unlike most places in the country, faces a very unique situation when it comes to energy. Due to its relatively isolated positioning in the world, Hawaii is heavily dependent on importing oil in order to keep our lights on. What this amounts to is that our residential electricity prices lead the nation by nearly triple. It's clear to see now how the energy challenges that we face in Hawaii might concern a software engineer whose livelihood depends on having consistent access to electricity. Even putting aside the obvious reliance of a software engineer upon power, it is also important to take note of Hawaii's unique challenges from a concerned citizen's perspective.

In addressing Hawaii's energy situation, it is good to first understand that energy is the measure of power used over a given amount time. In other words, a light bulb using a little power that's on for a long time can end up using the same, or even more, energy as a microwave that uses a lot of power but is only on for a few minutes in the day. Energy consumption is therefore what we must keep our eye on even more so than how must power a device requires to operate.

Energy conservation is a concern all over the world, but it is of particular importance in Hawaii. As I mentioned previously, Hawaii's reliance on oil for energy generation raises the costs of energy quite a bit. Additionally, due to the fact that Hawaii is geographically isolated from the rest of the world, its energy grid is isolated as well. This means that energy can't be freely transferred from grid to grid as needed as is the case in the continental U.S., not to mention the fact that Hawaii's power plants need to be smaller and therefore less efficient as well. What all of this amounts to is essentially that traditional methods of power generation aren't nearly as effective in Hawaii as they are elsewhere, yet it is very difficult to uproot these practices and adopt new methods as well.

Granted, it is often difficult to buck traditions and change is often slow and sometimes painful. Fortunately, there is and should be optimism for the energy situation in Hawaii because, along with its unique energy problems, Hawaii also has unique potential solutions. For example, although Hawaii's small size results in inefficient power grids, the same small size means a more modest need for energy overall compared to larger metropolitan areas. Furthermore, Hawaii is uniquely primed for numerous sources of renewable energy as well, including wind, wave, solar, ocean thermal and geothermal. Couple the potential for renewable energy with the desirability for Hawaii and its people to ditch the reliance on imported oil and there certainly exists reason for optimism.

Of course, better people than I have thought of these things before me and it is through these people that I am able to convey some of these thoughts to you today. It would especially be of surprise to me if any of these concepts were lost on the folks at the Hawaii Clean Energy Initiative (HCEI). The HCEI ambitiously plans for Hawaii to achieve 70% clean energy by the year 2030. There is probably initially quite a bit of skepticism for this number upon hearing it. However, the plans call for 40% of the energy to be from renewable sources and also reducing our need for energy by 30% thus enabling the 40% of renewable energy to effectively be 70% of the overall energy requirements. As people grow ever more conscious of the growing need for an energy solution and become more efficient with their energy use, even by simply replacing light bulbs with newer, more energy efficient ones, the 70% clean energy goal may not be so unrealistic after all.

For software developers in Hawaii, there are even a number of unique opportunities to contribute to the energy solution. For example, the Hawaii Natural Energy Institute (HNEI) implements various ways to collect energy usage data from consumers through installed devices in households which can send energy use information to HNEI as well as give users a more tangible reading on their own energy consumption. This allows HNEI to study not only energy usage in these households but also energy usage behaviors before and after the consumers are aware of their own consumption rates. Naturally, with all this collected data, software development expertise is then employed in the analyses and parsing of the information which may even be represented as graphical interpretations of energy usage that consumers can then access. Another opportunity for computer scientists interested in energy studies appears at Hawaii's flagship university campus as it undergoes renovations and seeks to improve energy efficiency in its buildings through wireless sensors streaming energy usage data to a central computer. Again, with all the data collected, there are opportunities for analyses and manipulation of the raw data into something coherent and useful. Likewise, with the rise in energy consciousness come more energy efficient homes and again, data collected from these homes provide unique opportunities for software engineers to help analyze it.

Even though being a mayor of Sim City might seem like a trivial task, the underlying lesson that one can take away from it is clear. Whether it's a computer game or reality, the need for better energy solutions exists and is more evident in the state of Hawaii than perhaps anywhere else in the country. Hopefully by now you also see why a software engineer might be interested in being part of the solution on a deeper level than simply the fact that their career choice relies on energy because, in fact, there are more than ample opportunities out there to challenge us and put our expertise to practical use.

Tuesday, October 25, 2011

Not so trivial pursuit - Software engineering edition

Hello readers. Today, I present to you 5 quickie questions for budding software engineers to chew on. Some of these are more specific to my development experiences so I don't expect you to know the answers, but you are reading this on the internet after all, so feel free to embrace the power of infinite shared knowledge.

1. Subversion is a version control system. Name another and briefly describe how it differs from Subversion. (Hint: Linus Torvalds insists you don't use Subversion)

RCS: Doesn't allow for concurrent changes, each developer must obtain a lock to edit a file. Developers must access the same file system to access files.

CVS: Versions are file-based as opposed to repository-wide. Back-end repository is composed of files rather than a database.

Git: Every developer has their own local copy of the whole repository. Rather than managing commit access, you choose other developers' repositories to merge with your own.

2. Briefly describe the difference between exhaustive and practical testing. Which test would you choose? (Answer correctness is based on your justification of your choice, rather than the choice itself)

Exhaustive testing can be more thorough and thus come closer to proving the correctness of a program where as practical testing tries to uncover errors by testing samples. Exhaustive testing, if possible to execute, can produce more reliable results. However, in most non-trivial programs, exhaustive testing is near-impossible if not impossible and thus impractical.

3. Name two ways that a robot can be scanned other than explicitly saying calling the scan() method.

Here are three other ways: 1) When your robot turns, assuming its gun and radar are not set to turn independently. 2) When your robot's gun turns, assuming its radar is not set to turn independently. 3) When your robot's radar turns.

4. When defining an equality relation, name at least two properties that must be upheld.

Here are four: 1) An object must equal itself. 2) An object must never equal null. 3) If two objects are equal, then their hash codes must be the same as well. 4) If object A equals B, and B equals C, then A must also equal C.

5. Given the following Ant code, what would you expect to happen? The default target is bubbles.


Ant prints out everything nice, then spice and finally sugar.

Friday, October 21, 2011

Alone we can do so little

An obligatory irrelevantly relative introduction spiel
If the pyramids were worked on by a single person, Tutankhamun's tomb would probably have a pretty big sunroof. Let's not argue over the details behind that statement or how King Tut existed after the age of pyramids and was buried in the Valley of Kings instead. The point being made is that the pyramids were built on the backs of a huge labor force working together to accomplish a single objective. Now if we can only apply this wonderful concept of collaboration to the world of software development, imagine all the virtual pyramids we could build together!

Let us collaborate...
Helen Keller once said, "Alone we can do so little; together we can do so much." The power of collaboration ought to be intuitively obvious to anyone. To illustrate, if we had 8 slices of pizza, it would be much faster for 4 people to eat 2 slices each as opposed to 1 person eating all 8 by themselves provided, of course, that each person eats at a relatively similar pace. Likewise, if a piece of software had to be developed, it seems obvious that if the work was divided amongst several developers, the overall efficiency of the development process would increase as well.

Pitfalls of working together
There are several downsides to group development of course:

1. The balance of work is not always fair. We've all been there before, a teacher assigns group work and you're forced to divvy up the work amongst the group members. But the day before the project is due, one of your group members have yet to even bother to communicate a single thought to the rest of you, not to mention put in any work effort. That's when you grit your teeth, shout some obscenities in your head and suck it up and do their work for them. By the way, if you have never gone through this before, you're the person that's slacking off.

2. Incompatibility of styles may exist. Sure, we can all pick up The Elements of Java Style, read it cover and cover and try to adhere to the standards at all cost. But there is always going to be a slip-up here or there. This really becomes a problem if you have a team member that's brilliant at coding but you can never figure out how their code works because it is simply unreadable and the documentation basically says, "trust me, it works."

3. Working concurrently is difficult. If the goal of a project was to serve a plate of faux-Chinese food to a hungry customer, a plausible solution would be to implement the Panda Express assembly line of food scooping. But when dealing with software development, working on a project sequentially becomes highly inefficient. Why must developer A wait for developer B to finish working on the Apple class of their Fruits project when he's in charge of handling the Orange class? But if they're each handed a copy of the Fruits project, it's entirely possible that the changes developer A makes to the Fruits project conflicts with with the changes developer B made.

Navigating the pitfalls
For dealing with the first two pitfalls, a large portion of the solution is communication. If there is an imbalance of duties, it really is up to every member to correct the situation. All too often you'll find that the person picking up the slack doesn't ever voice their dissatisfaction. Likewise, some of the solution to the second issue is to simply communicate and decide on a coding standard that will suit every project member involved. Then, as I've discussed previously, use a project builder like Ant! Using Ant in conjunction with automatic assurance tools like PMD or FindBugs and especially CheckStyle in this case will eliminate a big headache for any collaborative software development effort.

Enter SubVersion
Obviously, the problem of multiple developers working on a piece of software existed the very first time two programmers got together, modified the same piece of code, and realized they overwrote one another's alterations. If I had to guess, this probably took place a long time ago...

Not necessarily drawn to scale

But, I digress. With the advent of version control software, developers were able to successfully resolve the issue of concurrent development by requiring the source file to be checked out for revisions. While the source is checked out, no one else could make changes to it, but it made it possible for multiple developers to work on the same project without destroying one another's progress. However, the check-out system meant inefficient development, since a file could not be worked on simultaneously by another developer as long as it was checked out. The resolution was optimistic locking. Rather than actually locking the file from modifications and requiring that a file be checked in before it can be checked out again, a file could be "checked out" by any developer at any time and when they check the file back in and commit their changes, the changes are merged with other developers' changes. If a conflict arises, the developers can then work among themselves to resolve it. Subversion is one such version control system which utilizes optimistic locking and allows concurrent development.

Experiencing the multi-developer environment
To really grasp how useful Subversion can be, the best way is to experience it first hand. Downloading a project file from Google Project Hosting (which we will dive into a bit later) on which you are collaborating with 20+ people on is an interesting experience, to say the least. When I first downloaded the project just to get a feel for Subversion, I was able to immediately see the minor tweaks that my fellow developers had made previously. After settling on the revisions I wanted to make, I downloaded the latest project file again and, already, I saw additions to the project file that I weren't there just minutes ago. Conveniently enough for me, the changes did not interfere with the additions I had in mind, and I went ahead with my revisions, and committed the new file without a hitch. It was very interesting to see the updates being made in almost real time as multiple developers made their tweaks and committed their own changes. It was easy enough to simply download the project, make changes, and upload the changes but ultimately, the process had to be applicable to my own projects somehow! Subversion works by having contributors work from a central repository, but where could one host a repository that is easily accessible to all team members? One solution to this question came in the form of internet giant Google's own project hosting.

Hosting your very own software development project
Getting started with Google Project Hosting is simple, you just log in to your Google account, head over to the project hosting site and create a new project. To find out more, head over to their Getting Started wiki. Once again, I was able to host my very own project without too much problems. The only minor bump in the road for hosting my Robocode robot and officially opening the little guy up for open source development was creating the user and developer guide wikis. For those of you that are new to wiki editing like I was, there is a special wiki syntax by which you must abide by to quickly construct your wiki pages. Not all of the syntax is extremely intuitive, but a helpful guide does leave you with enough information to work out what you need to do to get your wiki looking how you want it to look. One interesting quirk about WikiSyntax is that words with multiple capitalization is automatically regarded as a link to another wiki page. Unfortunately, as it turns out, if you are hosting a Java project like I was, a lot of your references to your own project is regarded by the wiki as a link to a non-existent wiki page. This is a bit of a hassle, but ultimately, something that I could live with considering some of the other more useful features. For example, putting in a heading automatically generates an anchor to which you can then reference directly from a link. This was very helpful in creating a wiki with multiple headings and a Table of Contents that allowed the viewer to quickly jump to a specific heading. In fact, see it for yourself at my project home page.

Final thoughts
Not only is collaboration a good idea in software development, it is crucial to the success of larger projects. Albeit, I have thus far only barely scratched the surface of the potentials of hosting a project online and using version controlling systems to manage a collaborative project. But even with my brief swim in the vast ocean that is open source development, I can quickly already see the advantages to having a project hosted in a centrally accessible location and allowing multiple developers to access and modify the code concurrently. I'm hoping I was able to convey why I am so excited about the possibilities that these tools open up for me as a developer and that you, my faithful audience, will have some of the excitement rub off on you as well. After all, if you're reading this, you are likely interested in software engineering and if you're interested in software engineering, your proverbial mouths should be watering with anticipation of how you, too, can start collaborating with others right now!

Links to check out:
Apache Subversion
Getting started with your own Google Hosted Project
My Google Hosting Project Home Page

Tuesday, October 11, 2011

Coward: One who, in a perilous emergency, thinks with [its wheels] - Ambrose Bierce

A few weeks ago, I wrote about the marvelous little virtual minions that I created through the wonder that is Robocode. Now, one might have presumed that my robots were mere results of simple exercises no more exemplary of a battle worthy digital tank than a twig is of a shady oak tree. However, if one were to have thought that, then one would have failed to overlook that when thirteen twigs are combined, they would most definitely create something greater! Such as a branch perhaps?

To be certain, the general goal of this new endeavor was to create a robot that would compete among its peers in the virtual arenas in all of their 40 by 40 pixels of glory. In my efforts to accomplish this goal, I forged together a chimera of my previous iterations of single-function robots to create a single entity armed with the three basic principles of a Robocode robot: Movement, Targeting and Firing. Additionally, as any good robot knows, its primary edict in life is the Three Laws of Robotics. Now, if you will all recall from our previous discussion of the Three Laws of Robotics, the first two laws don't really factor much into Robocode robots. Thus, the ThirdRobotLaw robot was conceived, with its utmost priority being the protection of its own life.

ThirdRobotLaw, or TRL as I've come to know the little bugger as, was designed with a focus on survival. As such, it was determined that the strategy for its movement would be to minimize opportunities to be hit by its opponents. What this entails is that first we had to reduce the potential angles of attack by enemies. Hugging a wall, as it turns out, was an obvious choice since it immediately reduced a fourth of the cardinal directions from which bullets could come from. Upon the battle starting, TRL picks either the West or East wall to run towards in a true coward's fashion by determining which wall is closer. Upon reaching a wall, TRL changes to one of two modes depending on the number of enemies left on the battlefield. The first mode, if there are more than one enemies remaining is to randomly choose a direction between North and South and glide towards it at a random interval. The idea behind this mode is that if the enemy of TRL's enemy is the enemy of that other guy. TRL deviously hides along the wall and shuffles along at random and hopes that its enemies kill each other off. However, when the battlefield participants dwindle down to but one opponent, TRL will then adopt the only strategy available to a coward in that situation: eat or be eaten. At this point, TRL goes into turret mode and ceases to randomly glide around in a desperate effort to not die. It is also important to note that even in turret mode, if TRL is hit by bullets multiple times, it will try to glide away at random again in an effort to avoid bullets again. Conversely, if TRL is missing too often, it will try to move away from its current wall in an effort to get more aggressive.

Prior to reaching turret mode, TRL does not really engage in any sort of robot targetting. When it finally does begin to track enemies, there should only be one enemy left and thus, no real illusion of choice as far as who to prioritize. Using a modified version of the TrackFire sample robot's tracking mechanism, TRL sits in place and tracks the closest enemy. The closest enemy, in this case, also happens to be the only enemy.

When in turret mode, whenever TRL scans a robot and its guns are ready to fire, it will do so. However, based upon how far its enemy is, TRL will scaled back the bullet power in order to conserve energy since greater distances usually means a higher likelihood of missing. Yet, in order to compensate for robots who also act as stationary turrets, if TRL is able to connect on several consecutive shots, it was switch its guns to fire maximum power bullets under the assumption that either the other robot is stationary or our tracking is doing a decent enough job of keeping our gun lined up.

Here are the results of TRL's 1v1 attempts against the sample Robocode robots:

Vs. Walls: 0 wins, 10 losses (an absolute massacre)
Vs. RamFire: 0 wins, 10 losses (yet another massacre)
Vs. SpinBot: 1 win, 9 losses (slight improvement, but otherwise utter defeat)
Vs. Fire: 2 wins, 8 losses (still yet a bit better)
Vs. Crazy: 5 wins, 5 losses (two random robots producing 50/50 results)
Vs. Tracker: 7 wins, 3 losses (a bit more positive news)
Vs. Corners: 10 wins, 0 losses (unfortunately this was TRL's primary sparring partner)
Vs. SittingDuck: 10 wins, 0 losses (anything less here would be unacceptable)

On a whole, versus sample robots, TRL does not fare well in 1v1 situations, winning only 35 out of its 80 battles, 10 of which were against SittingDuck. While it would be most gratifying for me to report that in group battles, for which TRL was designed for, it performed admirably and conquered the field of battle by watching others die in front of its radar that was simply not the case. In fact, depending on the types of robots it faced in battle, it was often the first robot to die, especially when the other robot specialized in wall movements as well, forcing TRL to leave its sanctuary. The silver lining is that in the absence of these types of robots, TRL was rarely the first robot to die, and occasionally nabbed the first place in a round by virtues of janitorial prowess (i.e. finishing off the last enemy who has already no doubt sustained heavy damages). In retrospect, it might have been prudent for TRL's random wall sanctuary to include the North and South walls to avoid being pigeonholed by certain wall riding robots. Additionally, rather than turning its body to glide up and down, it may have been simpler and faster to simply make use of the back() functions available to all Robocode robots.

In testing TRL, I knew that its 1v1 prowess would be limited at best and so its acceptance tests consisted of generally weaker sample robots like SittingDuck and Corners. I also made the decision that I did not particularly care if TRL could beat non-SittingDuck opponents 100% of the time and that a better-than-half average was sufficient. In testing its movements, I made sure that its two primary controlled movements were implemented correctly. That is to say that TRL always necessarily arrived at either the East or West wall in each round without fail, and that against a stationary target, it too was stationary. Finally, I tested that TRL's bullet power was indeed scaling based upon its intended algorithm and that upon successfully hitting a target consecutively, it would then increase its bullet power to maximum.

If nothing else, this project has taught me one thing: an idea might sound good but until it manifests and is tested, there truly no way to know. Even in hindsight, I feel like the design of the strategy to evade at random until everyone else is dead is a sound one. Albeit there are kinks and unexpected behaviors that were unforeseen in the design of the robot, but overall the tactic still seems good, even if the execution in practice yields poor results. However, rather than focusing on the weaknesses and shortcomings of the robot, the most important thing that I took away from creating ThirdRobotLaw was actually the development process. From the Java coding standards to the automatic quality assurance tools, I learned more about the process than robocode development. It was simply nothing short of amazing how much more polished my project appeared in the end when I made use of Ant in conjunction with Checkstyle, PMD and FindBugs. Certainly, having more tools at my disposal as a developer now and having gained familiarity with how to take advantage of said tools, I would probably have approached this project a little differently. In particular, I would have been testing my robot along side JUnit from start to finish, making sure that each behavior was working as intended before moving on and tacking on more features. One of the biggest mistakes I made in this project is a mistake that often extends to students and possibly developers all over the world in that I started to write my robot as soon as I had a design in mind. I then proceeded to write big portions of functionality that intertwined with one another all at once rather than keeping them as separate modules which can then be tested on a per module basis as well. Ultimately, the failures led to a disappointing survival rate for a robot whose namesake is, in and of itself, an instruction for absolute survival. As a TRL's designer, I express my regrets here and now, and apologize to my loyal fans for TRL's many flaws. However, as a more seasoned Robocode developer now, I can promise you without a guilty conscience that version 2.0 of our robots will better than ever! Maybe by then it will be able to win 36 out of 80 rounds...

Tuesday, September 27, 2011

I'm terrified of bugs but Ant just might change my mind

I am. I truly am terrified of bugs. As a person, I am terrified of just about anything with more than four legs and as a software developer, I am terrified of my programs not doing what I want them to do. O bugs how I loathe thee! I recently discovered however, albeit ten years too late, that there actually is a bug I am actually quite fond of: Ant. Granted, if one were to truly overanalyze this one exception to my entomophobia, an ant is still an insect and the Ant I am so fond of is a Java application builder.

As any software developer should know, there exists a massive divide in the developer world regarding operating systems. Furthermore, not every developer is going to agree on which development environment they prefer to write code in and everyone has their own thought process about how their software projects should be organized. Naturally, these exponential differences between developer systems are going to cause trouble when two or more developers deem it necessary and wise to collaborate on a project. Thus the birth of software building utilities arrived and developers could carry on knowing they were right all along about which development system and environment is the best.

Ant is a tool which is ideally used for building Java projects. Invoking Ant on different operating systems should, theoretically, always yield the same project build and ultimately make it possible for developers to continue to work on the project in their preferred manner but have a quick solution for sending the project off to be worked on by another person as well. Additionally, Ant can be instructed to run various quality assurance tools each time it tries to build a project thus ensuring that the projects being shared adheres to the same standards as others using the same Ant build. It's easy to see now why a software developer can, upon learning about the existence of it, be so quick to embrace the technology.

Learning to write an Ant script does require a basic understanding of XML. However, suffice it to say that each Ant task is a different XML tag that is understood by Ant to perform some action whether it be print something to the command line or to simply set a value to a property. In order to get a crash course on Ant, I walked myself through several "Ant Katas" to get familiarized with some basic Ant scripting concepts. Said Ant Katas follow:

Preface
I do not intend to explain how I accomplished these katas in detail, but rather share with you my learning experience through them. On a side note, there have been several external links thus far in this article for your edification and education. You are welcome.

Ant Kata #1 - Ant Hello World
The idea behind this Kata is to learn how to write a simple Ant script. With a bit of quick internet researching, I was able to learn that an echo tag with a "helloworld" message value was all I needed. However, this being my first foray into Ant scripting, I hit a road block almost immediately. An echo tag by itself was no good because Ant requires actions to be wrapped in target tags to be performed. Targets, as it turns out, are the little blocks of instructions that tell Ant what to do. But since you can have several targets inside an Ant script, how would it know which target needs to be carried out, if at all? Hence my final lesson from a deceivingly simple kata was that one can specify a default target for Ant to use when the script is executed if no target is specified by the user of said script.

Ant Kata #2 - Ant Immutable Properties
This Kata involved associating a value to a property element in Ant and then associating a different value with it shortly after. As one might expect with a Kata referring to immutability, a property's value can not be altered once it has been set. What struck me as interesting here is that essentially properties can be viewed as constants in Java since they can only be set and referred to but never changed.

Ant Kata #3 - Ant Dependencies
If you have ever used Make before, you might be familiar with the concept of dependencies. Briefly speaking, associating a dependency to one target tells Ant that the execution of this target depends on the successful execution of its dependencies. For any person reasonably logical, the concept of dependencies shouldn't be very difficult to grasp. If a target Keyholder depends on Car (to get to work) and a Store depends on Keyholder (so it can open), it follows that Car is needed for Keyholder which is needed for Store. Likewise, if Car depends on Store (apparently the car needs to be purchased from the store first in this case) then we have a circle of dependencies with no logical entry or exit point. In the latter case, Ant would complain and fail to execute the build.

Ant Kata #4 - Hello Ant Compilation
The point of Ant is to build projects - ideally Java - and any decent Kata routine certainly ought to have something practical as part of its choreography. Ant Katas are no different and to practice Ant in see it perform its core functions in all its glory, I wrote a simple Java program to simply print "Hello Ant" to the console. By applying everything I learned in the previous Katas, I was able to execute this Kata without much trouble. Compiling the Java file was a simple matter of calling on Ant's javac task and telling it where to find the Java file and where to put the compiled file.

Ant Kata #5 - Hello Ant Execution
Of all the Katas, the one which gave me the most problems was figuring out how to execute the compiled class file from the previous Kata. Rather than an issue with understanding how to use the java task in Ant properly, it was a dependence on my development tools to keep track of my class path which led to my headaches. However, once I was able to surmise that it was my use of a lengthy package name which was causing my Ant build failures, I was able to quickly diagnose the problem and fix my script accordingly. Lo and behold, my compile was successful and my execution printed out "Hello Ant" to my delight.

Ant Kata #6 - 8
For you, the reader, I will summarize that the goals for Katas 6 through 8 were to have JavaDocs be generated by an Ant script, a standalone "clean" target to exist and be readily invokable should the user choose to do so, and to put everything we've learned from the previous Katas together and package the project in one neat zip file for distribution. However, as I forewarned previously, this is a discussion of my learning experience through these Katas and, quite frankly, there is little left to discuss here.

Ironically, it turns out, the simpler Katas taught me the fundamentals of Ant scripting which allowed following Katas to be much easier to execute, and the skills for deciphering how Ant tasks work were all it took to execute the latter Katas. In retrospect - which is always an easy perspective to speak from - it was with a very low level knowledge of Ant and XML that I was able to manage completing my 8 Ant Katas and take my first step towards writing more robust and functional Ant scripts. That fact, coupled with the power of Ant and its supreme usefulness in software development, made me a believer that perhaps not all bugs demand from me the response of utter terror.

Tuesday, September 20, 2011

Three Laws of Robotics

Whenever a person thinks of robots, they tend to think somewhere along the lines of C-3PO or R2-D2 - digitally charged beings programmed so superbly that they are nothing short of autonomous.  Now imagine, if you will, that R2-D2 had spent the majority of the Star Wars franchise sitting in place and twirling its dome-like noggin around in circles.  Han, Luke and Leia would have met an early death at the hands of Jabba the Hutt but R2-D2 would have performed exactly what I programmed my robots to do in Robocode.  Continuing down the line of not-so-obscure science fiction references, it is nearly blasphemous to talk about robots without talking about the Three Laws of Robotics as established by the late Isaac Asimov.  The laws state:

1. A robot may not injure a human being or, through inaction, allow a human being to come to harm.
2. A robot must obey any orders given to it by human beings, except where such orders would conflict with the First Law.
3. A robot must protect its own existence as long as such protection does not conflict with the First or Second Law.

Given my limited exposure to the joys of Robocode I was saddened to find that, while my robots all certainly cannot injure a human being and obey my poorly devised orders to the letter, they were all ill equipped to protect their own existence.  In my defense I, too, was given instructions on the functions that I was to write into my robots and, to their credit, all the robots I wrote performed valiantly on the field of battle with what they were given.

To get my feet wet, so to speak, I started off with a building a robot that did absolutely nothing.  This poor robot, when pitted against just about any other robot, was essentially defenseless.  I do make it a point to say just about any other robot because it drew every match it had against the sample SittingDuck robot which came packaged with Robocode to a dramatic stalemate.  However, as one might expect, making a robot that does absolutely nothing is not very interesting and soon, with the aide of a few built in movement methods, I was creating robots that could leisurely move across the playing field provided its opponents, too, were all pacifists who fired no bullets.  But even robots moving across the field back and forth quickly grew tiresome and it became all too obvious that more advanced techniques would be required to get them to perform more interesting movements.

Problems for me quickly arose when I attempted to create a robot that moved itself to the center of the playing field.  Firstly I realized that, due to the nature of how headings are organized from a range of 0 to 360, I had to warp my way of thinking and the trick to turning the robot efficiently would be to be very methodical and view destination headings as being relative to the robot's current headings.  To turn efficiently also meant that the choice to turn left or right was important and had to be based upon the robot's initial heading.  After tinkering around with the numbers a bit, I was finally able to get a robot to properly turn and move towards the center vertically and then horizontally.

Alas, I was not satisfied.  When walking to the middle of an open field, I would never first walk vertically along the field, turn 90 degrees, and proceed horizontally towards the middle.  Barring any obstacles, I would almost certainly walk diagonally across and I could think of no reason why my robot should not be allowed the same choice.  Thus, through trigonometry, I was able to devise an algorithm for which my robots were able to locate the center of the field, decide to turn left or right to be efficient and move straight to the center in a straight line.

Having mastered exhibited this skill a single time now, I forged ahead in my quest to learn Robocode and attempted to get my robots to not only acknowledge the existence of other enemies but to react to their existence as well.  Surprisingly, following another robot proved not to be as absurdly difficult as one might have imagined since Robocode actually offers several helpful methods for tracking enemies.  Since it is possible to keep a robot's radar facing in the same heading as the robot itself, following other robots was just a matter of turning my robot according to where the enemy is.  However, when it came time to finally work with the guns, a lot of unforeseen trouble headed my way.

Initially, working with guns seemed fairly straightforward: turn the gun in a direction which automatically activates the robot's radar and every time an enemy is scanned, fire away.  But when trying to track an enemy, I found that my previous algorithm for following an enemy did not translate very well.  This was due to the fact that, upon scanning an enemy, the bearings returned to my robot was relative to my robot's current heading, and not my robot's gun's current heading.  Thus working with bearings, which ranges from -180 to 180 and having to translate its relation from the robot's heading to its gun's heading turned out to be a spatial nightmare for me.  Ultimately, the solution I found was to translate the bearings into the same 0 to 360 range that headings worked in and after struggling with the problem for hours, I was able to get my robot to track another robot fairly well.  Albeit, at times, the tracking would still lose its target and the robot would be forced to spin its gun to relocate the enemy.

Although I was able to complete 13 simple robot implementations and develop a minor grudge against Robocode and mathematics in general, I realized that some of the instructions specified picking an enemy and although they did not necessarily always say to stick with the chosen enemy, the implication was there and had somehow gone over my head.  Thus, it is difficult to say that all 13 of my robots are living up to their specifications, but at least they are not injuring human beings.

Tuesday, August 30, 2011

Bizz Buzz Woof

If you don't know what Bizz Buzz is then you are, quite frankly, as ignorant as I was until 5 minutes ago.  Until recently, I didn't know that the game Bizz Buzz and several variations of it had existed.  Wikipedia to the rescue: http://en.wikipedia.org/wiki/Bizz_buzz.

The Bizz Buzz game, commonly known as the Fizz Buzz game is a game where the goal is to count numbers starting from 1.  However, whenever the counter encounters a number which is divisible by 3 he says the word "fizz" in place of the number.  Likewise, when the number is divisible by 5 it is replaced by the word "buzz" and when the number is divisible by both 3 and 5 the word "fizzbuzz" is said in place of the number.

By now, you're probably already 4 drinks in after finding out about this wonderfully simple game and can no longer make it past 6 without having to take yet another sip.  Alas, this is a software engineering blog after all so why even mention a silly game here?  Adapted for computer science, we can convert the game into a programming exercise: Print whole numbers from 1 to 100 but print "Fizz" in place of numbers divisible by 3, print "Buzz" in place of numbers divisible by 5 and print "FizzBuzz" in place of numbers divisible by both.  It's easy to see how this seems like a trivial matter when solved by a computer program, but according to an article written in 2007, "the majority of comp sci graduates can't [write the fizzbuzz program]."

Here is my solution which, by the way, took me 4 minutes and 56 seconds to implement from the time I opened by editor to the time that I was satisfied it was correct.  Obviously, I didn't do a lot of testing but I am still reasonably confident that the code satisfies the fizzbuzz requirements.


This program was by no means difficult to implement.  In fact, I was quite shocked to hear that most computer science graduates struggled writing something to simple.  Just to touch on the code briefly, I should explain the logic behind it just a bit.  Often, when converting a word problem into logic, it is easier to implement the algorithm behind solving the problem by thinking backwards.  The most specific case in this problem seems to be printing FizzBuzz when a number is divisible by both 3 and 5.  Simple arithmetic tells us that a number being divisible by both 3 and 5 means the same thing as a number being divisible by 15, saving us from doing two comparisons instead of one.  Next, it is important to realize that even though a number being divisible by 15 appears to be the most specific scenario, it is actually the most broad because it covers numbers divisible by 15, 5 and 3.  Thus, in order to make sure that, when a number is divisible by 15, we ignore the fact that it is also divisible by 5 and 3, we perform this check first.  The next two checks for divisibility by 5 or 3 can be interchanged and finally, if all checks fail, we know the number must not be divisible by any of the aforementioned numbers.

Personally, this logic struck me immediately, but I too can't claim that I am an expert programmer by a long shot.  When first posed with this questions, I came to the realization that I had quickly forgot how to start off a Java program.  It's almost embarrassing to admit but a couple simple lines of code to start a Java class and the main method in the class had slipped my mind because I had grown somewhat reliant on Eclipse filling in the "trivial" parts for me.  The other mistake that I originally made in my mind was to put everything into one method without considering the need for effective testing, which is now more achievable through JUnit in its current two method form.  Ultimately, the more complex logical parts of any program ought be split off from the main method so that each module can be tested individually.  Fortunately, because the program was so fresh in my mind from having walked through it in my computer science class, I ended up writing this code without running into any issues beyond quick syntax errors.  Unfortunately, for the exact same reason, my variables ended up being named the exact same way both times that I rewrote the program for my own edification and for that display of genuine lack of creativity, I had to frown upon myself.