Sunday, February 26, 2012
Enums and Hair Colors
Wednesday, June 29, 2011
Variable Initialization in Busy Kitchens
Wednesday, June 22, 2011
Swapping Array Values and the Swimmy Friends Pet Store
Swapping two values in an array is a basic operations that helps illustrate how arrays store data. Each entry in an array can be viewed as an individual variable -- it stores one piece of information. Thus, in order to swap the values contained two different entries, additional (temporary) storage must be used. Specifically: 1) The data from one array entry is written to the temporary storage, 2) the data from the other array entry is written into the memory location of the first entry, and 3) the data from temporary storage is written into second array entry. For example to swap array entries at indices i and j in C, we might write:
int temp_variable = my_array[i];
my_array[i] = my_array[j];
my_array[j] = temp_variable;
Casey's first day at the Swimmy Friends Pet Store had not gone smoothly. Within fifteen minutes, he had accidentally allowed all thirty turtles to escape. He then spent the next eight hours trying to round them up. Although the turtles were slow, they scattered in different directions and hid under store shelves. No matter how nicely he asked, the turtles refused to come when he called them.
Casey sincerely hoped that his second day would go better.
"Hey, Casey. I have a job for you." called the manager as Casey entered the store.
"Sure!" responded Casey eagerly. He wanted to prove that he was a good employee.
"We are starting a promotion on tiger barbs this week." the manager explained. "I want to put them in the big tank at the front of the wall. Can you swap them with the neon tetras?"
Casey looked at the fish section. The entire back wall of the store was lined with large, brightly lit fish tanks. At the front was the tank currently occupied by the neon tetras. Five tanks over, two dozen tiger barbs swam lazily around a small rock. Both tanks looked quite heavy.
"You want me to move the tanks?" asked Casey. Casey's mind froze as he pictured himself dropping a full 50 gallon fish tank.
"Of course not!" the manager answered. "The tanks are full of water. Just swap the fish. The temperature and PH are already identical."
Casey nodded. He walked over to the tiger barb tank and began trying to scoop up barbs in the net. The manager watched from the side.
"What are you doing?" the manager asked.
"Moving the tiger barbs over." responded Casey without looking up. The tiger barbs were fast, and Casey was not particularly coordinated. He thrashed about with his little green net, hoping that he could at least catch one by luck.
"You do know that tiger barbs and tetras cannot go in the same tank, right?"
"Uh huh." responded Casey, still lost in concentration.
"So, what are you going to do with the tiger barb that you are having trouble catching?" prompted the manager.
"I am going to put it… oh." Casey suddenly realized his mistake. There was no way he could transfer the tiger barbs over without first moving the tetras. And there was no way to transfer the tetras over without first moving the tiger barbs. The whole swap was deadlocked.
The manager watched for a minute as Casey grappled with the problem, waiting for him to see the solution. After all, it was not a hard problem. Finally, the manager realized that Casey was not going to figure it out.
"Just use that empty tank as a temporary storage." The manager prompted. "First, put the tetras in that empty tank. Then move the tiger barbs to the old tetra tank. Then move the tetras to the old tiger barb tank."
Step 1:
Step 2: 
Step 3: 
"But… that means three sets of moving things. I know that I can do it in two." responded Casey. He was determined to prove that he was a good employee.
The manager sighed. "No. You cannot. You need to use temporary storage. Otherwise, you will end up putting tiger barbs in the tetra tank and causing problems."
Casey wanted to argue, but he could not think of a better solution. "Okay," he finally agreed.
The manager looked at Casey doubtfully. While he was semi-confident that Casey could handle the fish swap, he worried about Casey doing something stupid later.
"Come find me when you are done." the manager instructed. "And, stay away from the turtle tank." he added for good measure.
Sunday, June 19, 2011
The Incident at the North Gate (or Why = Is Not ==)
In many modern programming languages the expression "a = b" is used to assign the value b to the variable a. In contrast, the expression "a == b" tests for equality and returns true if and only if the values of a and b are the same. Unfortunately, in some languages, such as C and C++, this syntax can lead to difficult to detect errors because the = operator returns the value being assigned. For example, "if (a = b)" will compile without problems and trigger if and only if b's value is equal to true.
King Fredrick loved to tell the tale of the "incident at the northern gate". He was a firm believer in the importance of clear, correct documentation. And, the occurrences of that day provided a perfect case study.
The incident had occurred during the last period of war and unrest. King Fredrick's father held the throne and was working hard to guide the kingdom toward peace and prosperity. As part of this effort, he personally oversaw the creation of new rules for the castle guards.
The new rules read:
"Check the entrant's ID and examine their entrance ID class.
IF (ID class == 0): they are a member of the royal family, so let them pass,
ELSE IF (ID class == 2): they are a member of the carpenters' guild, so let them pass;
ELSE IF (ID class == 3): they are a member of the plumbers' guild, so let them pass;"
and so forth. Unfortunately, even a king makes syntax mistakes occasionally. The erroneous line read:
"ELSE IF (ID class = 72): they are a mime, so stop them"
The king had used an assignment statement instead of an equality test.
It took three days for someone to reach this test in the series of IF-ELSE statements. On that day a young hedgehog walker (ID class 185) arrived at the north gate with the King's prize hedgehog. He presented his ID to the guard. The guard consulted his manual and paused in confusion.
"What is wrong?" asked the boy.
"Well. The manual says here that I am to change your ID class to 72 and prevent you from entering." The guard responded. As he spoke he reached into his booth and pulled out a permanent marker. He crossed out the ID class of 185 and wrote 72 in its place.
"But, I am supposed to go inside." argued the boy. "I have the king's hedgehog."
"I am sorry lad. No mimes allowed in here!" responded the guard.
The boy looked confused. "Mime?"
"Yes. It says ID class 72. That means you are a mime!" answered the guard.
"But, you just wrote that. It was ID class 185. I am a certified hedgehog walker. And, I am working on my parrot walking license too. I provide a valuable public service."
"The manual told me to reclassify you as a mime, so that is what I did. And, we do not allow mimes here!" responded the guard formally.
"But…" started the boy.
"Be gone!" shouted the guard.
The boy quickly retreated and circled around to the south gate. Unfortunately, his ID now clearly indicated that he was a mime. He was not allowed to enter. Discouraged, the boy went home, bringing the king's hedgehog with him.
The incident went unnoticed for almost a day, until the king sent a search party to find his hedgehog. Fifty knights arrived at the boy's home, scaring both the boy and the hedgehog out of their wits. It took three hours for the boy to pull himself together enough to explain what had happened. And, it took another five hours to calm down the hedgehog.
The king was furious when he found out. He marched down to the north gate and grilled the guard on why he had changed the boy's ID. The guard pointed to the instruction and explained himself. But when the king saw that this was his own mistake, his mood only worsened. The king launched into a six hour rant and then immediately insisted on three sweeping changes:
1) All IF statements would put the constant value before the variable (e.g., 0 == Class ID), so that no assignments could happen by mistake;
2) Every new set of rules had to be checked by at least one other person for correctness (although this was a great practice in its own right, the king also wanted someone else to blame if there was a mistake).
3) All new rules would be unit-tested by a group of Shakespearean actors.
Despite the seeming overhead of these new regulations, the castle was launched into an unexpected period without any mistakes. Even the castle stables, which had 100 page rulebooks, went a full week without any mistakes.
Feeling satisfied with his contribution for the day, the king decided to get a pet parrot. He had heard good things about parrots recently.
-------------------------
Related stories: Also see the story of how King Fredrick rewrote the instruction castle instruction manuals to use the Switch/Case format in Switch/Case and the Palace Guards. Or read more about the IF-ELSE statement in Learning IF-ELSE the Hard Way.
Friday, June 10, 2011
Switch/Case and the Palace Guards
Switch/Case is a computational construct in many modern programming languages that allows the program to choose one of multiple execution options. The option is chosen by "switching" on the value of an input parameter.
King Fredrick loved performing surprise inspections of the palace guards. Naturally, he felt that these inspections kept everyone prepared. But, more importantly, he found that wandering the grounds for an inspection was the best way to keep the castle steward from finding him. If Fredrick stayed in the throne room, the steward would constantly bring problems to his attention. Sometimes, the king just needed some quiet.
"You there. Guard." called the king.
The guard groaned quietly. Unlike the king, the guards were not fond of surprise inspections.
"Yes, sir!" the guard responded in his best military voice.
"Tell me, are you always at this gate?" inquired the king.
"Yes, sir!" The guard could sense that it was going to be a long day.
"Wonderful. Wonderful. I have some questions about security. If someone comes down the path, how do you know whether to let them in?"
The guard reached into his little guard booth and pulled out a thirty page instruction manual. He quickly opened to the first page, hoping that the king did not see the coffee rings on the cover. It was considered disrespectful to use the official castle manuals as coasters. But, truthfully, that was often their most useful function.
The guard started to read from the manual in a loud military voice:
"Check the entrant's ID and examine their entrance ID class.
IF the person is a member of the royal family (ID class 0): let them pass,
ELSE IF the person is a merchant of a registered guild (ID class 2, 3, or 6): let them pass,
ELSE IF the person is from an opposing army (IF class 107): stop them,
ELSE IF the person is a registered juggler (IF class 71): let them pass,
ELSE IF the person is a registered mime (IF class 72): stop them,
ELSE..."
"Enough!" interrupted the king. The manual was in the familiar IF-ELSE series of conditions of which the past king, Fredrick's father, had been so fond. Why any king would prefer that style was beyond Fredrick. Fredrick was certain that he had updated all the manuals by now.
"It looks as though we need to update your manual." the king stated.
The guard was confused. He also looked scared. "But Sir, I have not made any mistakes. No intruders have been let in and no VIPs made to wait. I have not done anything wrong!"
The king gave the guard a reassuring smile. It did nothing to assure the guard. "No. That is not it. The manual uses a complex format that is simply harder to understand. We switched everything else to switch/case a few years ago. For a long list of conditions like that, it can be cleaner."
"Switch/case?" asked the guard. He did not remember that from his training.
"Yes." the king looked around for a prop to illustrate. Finding none, he started gesturing with his hands.
"Here is how that would work in switch/case." the king began.
"Check the entrant's ID and find the first matching case.
Case Royal Family: let in and done,
Case Enemy: Keep out and done,
Case Merchant of a registered guild: let in and done
And so forth!"
"You just go down the list and find a match. It is the same logic as the long list of nested IF-ELSE conditions. It is just easier to read... Sometimes." finished the king. He loved explaining computational constructs and was debating launching into a description of unrolling loops, when he realized that he could be boring the guard. He had a habit of boring people sometimes. Then again, the guard was nodding intently as the king spoke. Maybe the guard would want to hear about unrolling loops.
"Oh..." responded the guard, clearly thinking this over. "Why do you keep saying 'and done' after each command?"
"Well technically, the way it works is that you go to the first case that matches and keep reading instructions down until you hit a break. That way you can use complex blocks of commands for multiple cases without repeating them. When I say done, I just mean break out of the switch statement."
"Oh... But what if the appropriate condition is not there?" asked the guard.
"You can always have a default case to cover everything else. For you, I would make that 'Keep the person out and call for clarification.'"
The guarded nodded. "Yes. That would seem like a good default. I would hate to have to make a judgement call on my own. But, it seems that you are not actually changing any of the procedures?"
"That is correct." answered the king. "Switch/case can be thought of as a sort of shorthand for a long series of if statements. We will simply clean up the manual… and maybe put something in there about marching bands. Yes. We should certainly have a case about marching bands."
The king trailed off and stared out at the castle wall. Although he could not explain it, he knew that marching bands, mimes, and clowns all needed their own cases. Something about each of them made him profoundly uneasy.
"Well, I shall return to the castle and set to work on a new manual right away." proclaimed king Fredrick. He was excited by the opportunity to update more castle documentation. Given the recent peace in the kingdom, he had not had much real work to do for a while.
This was the best news of the guard's day: an early ending to the surprise inspection.
------------------------
For more information on IF-ELSE statements, see Learning IF-ELSE the Hard Way.
Or for more adventures of King Fredrick, see Hunting Dragons with Binary Search or Stacks, Queues, Priority Queues and the Prince's Complaint Line.
Friday, May 27, 2011
Learning IF-ELSE the Hard Way
The IF-ELSE statement is a computational construct that allows the program to branch off and execute one of two different blocks of code. The IF statement starts by evaluating a Boolean clause. If this clause evaluates to true, the block of code conditioned on this IF statement is executed. If an ELSE statement is present, it can provide a block of code to execute in the case where the Boolean clause evaluates to false.
Ann had learned the value of IF-ELSE statements at a very early age. When she was only three years old, she was given VERY strict instructions from the castle's head chef NOT to randomly eat things in the kitchen. Specifically, she was told:
IF the food is on the 'finished' table
You can eat it.
ELSE
Do not eat it.
Of course, as any three year old is bound to do, Ann ignored these instructions. She would sneak into the kitchen and eat pieces of fruit off of the chef's prep table. Each time that the chef caught her, he would give her a lecture about obeying the IF statement. His lectures would last a full ten minutes and include at least one remark about "kids these days". Ann enjoyed listening to him describe the branching logic of the IF statement almost as much as she enjoyed sneaking fruit. In fact, some days she even made sure that she was caught so that she could listen to his rants.
Then one day, the chef was preparing eight-chili soup for dinner. As the name implies, the ingredients involved eight different types of chilies, including the ultra-hot Dragonia chili. Unfortunately for Ann, the Dragonia chili looked remarkably like a strawberry. She snuck two, and popped them in her mouth. The resulting pain was intense. Ann's eyes did not stop watering for three weeks. After that, Ann never disobeyed the chef's IF statement again.
As she grew older and more responsible, the chef added a chained IF statement to allow Ann access to a wider variety of food:
IF the food is on the 'finished' table
You can eat it
ELSE IF the food is on the 'raw ingredient' table AND you ask first AND the chef says "yes"
You can eat it
ELSE
Do not eat it.
Having learned her lesson from the chili pepper incident, Ann dutifully obeyed this new expanded rule. Food that was on the finished table was always okay to eat. Otherwise, if the food was on the 'raw ingredient' table, she knew that she would have to ask the chefs first. The logic was simple and covered the important cases.
Of course, those rules still did not stop Ann from trying to trick her younger brother into eating Dragonia chilies. She even succeeded -- twice.
-------------------------------------
For more IF-ELSE fun, see The Marvelous IF-ELSE Life of the King's Turtle.