Recently in Misc Category

Counting Unique Digits

Here's a way to count the unique digits in a number using a mostly functional style. There's an API method, count_unique_digits:

def count_unique_digits(n)
  if n < 0
    raise Exception.new("can only handle numbers >= 0")
  end
  return count_unique_digits_iter([], 0, n)
end

This calls the main method, count_unique_digits_iter. This is recursive, passing intermediate results as parameters to itself.

def count_unique_digits_iter(num_array, count, n)
  new_digit = n % 10
  new_digit_unique = ! num_array.include?(new_digit)
  increment = new_digit_unique ? 1 : 0
  if n < 10
    return count + increment
  end
  if new_digit_unique
    num_array.push(new_digit)
  end
  return count_unique_digits_iter(num_array, count + increment, n/10)
end

Given the methods, here's a method to count how often digits repeat in all the integers in a range:

def build_count_map(range)
  count_map = Hash.new(0)
  for i in range
    old_count = count_map[count_unique_digits(i)]
    count_map[count_unique_digits(i)] = old_count.succ
  end
  count_map
end

This counts all the digit repetitions of four digit numbers

count_map = build_count_map(1000 .. 9999)
for count in count_map.keys.sort
  print "#{count}: #{count_map[count]}\n"
end

And here's the output:

1: 9
2: 567
3: 3888
4: 4536

(In the first version of this post, I omitted the unit tests.) Instead of a test framework, I used a homebrew checking method:

def check_method(method, input, expected)
  if self.send(method, input) != expected
    raise Exception.new("#{method}(#{input}):\n" +
      "expected " + expected.inspect +
      " but got " + self.send(method, input).inspect + "\n")
  end
end

Which made it easy to plug in tests for count_unique_digits

def check_digits(input, expected)
  check_method(:count_unique_digits, input, expected)
end

check_digits(0, 1)
check_digits(1, 1)
check_digits(10, 2)
check_digits(11, 1)
check_digits(123, 3)
check_digits(999, 1)
check_digits(1000, 2)

and tests for build_count_map

def check_count_map(input, expected)
  check_method(:build_count_map, input, expected)
end

check_count_map(0 .. 0, {1 => 1})
check_count_map(0 .. 1, {1 => 2})
check_count_map(10 .. 20, {1 => 1, 2 => 10}) # only 11 has no repeated digits
check_count_map(10 .. 99, {1 => 9, 2 => 81}) # 11, 22, 33, ..., 99 are the doubles

How CEOs Can Create Shareholder Value

| No Comments

As seen in the news: Carly Fiorina finally creates some shareholder value by resigning. The value of HP went up by about $5 billion as a result.

Reminds me of this, from September 2003: Motorola CEO Resigns; Five Analysts Issue Upgrades (MOT, 12.06, up 0.97).

After Chris Galvin resigned, Motorola finally spun off its semiconductor division, like Wall St had been demanding for years. MOT subsequently rose to over $20 (albeit mostly because of improvements in the cell phone business).

No matter how unpopular CEOs are among the rank and file, when they go it's because Wall Street doesn't like them.

Privacy and Context

| 2 Comments
Via Esther Dyson, a ramble by Michael Sippey on e-mail, RSS, weblogs and so on. I'm not sure I need to be able to do everything in one piece of software. (I'm tempted to label this the Mozilla fallacy.) In different contexts, I'm comfortable using different tools. When it comes to privacy, I need to maintain a separation between work and non-work. That runs both ways: I don't want (confidential) information from work to leak to my private sphere any more than I would want it the other way around.

So Little Time...

| No Comments

Today is a payday for me. I was pondering about how much time I spend at work.

In my head I figure it's a little over 50 * 40 hours. Wait, that's only a little 2,000 hours a year, that can't be right!

I ran a calculator and checked 366 * 24. That works out to be only 8,784.

Those numbers seem shockingly low to me. In a whole year I don't even have 9,000 measly hours?!? I know they say ars longa, vita brevis but I didn't realise it was that brief.

Word of the Day: Fraught

| No Comments

I wish I had had a etymological dictionary when I was in school. Dictionaries that only give you the spelling and definitions leave out so much. The roots and relatives of words colour their meaning.

Fraught is related to freight and the German verb frachten. It does seem to have Germanic rather than Romance roots.

The dict.org definitions come with a highly relevant example: words fraught with meaning. It really conveys the sense of being burdened or laden and heavy.

By the way, there is a site that really does a word a day. I'm just stealing the idea for today.

Outsourcing Creates New Jobs

| No Comments

Well, this is certainly interesting. A new study concludes that the U.S. economy has much to gain from global sourcing.

The gains are not only in real incomes (partly because of lower inflation) but also in jobs.

While offshore outsourcing has and will continue to displace workers in the IT software and services profession, the positive gains to the economy, as a whole, will stimulate job creation throughout the economy. The overall gain is positive: an estimated 193,900 new jobs were created in 2003 and over 589,000 new jobs are expected by 2008, if offshore ITO continues. These estimates include both IT and non-IT jobs. After accounting for the number of displaced IT software and services jobs, the net number of new jobs in 2003 was estimated to be over 90,000, and the net number of new jobs in 2008 is expected to be over 317,000.

One big caveat: the study was commissioned by the Information Technology Association of America (ITAA), a trade body and hardly disinterested in the results.

The ITAA, not surprisingly, wants government to help out: it should

Consider offering assistance to service workers similar to that offered manufacturing workers, in a variety of forms, including skills training (and compensation during the training period) [...]

[ Found via KeepMedia's RSS feed. ]

Update: Sure enough, it looks like the report needs to be taken with more than a grain of salt. Max Sawicky is seriously annoyed and Calpundit, errr, Kevin Drum thinks skepticism is warranted:

You probably shouldn't take these kinds of reports very seriously unless someone you trust gives you a good reason, and you should never take them seriously based only on their press release. Caveat emptor.

Leaving Cert Nightmares

| No Comments

Maria over at Crooked Timber writes about her recurring dream: having to sit the Leaving Cert again. It's more properly called a nightmare, particularly because she's faced with the dreaded Honours Maths exam.

Judging by the rest of Maria's entry, girls really did have it worse than boys. She compares herself to the Magdalene Sisters and it's only a little over the top.

As for the Maths, the link she gives shows the worst of it: integration. The questions on the paper were a form of intimidation through minimalism. Integrate this.

On the the other Leaving Cert subjects , they deliberately left calculus out of the curriculum, which made physics (in particular) and economics easy. (One exception I remember: there was an easy proof of Gauss's Law you could use that involved just a smidgen of calculus.) The Leaving Cert is one where choosing which questions to answer is among the most important skills. The strategy for physics and (especially) economics was to do the most mathematical questions. That way you eliminated as much subjectivity in the marking as possible: if you got the right answer you'd get 100% of possible marks. Essay questions always carried the risk that an examiner might not like your style of writing.

That risk applied for me even in subjects that had no mathematical content. I don't think I wrote one essay for English in my last two years of school. I got a D in the exam. I suppose it's only fair, but that result is the only one that bothers me.

On the subject of Magdalene Sisters... I went to a boarding school. Our laundry was done at a convent. I now know that means it was probably done by fallen women who were shunted into that occupation for having children out of wedlock.

As their punishment they were washing the soiled clothes and bedclothes of hormone-addled teenage boys.

There was worse. Ann Lovett died twenty years ago while giving birth alone in a grotto Co. Longford. She was fifteen. To this day no one knows who the father was or how it could have happened.

And yet a generation of us made it past the Leaving Cert. We grew up and in some ways the whole country grew up. Surely there can never be another referendum like the one in 1983 again. But is it any wonder that people have uneasy dreams about the period.

The Irrationality of Investors

| No Comments

Found through the Efficient Frontier web site: a presentation saying that people tend to make a lot of mistakes when they invest. People are overconfident about their abilities; they trade too much; they choose stocks based on what's making the news and what did well last year.

Supposedly, men suffer more from the overconfidence syndrome than women. Hmmm...

I know I'm probably as guilty as anyone. I am inclined to the contrarian approach, so I like to sell short. Incredibly, I've lost money on this. I've even lost money shorting dot-com companies that don't make money. To make it worse, I hate to cover shorts that are losing me money.

Fortunately, I'm most of my savings are out of my own control, in 401k retirement accounts and the like, where I only get to select the funds. That part of my savings has done much better overall than the part that I control myself. Diversified index funds are the way to go.

Having said that, I think the stock market is overvalued and I cannot resist looking for a chance to short.

Back to Workaday Life

| No Comments

Dave Pollard has a piece about saving time for bloggers. It's a reminder that I'm back in a place where time is in short supply and needs to be rationed.

During my vacation I slept nine hours or more most nights. I would idle the evening away in the living room, hanging out with family under the guise of watching television or playing cards, going to bed between midnight and one o'clock and sleep until 10:30 or so the following morning. Apart from a visa appointment at the embassy at 8:30 early on during my trip I had no pressing commitments. After the 23rd most museums and other places S. would want to see were closed anyway.

Coming back, it's hard to adapt the Taylorist mindset required to rouse myself from sleep out the door to catch a bus in less than an hour. For the moment, I'm still going to bed long before ten at night, so it's relatively easy to wake up at 6:30 and take an hour and a half. It doesn't feel as if I am slacking — I'm just not being ruthless about doing only what needs to be done in the shortest way possible.

It's enough to make you want to curse whoever invented agriculture and the associated evils of civilization and long for the existance of noble hunter-gatherers, who could do anything they wanted after they had got enough food to subsist. It's a myth, I know, but so attractive.

The Joys of a Digital Camera

S's parents gave us a digital camera for Christmas with the understanding that we would provide them with plenty of shots from our trip to Ireland. We just got back so I have spent most of the afternoon getting the pictures from the camera to my ISP's web server.

The camera is a Canon PowerShot A70. Neither of us is more than a point-and-shoot photographer, but it took good pictures even under fairly challenging conditions (high contrast, low light, that kind of thing). My Linux box is the only computer in the house with USB ports, so I paid a visit to Peter Toft's Linux / A70 Howto page.

My system is a little different to his: I am using SUSE 8.0 and he was using Mandrake. I found that digikam crashed when trying to load pictures from the camera. So did gphoto2, apparently at places where pictures had been erased from the camera.

I was eventually able to get gphoto2 to work. I downloaded, compiled and installed a more recent version of libgphoto2 (version 2.1.3 to be exact). With that change, gphoto2 loaded all the pictures from the camera. It still does not recognize the camera, so Peter Toft's workaround is still required:

gphoto2 --usbid 0x4a9:0x3073=0x4a9:0x3056 --camera "Canon PowerShot S40" -P

I used ImageMagick as described in an earlier entry to massage the photos a bit. (There is one additional step: the photos from the A70 are 3.2 megapixels, so the pictures need to be halved in size before they can be viewed on screen all at once.) The results can be seen at my ISP (for those who are interested).