Home

Advertisement

Customize
igor_nav
28 October 2009 @ 12:13 am
Aside from the amazing writing, one thing I love about Dollhouse is the Topher character. It's the most (the only?) accurate portrayal of a genius computer hacker guy I've ever seen. He is spot on -- extremely competitive, always trying to do the absolutely best job possible, gets excited when somebody challenges him (Alpha), talks down to the dumb people around him, gets really into it when explaining something technical, has no respect for all that "feelings" and "cosmic morality" crap, but isn't an antisocial basement slob.

Any other show would have him buried under rotting, empty pizza boxes, with long, dirty hair, afraid of any contact with humans, let alone females. He would have a sex robot, too. Instead, Topher looks like a normal, approachable guy, works just fine with several other people, including a woman, who is his boss, and enjoys an occasional date with a girl. Yes, she is one of the "dolls", but that's quite far from the usual robotic girlfriend cliche you would find in Buffy or Firefly, both of which featured nerdy geniuses with robotic girlfriends. He likes the social aspect of his date; they spend the time playing video games and having a passionate conversation. In that sense, his relationship is more substantial than Adelle's relationship with Victor.

I get Topher completely. He is me. I'm glad Joss finally got it right, on third try. Fourth, if you count Dr. Horrible. That was a step in the right direction. A tiny part of me is waiting for Dollhouse to get cancelled, as it obviously will be, just so that I can see the next set of characters he comes up with. Looking at the garbage that was Season 1 of Buffy and the steep slope of improvement since then, I will be following his work very closely.
 
 
igor_nav
19 October 2009 @ 01:27 pm
SLOCCount is a program for estimating the cost of writing code. It takes a directory of source code and estimates the amount of time and money it would take to hire somebody to write that code for you.

Here is what SLOCCount says about all of the code I wrote while solving problems on UVa and during various online programming competitions. This doesn't include TopCoder, so the true number is much larger.

Total Physical Source Lines of Code (SLOC)                = 178,686
Development Effort Estimate, Person-Years (Person-Months) = 46.32 (555.78)
 (Basic COCOMO model, Person-Months = 2.4 * (KSLOC**1.05))
Schedule Estimate, Years (Months)                         = 2.30 (27.61)
 (Basic COCOMO model, Months = 2.5 * (person-months**0.38))
Estimated Average Number of Developers (Effort/Schedule)  = 20.13
Total Estimated Cost to Develop                           = $ 6,256,575
 (average salary = $56,286/year, overhead = 2.40).
SLOCCount, Copyright (C) 2001-2004 David A. Wheeler
SLOCCount is Open Source Software/Free Software, licensed under the GNU GPL.
SLOCCount comes with ABSOLUTELY NO WARRANTY, and you are welcome to
redistribute it under certain conditions as specified by the GNU GPL license;
see the documentation for details.
Please credit this data as "generated using David A. Wheeler's 'SLOCCount'."


I'm not sure what to think about this.
 
 
igor_nav
15 June 2009 @ 01:15 am
Ladies and gentlemen...

I will now attempt the impossible -- to walk you through the most confusing problem in all of mathematics. This infamous problem has confused millions of students and professors, sparked thousands of hour-long debates and netted me at least $20 in bet winnings. The Monty Hall problem is a famous paradox of probability theory. The intuitive solution is incorrect, and the correct solution is completely counter-intuitive. Most people refuse to believe the correct solution, rejecting it as some sort of a trick of the mind. But what really makes this problem amazing is that, unlike most math problems, it is entirely grounded in the real world. Instead of giving you a proof, I will give you a simple tool that you will be able to use to prove it for yourself.

...and then when you get it, I will turn the problem upside down and confuse you forever. Ready?

Behold: the Monty Hall problem

You are a contestant on a game show. The grand prize is a car, hidden behind one of 3 identical doors. Behind the other two doors are goats. You are a vegan, living in a Manhattan studio apartment, so winning a goat would be a highly undesirable outcome for you -- you want the car. The game show host, Monty, asks you to choose one of the doors. You do so. He then opens one of the other two doors, revealing a goat, and asks you whether you want to take the prize behind the original door of your choice, or whether you want to change your mind and win the prize behind the other unopened door. What should you do?

Most people say that it doesn't matter -- the chances are 50/50 between the two remaining doors. In fact, the correct answer is to change your mind and pick the door you have not chosen originally. This strategy gives you a 2/3 chance of winning the car. Unconvinced? No worries. Let me show you a simple trick.

"Any lock can be picked with a big enough hammer"

Instead of trying to convince you, I will give you a tool you can use to solve this problem yourself. What do most people mean when they say, "The probability of getting heads in a coin toss is 50%"? They mean that if you toss that coin many, many times, about half of the time it will come up heads. One way to verify this is to take a coin, toss it a thousand times and count occurrences of heads and tails. It's boring, but it works. Fortunately, in the 21st century, we have machines that can do such boring tasks for us.

Open up Google Spreadsheets or a copy of Excel, if you have it. Make a new spreadsheet with 4 columns -- let's call them "Door with the prize", "Player's first choice", "Monty opens" and "Should switch". Put these column names into cells A1, B1, C1 and D1, respectively. Go ahead, do it, really; it will be worth your time. Next, set the values of cells A2 through D2 as follows:

A2: =randbetween(1,3)

A random number between 1 and 3, inclusive. This is the number of the door behind which the car is.

B2: =randbetween(1,3)

Another random door number. This is the player's first choice.

C2: =if(mod(B2,3)=A2-1,6-A2-B2,mod(B2,3)+1)

This is the door Monty will open. The formula says that, of the two doors not picked by the player, if the first one contains the prize, Monty will open the second one. Otherwise, he will open the first one.

D2: =if(B2=A2,false,true)

If the player has picked the door with the prize, then switching is a good idea; otherwise, not.


Cell D2 will contain your answer -- true if you should change your mind; false if you should keep the door you picked originally. We have successfully simulated the game once.

Now comes the cool part. Select cells A2 through D2 with your mouse and drag the little "+" sign that appears at the bottom-right corner of the selection all the way down to cell D100. The selected cells will fill up with numbers, giving us the results of 99 independent simulations of the game and for each one, the answer to the main question -- "Should the player switch or not." You will notice that the word "TRUE" appears about twice as often as the word "FALSE". To get a precise count, put the following formula into cell E3: "=sum(D2:D100)/count(C2:C100)".

Here is my spreadsheet for doing this. I got 65.66% TRUE, which is just under 2/3. If you add more rows and fill them, you should get closer and closer to 66.67%.

Note that we didn't even use the values of column C to compute column D. That is not a mistake. The outcome of the game does not depend on which door Monty opens! Whether the player wins or loses depends only on the player's initial door choice.

Forgetful Monty Hall

It is time to make things weird. Let's change the game scenario a little bit. There are still three doors, one car and two goats, and you still get to choose the first door. But now, Monty has forgotten where the prize is! He knows he has to open one of the two remaining door, but he can't remember which one has the car. He is nervous; he is sweating. The show's producer is looking around the room in panic. Finally, Monty decides to take a wild guess and picks the door on the left. He opens it, and... whew! It's a goat. The show goes on. It's your turn to decide. Do you change your mind, or do you stick with your original decision?

You are probably thinking, "What's the difference?" What does it matter if Monty knows where the car is. The outcome is the same, right? He still opens a door with a goat behind it. Well, it turns out that in this case, it doesn't matter if the player switches or not -- the probability is 50/50. But you don't have to trust me. You have the tool to check it yourself -- simulation!

Let's start a new spreadsheet. This time, we will need 5 columns -- "Door with the prize", "Player's first choice", "Monty opens", "The show goes on" and "Should switch". Here are the formulae:

A2: =randbetween(1,3)

The prize is behind a random door.

B2: =randbetween(1,3)

The player picks the door at random initially.

C2: =mod(B2-1+randbetween(1,2),3)+1

Monty picks one of the other two doors at random.

D2: =if(A2=C2,false,true)

This is TRUE, unless Monty has opened the door that was hiding the prize. Since we know that this didn't happen, we ignore all rows that have value FALSE in this column.

E2: =if(A2=B2,false,true)

Same as before -- if the player has picked the door with the prize, then switching is a good idea.


Select cells A2 through E2 and drag the bottom-right corner of the selection down to cell E100.

Note that about 1/3 of the values in column D are FALSE. In my spreadsheet, I have marked them in gray. They correspond to scenarios where Monty has accidentally opened the prize door. The problem states that this is not the case, so we ignore all such rows. From the rows that remain, we count the fraction that have TRUE in column E. An easy way to do that is to type the following formula into cell D3: "=sum(filter(E2:E100, D2:D100))/sum(D2:D100)". Mine shows 45.16%. If we added more rows, that value would get closer and closer to 50%.

If Monty doesn't remember which door hides the car, then changing your mind and not changing your mind give you the same chances of winning the prize.

So where does Schrödinger's cat come into this?

Schrödinger's Cat is a famous paradox of quantum mechanics, where a cat can be simultaneously alive and dead, until an observer opens a box and looks inside. The act of observation seems to have a measurable effect on the physical world. I claim that the case of forgetful Monty Hall is similarly weird, if not more so.

Imagine you are a contestant on Monty's game show. You pick your door, and Monty opens one of the other ones, revealing a goat. He then offers you a chance to change your mind. You may open one of the two remaining doors and claim the prize behind it. To make things a little bit more interesting, Monty offers you an extra $100 if you do not change your mind and stick with your original choice of door.

At this point, you have to ask yourself -- did Monty know where the prize was, or did he just get lucky by opening the right door at random? How certain was he? Is he tired today and thus prone to forgetfulness? If Monty is perfectly lucid, then your door has the prize 33% of the time. If he is completely out of it, then your door has the prize 50% of the time. In reality, Monty is probably somewhere in the middle, depending on his age, how much sleep he got last night and how distracted he is by the cute girl playing against you. None of this is in your control, or has anything at all to do with you! I'm calling it "spooky probabilistic action at a distance".

If you think this is weird, look at it from Monty's point of view. If he knows where the prize is, he wins with probability 33%. If he doesn't, he wins half the time. Knowledge works against him! To be fair, that's not exactly true. It depends on what happens if he opens the door with the car behind it. If the punishment is getting fired from the show and ridiculed by all the TV viewers, then Monty definitely wants to know where the prize is. If instead the director simply yells "Cut!", closes the doors, shuffles the car and the goats, and we replay the round, then Monty would rather not know where the prize is. (Well, technically, he does want to know, and he would always intentionally open the door with the prize, unless you, the player, are holding that door, but then if you knew that that was Monty's strategy, you would never switch, unless... it gets complicated.)

The point is -- whether or not Monty knows something determines your optimal playing strategy.

How bad can this get?

Is there a situation where the mere fact of me knowing something would mean the differce between a 99%-good and a 99%-bad outcome for you? For starters, if you simply increase the number of doors to 100, (keeping the one car, but now requiring a sizeable herd of goats), then the 66.67% probability in the "Monty knows" case turns into a 99% probability. The "forgetful Monty" case remains at 50%. See, for example, my previous post about a 30-door version of the Monty Hall problem. Or else, you can make a tiny change to the spreadsheet and easily simulate the 100-door case yourself.

The homework question is -- can you devise a game where you win 99% of the time if I know something, and lose 99% of the time if I do not? It is tricky to understand what I mean here! Both scenarios must be exactly the same, up until the point where you have to make a critical decision. At that instant in time, your probability of winning must heavily depend on whether I know some particular fact. In the case of the 100-door Monty Hall problem, this difference in probabilities is 99%-50%. Can you make it 99%-1%?
 
 
igor_nav
12 June 2009 @ 07:33 pm
Step 1: Admit you have a problem

I like starting new projects. I have a bright idea; I work on it for a few days; I put together a prototype, an alpha version, something that works, but isn't quite ready for use by the general public; then I lose interest. For months afterwards, I come back to it, hoping to finish off that last 10%, but I never do. It always turns out to be more difficult than it should be. I'm very bad at finishing projects. On my computer, I have a directory called "projects" that keeps a pile of these "90%-finished" projects -- a JavaScript physics engine, a new game platform for Funny Farm-like games, a QBasic compiler, a whole new online Sokoban-like game and more.

A couple of weeks ago, I had another "bright idea" -- a website full of puzzles... "a house that the wealthy toymaker was to build. A strange house, a house that scared people..." The task looks fairly straitforward -- make a website similar to the UVa online judge or Sphere, only simpler and not targeted at computer programmers. It seemed like a couple of weeks worth of work that I could do on my free time. So I went into my "projects" directory and realized that I was about to repeat the same mistake.

How could I make sure this was not going to become another "90%-finished" project? I needed a way to track my progress, estimate the difficulty of each task and predict the time each task would take to get done. As reluctant as I was to admit it, I needed a project manager!

Step 2: Find the cheapest solution

I started having flashbacks of UML diagrams, flow charts and team meetings. Oh, the horror! I'm not doing any of that; not voluntarily! What is the minimum possible amout of boring non-programming work I could do to solve my organizational problem? What tools do I need? What fraction of my time should I spend organizing tasks? The problem didn't look too difficult. After all, I had no people to manage, no meetings to schedule and no deadlines to meet. All I had to do was ensure some minimum level of progress over time to prevent the project from freezing at the 90% mark.

Here is what I came up with. I wrote down a list of the features I wanted to have in version 1 and made a decision to release my first version as soon as those features were done. I ended up with a list of 8 features.


  • Home page

  • A page listing the puzzles

  • A page that displays a puzzle

  • An AJAX entry form for guesses

  • A ranklist of top puzzle solvers

  • Contests -- timed competitions

  • A way to create and join teams

  • A set of 5 puzzles to start with



As soon as I had these featuers completed, I would release the website to the public and let people play with it. That would give me a chance to fix bugs and get ideas about the set of features I should work on next. Writing down this list took about 10 minutes.

Next, I made a promise to myself that I would try to look at this list every day, or whenever I had at least 30 minutes to work on my project. Whenever I would look at the list, I had to perform one of the following actions.

  • Complete the top task on the list.

  • If the top task is not what I should be working on next, move that task down in the list.

  • If the top task is too difficult to complete in 30 minutes, remove it, split it into several smaller tasks and add those to the list instead.


The goal was to force myself to make some progress every single day.

I kept a progress indicator in my gTalk status message. It started at 0/8, but soon became 2/10, then 3/12, then 5/12, then 7/14. Both the numerator and the denominator were growing fast, as I contined to complete and divide tasks. I got to "50% done" in a couple of days. By the end of the first week, I was at 13/20 (65% done). After the second week, I was at 19/30 (63% done). I started getting smirky messages from my friends, confused by my negative 2% of progress on "whatever it is I'm working on". I was creating tasks at a faster rate than I was completing them. That is not surprising -- by that point, I started running out of easy tasks and started splitting difficult ones into a large number of smaller, easier pieces. I knew this trend had to end, so I was not worried about the "negative progress".

That is, until I hit a wall. The next task on my list was "A way to create an join teams". I wanted my users to log in with their individual user names and passwords. They would then be able to join teams with each other and solve puzzles together. I would compute team statistics (like the number of puzzles solved) and rank teams accordingly. I also had the great idea of automatically assigning users to certain fixed teams, like their "country team" or their "university team", which would give me a unified way of computing country and university rank lists.

This turned out to be very difficult to do in Google App Engine. I went through a number of designs and rejected all of them for various technical reasons. For 3 of 4 days in a row, I had made no progress. There was no way to split the difficult task into smaller pieces, and I could not find a good solution. I tried pushing it down the list and working on other tasks, but eventually I had to face the wall. Things looked bleak.

With no good solutions in mind, I gave myself two new abilities.

  • Remove a task from the list.

  • Add a new task to the list.


These could only be used in situations of crisis, like the one I was faced with. I decided to abandon the idea of teams and instead find other ways to promote cooperation among the puzzle solvers. I decided to add a forum, or a discussion board, and a page of generally useful puzzle solving hints and tools.

Similarly, I decided to let go of the idea of timed contests. Instead of forcing people to be logged in at a particular time on a particular day, I would instead promote a more casual, less competitive atmosphere. Competitions tend to alienate girls, and there is no reason to drive away half of my audience.

Another week went by, and I was at 30/34 tasks on my list. The remaining four were all easy and well-defined, and the website was beginning to look usable. I recruited a few of my friends to be alpha testers. They gave me some great ideas and bug reports that I turned into a few more tasks to be added to the list. After about a month of work, I was at 39/39! 100% done. Of course, there were lots of things I could improve, but a deal is a deal -- it was time to release version 1.

Step 3: Profit!

HenryStauf.com was born. I posted a link to the TopCoder forums and watched the little wave of requests coming in. The site looked ugly, and it had a few bugs, but it worked, and people seemed to enjoy my puzzles. In the weeks since then, I fixed a few bugs and added a few more puzzles. The task list is still growing, and I am going to make similar lists for some of my other unfinished projects.

What have I learned? Estimating the time required to complete a project is hard! Something that looks 90% done probably isn't. People tend to work on the easy parts first and leave the difficult parts until the end. Sometimes, you have to rethink your goals and re-prioritize your features. A tiny bit of bureaucracy helps. Project managers are useful, even when you only have one person on the team.

If you like finishing projects more than you like starting them, I envy you. If you are instead like me, try the task list method and let me know whether it works for you.
 
 
igor_nav
20 April 2009 @ 07:59 pm
If you know anything at all about probability theory, you know that playing the lottery is a bad idea -- your chances of winning are very low. Or more precisely, if the lottery ticket costs $10, then your expected winnings are less than $10. Even so, I'm going to convince you that it is mathematically optimal for you to play the lottery.

Imagine that all you have is $1000 in cash. That's it. This is your whole livelihood. Would you bet it all on a coin flip? If you win, you get $2000; if you lose, you lose everything! Of course you wouldn't. You would rather spend that money on food for the next few days, while you are looking for a job.

Imagine instead that you are a millionaire, and you enjoy playing poker. Would you agree to play poker with your friends for $1000? Let's say they are of a similar skill level as you are, and they are fun people to hang around. Will you play? Sure. Maybe. Why not? It's only $1000. It's only 0.1% of your net worth. Your expected winnings are about $0 (breaking even), and the fun you will have playing is definitely worth more than that.

The point I am trying to make is that the first $1000 in your bank account is worth much more to you than your most recently added $1000. The value of money, to you, decreases the more money you have. Mathematicians call this "utility". If you buy a couch on Craig's list for $20, then you want the couch more than you want the $20. The couch has higher utility for you. The person selling you the couch wants the $20 more than she wants the couch. The couch has lower utility for her. Both sides win (increase their total utility). That's why capitalism works -- there is always somebody who has what you want, and will trade it for stuff you need less. Utility is personal. Think of it as your quality of life.

Coming back to the money, it seems that the more money you have, the less is the utility of $1000 to you. If you are broke, you might agree to do somebody's taxes for $100. If you are rich, you probably won't. In fact, things are a bit more non-linear. Imagine if you had $X in your bank account, for various values of X from $0 up to $1 million. What would your quality of life be? With $0, it would suck. Let's call that zero quality of life. With $1 million, life would be pretty sweet. Let's call that 100 units of quality. There is some non-linear, increasing function that maps money in the bank to quality of life. If you had nothing, and somebody gave you $X, the blue curve shows what your quality of life would become.



There are some bumps around $10,000 (the price of a car) and $100,000 (the price of a down payment on a house). This function is not concave.

Now imagine you already have $10,000 in your bank account. How much would your life improve if somebody gave you $10? Very little. $100? Still very little. $1,000? A bit. $1 million? It would go all the way up to 100 units. The red curve shows your new quality of life after receiving $X once you already have $10,000.

So what does this have to do with playing the lottery? Let's say a lottery ticket costs $10, and it gives you a small chance to win $1 million. That chance is almost certainly smaller than 1/100,000; otherwise, the lottery organizers have made a terrible mistake. Let's say the chance is half that -- 1/200,000. Should you play the lottery?

In terms of maximizing your wealth, no, you shouldn't. Your expected winnings are -$5 (negative $5). But what about quality of life? That's a lot more important than money! It depends on how much money you have. Let's say it is $10,000. What is your expected gain in quality of life? If you lose, you lose $10, which is worth almost nothing. If you win, you can buy a house. Your quality of life jumps all the way up to above 100. It sounds like you should play! In fact, it makes sense to play whenever you find yourself in one of the convex parts of the utility function that is curved enough to compensate for the negative expected value of the lottery.

In simple terms, if you don't mind risking $10 to win an amount of money that is larger than you would be able to earn at work, then sometimes it makes financial sense to play the lottery.
 
 
igor_nav
08 April 2009 @ 05:40 pm
A few strange things have happened in the past few days in regards to the little game I had written a few years back.

First of all, I can proudly claim two successful hook-ups caused by the game. At least two pairs of people turned their mutual interest in Funny Farm into something more. I'm definitely building collaboration into all of my future games; it's just way too much fun to get emails from happy people thanking me for successful matchmaking. One more love-related surprise is in the works, but more on that later; I wouldn't want to spoil it.

Secondly, I got an email today from Amy Wilcox, a web analyst at Microsoft, asking me to lift the ban on MSNBot that I have in my robots.txt file. I can't believe my website matters enough in this world for somebody at Microsoft to spend the time to write me an email! The reason I had banned MSNBot from indexing my site is that they had a bug -- the bot was indexing restricted parts of my site, in blatant disregard of the rules in robots.txt. Well, not "blatant", to be precise. Even after I had completely banned MSNBot, about 480 of the 500 or so requests I would get from it would go to robots.txt, but the remaining 20 would crawl various pages on my website. So it was being sneaky, not blatant, which is even worse. Incompetence being more likely than malice, I bet they had a bug.

Looking through the logs today, it seems that the bug got fixed some time in June, 2008. I've had no illegal requests since then. Alright, Microsoft, peace. I'm lifting the ban. Let's see how much traffic I get from live.com this month.

Finally, I got an email from an online gambling website, asking to buy advertising space on Funny Farm and shygypsy.com. I've been running Google Ad Sense on Funny Farm for a few years, so I have a pretty good idea how much to charge for something like that. (It's not much.) It looked like an interesting experiment, and it would amount to 5 minutes of work for me, so I quoted them a price. Then it got weird.

I was worried that they would want Flash, or pop-ups, or maybe even javascript that would spread virii to my visitors, so I made it clear that only text and images would be acceptable. They said OK! Then they sent me a detailed email with screenshots of my pages and very inconspicuous text ads, or more precisely, sponsored links, inserted in some places. It turns out that they were not interested in clicks at all! They only wanted to increase their site's PageRank, and they were most interested in the Funny Farm page because of its "PageRank of 5". It turns out that there is a free PageRank checker online, and my game scores fairly high on it, which makes it valuable for other websites when I link to them from that page.

I looked up the PageRank of several popular websites:

Most annoyingly, my friend Igor O has a game with PageRank 6.

Long story short, pay-per-click and pay-per-impression ads are not the only way to make money from websites. If you have a popular page, search engine optimizers (SEOs) will pay you for links to their site.
 
 
igor_nav
06 April 2009 @ 05:32 pm
Everybody has gut reactions. Have a look at the following two yes/no questions and tell me whether your first impulse is to say yes or no. I'm curious if anyone can "feel" the right answer to both questions, without having to think about it.

Question #1: I give you a fair 6-sided die. You inspect and weigh it and agree that it is fair. You roll it three times, and it shows the number 6 every time. I bet $1 that it's going to be 6 again. Would you bet $4 against me? (If it comes up 6, you lose $4; if not, you win $1.)

Question #2: Award-winning research has shown that 4 out of 5 math students at the University of California in Sunnydale wear white socks. We walk into a UC Sunnydale math class and look at the sock colour of 10 students. They are all white. I bet $4 that the next student we check will also be wearing white socks. Would you bet $1 against me? (If they are white, you lose $1; if not, you win $4.)

While we are in a betting mood, how much would you bet that your answers are correct? Probability is hard...
 
 
igor_nav
02 April 2009 @ 11:28 pm
Do you know Java? The programming language. Do you know Java 1.5? If you think that you do, have a look at this puzzle.

Can you implement a class called Subsets that will work like this?
String[] set = new String[] { "A", "B", "C" };
for (String[] subset : Subsets.of(set)) {
  //...
}

The loop should run for 8 iterations, with subset having the values
{},
{ "A" },
{ "A", "B" },
{ "A", "B", "C" },
{ "A", "C" },
{ "B" },
{ "B", "C" }

and finally
{ "C" }

Of course, your code should work for arrays of other types as well, so the class definition will look like this.
import java.util.Iterator;

public class Subsets<T> implements Iterable<T[]> {

  public static <T> Subsets<T> of(T[] set) {
    return new Subsets<T>(set);
  }
  
  public Iterator<T[]> iterator() {
    return new SubsetIterator();
  }

  private final T[] set;

  private Subsets(T[] set) {
    this.set = set;
  }

  private class SubsetIterator implements Iterator<T[]> {

    public boolean hasNext() {
      //...
    }

    public T[] next() {
      //...
    }

    public void remove() {
      throw new UnsupportedOperationException();
    }
  }
}

All that remains to do is fill in the contents of hasNext() and next(). You will probably also need to add a private field or two to the SubsetIterator class.

Try it. Seriously. If you think you know Java, it will be a humbling experience. For bonus points, make your code compile without warnings in Java 1.5 or later. (Suppressing warnings is considered cheating.)

I'm hoping to see you post a solution that is more elegant than mine.
 
 
igor_nav
23 February 2009 @ 10:36 pm
They do. It's no secret. Whenever I buy anything online, I always dread that they will mail it with UPS. There are lots of ways in which UPS sucks -- from refusing to leave packages by the door, even when you ask them in writing, using their own form for such things,.. to charging exorbitant rates for doing you the service of paying customs charges for your package when it crosses the border.

I can rant forever, but that's not what this post is about. I wanted to see if other people shared my opinion of UPS, so I went to upssucks.com, only to find that the site does not exist. I couldn't believe it! Has UPS been picking on me alone all this time? Is everyone else a happy customer? Have they not yet annoyed anyone enough to make it worth the $10 it costs to register a domain name?

So I ran a WHOIS query on the upssucks.com domain name, and it is indeed registered. Guess by whom. By "United Parcel Service at 340 MacArthur Blvd in Mahwah, NJ 07430".

They know that they suck! In fact, back in 1997, they anticipated that they would suck, so they paid the $70 it cost back then to register the domain name. And they have been paying the fees to maintain possession of the domain name ever since. It's interesting to note that ups.com itself has been registered since 1992. So either UPS didn't suck for its first 5 years, or they just didn't know that they sucked.

United Parcel Service are also the proud owners of such prime internet real estate as upsblows.com and ihateups.com. That's some confidence in your service! Well done, UPS.
 
 
igor_nav
11 February 2009 @ 09:56 am
As you might know, a couple of years ago I made a little game, which became a lot more popular than I had ever expected. Ever since, it has been a never-ending learning experience in human psychology and online marketing, and it keeps going.

In an earlier post, I talked about the effect of social bookmarking sites like digg.com, fark.com and reddit.com. In short, each one brings an enormous flood of visitors, which is great if your service provider can handle it. But the flood recedes almost as quickly as it comes in -- almost all of them leave within a matter of hours. For this reason, webmasters don't like social bookmarking sites. These sites cause havoc on your site by bringing huge numbers of "low-quality" visitors.

If you have a small website or a blog, and you are looking to get some visitors, then social bookmarking sites might be exactly what you need. All you have to do is post something interesting, and the flood will come. Free marketing! Of course, like most free things, this is low quality marketing, but small websites are happy with any visitors they can get.

StumbleUpon.com is different though. It is a social bookmarking Firefox extension that lets you rate websites and suggests new ones for you to visit based on ones you have rated highly before. From the webmaster's point of view, StumbleUpon has a very different effect. The initial wave of visitors it brings is much smaller than that of Digg or Fark, but it keeps bringing visitors over a much longer period of time. At this point, 2.5 years after my game's launch day, StumbleUpon dwarfs every other website in terms of the number of visitors it brings. Google search is in second place, by a factor of 4, followed by a number of discussion forums.

I haven't done any in-depth analysis of the kind of visitors StumbleUpon brings -- how many are unique, how many are new, etc. It could be that the same people keep coming back by using their StumbleUpon toolbar as a bookmark (high-quality visitors), or it could be completely new people (new visitors). Either way, as a webmaster, I'm happy -- StumbleUpon is a much better marketing tool than any other social bookmarking site.
 
 
igor_nav
05 February 2009 @ 12:58 am
Seriously. I mean it. I know I've given up on religious debates, but this one is just so obvious! Heaven is said to be a place where everyone's desires are fulfilled, and no one is ever hungry or unhappy. If so, then what of bakers?

Imagine that you bake delicious bread for a living, and that feeding people makes you happy. You have perfected your recipe over the years, and now your bread is the best in the village. That brings you joy -- you have accomplished something. The other bakeries are scrambling to come up with better recipes than yours. They are experimenting with sourdough and sunflower seeds to carve out a corner of your bread eater market for themselves. You are in competition!

The next day, an alien space craft crash lands in town square, and the village is destroyed in a flaming tachyon-graviton reaction explosion. Everyone goes to heaven, where no one is hungry, and everyone in the village gets to eat any bread they wish at any time in any quantity. What are you and your baker friends going to do there? Nothing brings you more joy than making people happy by feeding them the best bread they've ever had. But if every one is always happy anyway, then what's the point? No matter how hard you work, or how exquisite your bread is, you will never make anyone any happier than they already are. After all, everyone is equally, maximally, absolutely happy in heaven. Your competition is over. Each of the bakers is equally a winner.

...or equally a loser. Your life's purpose is ruined. You have nothing to do. All you are left with is mindless self-indulgence. You stuff yourself with loaves of your bread for days, but you don't even gain weight. You stop eating, but you don't ever get hungry. You challenge the other bakers to an Iron Chef competition, but each of you gets perfect marks from each of the judges. Whatever you do, you cannot make any improvement to this world because the world is already perfect.

You have no other choice but to end your life. You suffocate on baking powder and go to hell. At least now you will have something to do with your life -- try to escape.
 
 
igor_nav
30 January 2009 @ 12:44 am
A fusion of Blade Runner, Donnie Darko, The Fifth Element, Fight Club, The Hitchhiker's Guide to the Galaxy, Kill Bill and Mulholland Drive, with a welcome pinch of original WTF thrown in. 5/5
 
 
igor_nav
04 November 2008 @ 10:04 pm
I stood on Times Square looking up at a giant TV screen.
And just as Obama was being pronounced the winner, three raindrops fell on me.
God was crying.

Edit: Damn it, Jon Stewart! Way to steal the joke I came up with today and use it in your show yesterday. That's just uncool.
 
 
igor_nav
24 July 2008 @ 10:36 pm
Here is an extension of a classic puzzle. It's very, very simple, but I can bet that many smart people will be royally confused for a long time. For the record, I do have a solution, and I can prove that it is correct. You've been warned. Enjoy.

You are a contestant on a game show. Howie Mandel is the host, and he shows you 30 suitcases. "One of these suitcases," he says, "contains $1,000,000. The other ones are all empty. Pick one." You pick a suitcase and hold on to it, but you cannot open it. Howie then opens one of the remaining 29 suitcases and shows you that it's empty! "Would you like to change your mind?" he asks. Now you may either keep holding on to the suitcase that you already have, or you may trade it for one of the unopened suitcases. After you have made up your mind, Howie opens another empty suitcase -- one of the 28 that you do not have. He then asks you again, "Would you like to change your mind?" This continues until there are only two suitcases left. You have one. Howie has the other. He asks you for the final time if you would like to change your mind. You make your selection, and your both open your suitcases. If you find the money, you get to keep it. If Howie has it, he keeps it, and you go home a loser. How would you play the game?

Note that Howie is sneaky -- he can choose where to put the money before the start of the game, and he is playing against you.

My only hint is: don't trust anyone who tells you that they know the answer. That answer is probably wrong. (Except mine, of course. Mine is right.)
 
 
igor_nav
24 June 2008 @ 10:07 pm
The language, not the island or the coffee.

Today, I needed to find a bug in some Java code. It was written by somebody else, and I suspected that the bug was in that code rather than in the way I was using it. The suspected method was 20 lines long, so I started there. I ended up having to open ten different files (I counted) and read through 15 different classes, most of them abstract, until I found a single line of code that actually did something. The rest of that code was entirely declarative - abstract classes, interfaces on top of interfaces, factories, collection classes with generics, abstract visitors implementing inherited interfaces, and a whole lot of other stuff that, functionally, did absolutely nothing! Hundreds of lines of "self-documenting" code. By "self-documenting" I mean that it had no useful comments - only JavaDoc of the form "inherits from X" and "overrides Y".

After spending most of the day, I still don't have a solid lead on exactly where the bug is. And I'm not a total n00b; I have a few years of programming experience, a couple of them writing Java. What happened to this language that started out like such a breath of fresh air? I have seen this trend brewing for quite some time now - Java being suffocated by design pattern fanatics.

Back in the days of version 1.4, Java used to be "the language that C++ should have been". It had a clean syntax, incredibly useful, well-designed libraries and a virtual machine that was getting fast enough to compete with C++ in most situations. I turn away for a couple of years and it has become the Clearwater, FL of programming languages - overtaken by a cult of Design Patterns.

There is nothing wrong with design patterns as an idea. (Just like there is nothing wrong with Communism, in theory.) The problem starts when design patterns become the absolute truth, to be used for every purpose, whether they are needed or not. I consider object-oriented programming as a whole to be a design pattern, just like functional and imperative programming are. They are ways of structuring and organizing code that make it easier to achieve a particular goal - readability, maintainability, testability, etc.

Like in everything else, moderation is key. Java is turning from a programming language into a software engineering language, and I mean that as a derogatory term. Is there still hope to save it, or is switching to Python humanity's only chance?
 
 
igor_nav
31 May 2008 @ 04:02 pm
Today I bought a new car. That was a perfect opportunity to test out the ideas taught by Michael Badnarik in his class on the constitution. In short, he claims that every new car is (co-)owned by the government, and the car "title" does not denote the owner of the car, only the person who is allowed to use it. The real document that determines ownership is the "Manufacturer's Statement of Origin" (MSO), which the car dealership mails to the Department of Motor Vehicles (DMV) in the process of getting the title. Some people claim to have been able to get the MSO from the dealership and hence remained the sole owner of their cars, avoiding the need to get (and pay for) the title.

I asked my car dealership about it, and they were very surprised. Apparently, no one had ever even asked them about the MSO before, but they had no objection to giving it to me. However, they could not do it today, and the salesman at the dealership had no idea why I would want to get myself into all the trouble with the DMV - I couldn't have both the MSO and the title. That was enough to satisfy my curiosity, so I left it at that, but it does look like you could get the MSO fairly easily when buying a new car. Of course, good luck explaining to the next traffic officer why you do not have a title for your car and that you don't need one because you have this other document instead.
 
 
igor_nav
10 May 2008 @ 04:28 pm
Here is my next entry in the series of posts on complicated conversations with random people. This one took place at a gas station in Santa Clara, CA. An elderly Philippine woman approached and offered me a little pamphlet titled "Who really rules the world". I said, "Thank you, but I already know who rules the world." Then I noticed the pamphlet in her other hand. It was a copy of something I had seen a few times before - the "Watchtower". So I asked her if she was a Jehovah's Witness. She said yes, and I asked how she felt about her church's policy against blood transfusions.

A couple of questions later, she realized that she needed backup and called on her granddaughter Irene, who took over for her at that point. The rest of the conversation was fairly standard. I started off with the blood transfusion and political non-involvement questions and then we spent over an hour and a half talking about the authenticity, independent authority and infallibility of the Bible. Good thing the gas station was almost empty. Irene was a pro; dodging all my questions with careful applications of the Rule of Selective Metaphor, the Axiom of Self-Evident Truth and the Principle of Avoiding the Question by Quoting a Random Biblical Passage - the standard tools of any well-trained Jehovah's Witness.

There was one memorable moment though, which I will quote below. I told Irene that whenever I would try to read the Bible, I would always come away very confused. Everything in that book was up to interpretation. So I asked her, "How do you know what the correct interpretation is?" She looked at my Google t-shirt and said:

Irene: "You are a programmer, right?"
Me: "Yes."
Irene: "You use C, right?"
ME: "Sure, sometimes."
Irene: "Suppose that you don't know what polymorphism is. How would you find out?"

I kid you not. Even the Jehovah's Witnesses in the Silicon Valley know programming language design principles.

It turned out that Irene worked in the IT department at a bank. (I won't say which one.) She has been a Jehovah's Witness since 1984, which explains her mastery of the art of the illogical argument. It was a fun conversation overall, and I learned a few things about human psychology, even though Irene did stoop to saying the following when I mentioned evolution: "Well, let's see you lock an ape in a cage and see it turn into a human."
 
 
igor_nav
Have you heard the terms "Desktop Linux" or "Linux on the desktop"? They keep popping up in news articles and blog postings (like this one). The question is - is Linux ready to replace Windows for average desktop users? You can tell from the post's title that I'm about to take a side in this debate, but first, have a look at the following wonderful, unbiased, scientific article. It is titled "The Great Ubuntu-Girlfriend Experiment", and if you are interested in how far Linux has come, you should read it. It describes a set of common tasks and how an "average computer user" dealt with each one using a Linux OS. If you are incredibly lazy, let me summarize - the experiment went rather badly. It wasn't a disaster, but it was certainly painful enough to turn the vast majority of average first-time users off of Linux and back to Windows.

On the bright side, the author points out that each of the usability hurdles could be overcome if only the developers made it a priority to make their software easy to use for average Windows users. However, that is something that, in my opinion, cannot happen. That's my first point. My second point is that this is a Good Thing.

Open source software is written by programmers (obviously). What's more important is that open source software is designed by programmers, usually pretty good ones. These people spend a great deal of their free time and do not expect to be paid for this work. Why would they do that?! Usually, this is because they are unhappy with the software that is out there, so they say: "Screw it! I can do better than this." "All the instant messengers are broken. Here is what a better one should look like." So they start a little pet project. They get it to the point when it is useful, to them, and they feel good. If enough of their (programmer) friends find it useful, too, the project grows and gets more features. Eventually, if it's a good project, there will be a lot of programmers using and improving it. The best projects have very good programmers working on them, designing them and adding features.

The problem is that good programmers are very weird people. Unlike most humans, they are logical. They value simplicity and symmetry, and they abhor exceptions and inconsistencies. When choosing among several possible designs, they will pick the simpler one, the one with fewer rules and fewer exceptions. They spend their life telling computers what to do, so they like it when computers do exactly as they are told, without trying to infer what the user might have meant. So they will design a user interface that is logically correct, rather than one that second-guesses the user. That's why the OpenOffice.org Drawing program's "Save As..." menu does not have PNG or JPEG as an available format. Those are in the "Export" menu because they cannot be used to save a vector graphic without rasterizing it first. That's why there is no "File Type" option in the file search dialog when you can already search using a regular expression.

These design decisions are here to stay for as long as computer programmers are designing the software.

The Microsoft Office user interface is not designed by programmers, and it is not modified in response to feedback from programmers. It is designed to please average Office users. That's why the users love it. And that's why programmers hate it.

That brings me to my second point. I hope that things stay the way they are. I hope that Linux remains difficult to use for average users because the price is a sacrifice in clarity, precision and logic. I don't see the great appeal of making Linux universally accessible on the desktop. I would much rather keep PNG out of the "Save As..." menu and the translucent, "user-friendly" pop-up bubbles in the bottom-right corner of Vista, where they belong. Why do people feel the need for another Windows? The Windows users are happy. The Linux users are happy. (The Mac users are nauseatingly ecstatic!) Switching from one camp to the other requires a paradigm shift. That's a good thing. Different options are a good thing. Leave it alone.

PS. For extra evidence that open source software is not likely to change its user interface design, have a look at this incredibly arrogant, but painfully accurate portrait of a good programmer, by Eric Raymond. It's a very honest look at the way open source programmers think, and I believe that it illustrates my points beautifully.
 
 
igor_nav
Inlaws. Outlaws.

Edit: A couple of greps and a join later, I also found...
Income. Outcome.
Onset. Offset.
Upright. Downright.
but these aren't as cute.

If you know where I can get a good list of words, please tell me. /usr/share/dict/words is missing some very basic ones (like "inlaws").

Edit 2: With the help of the Scrabble dictionary and after playing around with lots of common prefixes (like on-off, up-down, him-her, he-she, you-me), I've stumbled upon a few more gems:
Youth. Meth.
Hell. Shell.
Chickened. Egged.
 
 
igor_nav
07 February 2008 @ 01:45 pm
As a follow-up to my yesterday's post, have a look at this scary story of US customs confiscating laptops at the airport.
 
 
 
 

Advertisement

Customize