Generating random numbers in Cocoa

I’m writing an application to pick prize winners for the RubyNation conference that’s coming up here in the Washington DC area. As part of that, I have to generate random numbers. So I went looking for how to generate random numbers in Cocoa. I was looking for something reasonably fast, built-in to Mac OS X, had an easy to use API, and had the most randomness. I defined a random number generation algorithm as being more random if it had a larger range of numbers that it could generate.

The basic usage of a random number generator is something like this:

  1. Seed (initialize) the random number generator
  2. Generate a random number
  3. Modulo the random number against your maximum number to get a number from 0 to your maximum number – 1.

Alright, first off I looked for Objective-C libraries. You know, maybe there was an NSRandom or something like that. There isn’t really one, so I went to look for C functions instead.

Digging into my memory banks, I remembered from my early C days that the standard C library call is srand() with a seed to initialize and then rand() to get the random number. So I looked up srand in the Apple Developer Connection (also known as ADC)
and came up with the laughable description:

rand, rand_r, srand, sranddev — bad random number generator

These interfaces are obsoleted by random(3).

Alright, so onto random. I looked up random in the ADC to see its Mac OS X Manual page. Alright, so it can generate numbers from 0 to (2**31) – 1. You can seed it with srandom() – which could be useful because the same seed will generate the same sequence of random numbers – useful for replaying a game sequence. A better seeding is to use srandomdev() which creates a state array which can’t be guessed by attackers and effectively uses the /dev/random device.

OK that seemed pretty good, but I read on and found this intriguing line:

Applications requiring cryptographic quality randomness should use arc4random(3).

Alright, so now I look up arc4random on ADC. arc4random uses the Alleged RC4 cipher, hence the ARC4. It has a range of 0 to (2**32 – 1), which is twice the range of random. It uses the /dev/urandom device. And best of all, in my opinion, it doesn’t require seeding/initializing since it initializes itself.

So the winner in my book for generating random numbers in Cocoa (really any Objective-C or C program on Mac OS X) is arc4random.

RubyNation – a Ruby conference in the Washington, DC area

I’m proud to say that we are going to have our very own Ruby conference here in the Washington, DC area! It is called RubyNation and it will be happening on August 1 – 2, 2008 at the Center of Innovative Technology in Herndon, VA. That’s probably one of the strangest shaped buildings in our area that should be hard to miss – it sort of looks like a squarish ruby with its point up.

We’ve lined up Stu Halloway, Neal Ford, David Bock, and Giles Bowkett as keynote speakers and we’ll have lots of Ruby content. I think it will be single track which is my preferred format – fewer things to think about. Plus, if you’ve got something cool you’ve been working on, you can present them during the lightning talks!

I hope to see you there!

The closing Jimnote at MountainWest RubyConf

Many of us call the opening keynote of WWDC by Steve Jobs the Stevenote. Well I’m dubbing the closing keynote of MountainWest RubyConf the Jimnote in honor of Jim Weirich. But… maybe I’m too late. It was sort of like watching a Mike Tyson fight (back when he was his prime and KOing people in 90 seconds.)

Jim gets up, tells us that this is the most important thing that programmers should know and brings up three slides:


do it


and sits down.

OK – here he comes and more fired up than ever.

A brief tutorial on LISP.

syntax: s-expressions (s-exps), atoms, lists

nil is the same as empty list

functions: car == head, cdr == tail (trivia: car is address register, cdr is decrement register), cons, eq, atom

special forms: cond, lambda

LISP is turing complete with just this small set of rules.

Now we go into a discussion of how Jim solved the problem of showing the same graphics between an 8-bit memory-mapped 8080-based computer and a 16-bit vector-based PDP11. The answer: FORTH.

FORTH “words” (like Ruby methods) were very short and FORTH itself used reverse polish notation (RPN.) Jim learned about factoring properly this way. To port FORTH all Jim needed to do was write some primitive words (aka graphics drivers.) Note that Jim says that Nintendo console games were written in FORTH.

UDFs – now we’re looking at unducted fans engines which has spinning blades which would pull in air into the engine but did not succeed.

But… designing these engines was an interesting gig. It did involved multiple threads that access shared data. Which is a huge headache. Perhaps a way to help with this would be to avoid system locks but this worked out to one chance in a million of failure. Which seems like good chances, but it failed roughly once a day (since it executed roughly 1.5 million times a day). The point is that writing threaded applications is hard especially when accessing shared modifiable data.

Which brings us to Erlang…

There’s four types: Atoms, Variables, Tuples, and Lists. Hmm I think I see how this starts to form a Moebius strip.

You can’t change a variable once its assigned, which is actually pattern matching. I would call this immutable data. I use immutable data when passing objects between threads in my Cocoa apps.

Then we go into a client/server example in Erlang and it starts to remind me of Cocoa’s Distributed Objects.

In Ruby you send messages to objects and in Erlang you send messages to processes.

We’ve come up with really complicated systems. Jim shows a code example with 6 different languages/frameworks in one html snippet that shows HTML, CSS, Java, JSP, taglib, and JavaScript.

Erlang in comparison is simple, powerful and spawns processes quickly. Ockham might have approved.

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” – Tony Hoare

We live in a (programming/business/consumer?) society that values complexity. In the Ruby world, we’ve come up with Camping, Merb, and Rubinius.

So in summary: Simplify.

  1. Small core.
  2. Simple rules.
  3. Powerful abstractions.

Follow-up question: Where do you draw the line between simplicity and metaprogramming? Answer: If it solves a problem you’re having, go ahead and metaprogram – as long as its a significant amount (more than one line or so.)

2007 Training in Review

Last year I took a lot of training. In the past, my employers would usually send me to one training event. Sometimes I would get to go to two if times were good. Other times, there was no training budget.

In 2007, I was self-employed as the sole member of Happy Apps LLC. So being in charge of the training budget (well actually the entire budget), I went to six training events:

  1. Rails Edge in Reston, VA
  2. Advanced Rails in Chicago, IL
  3. WWDC in San Francisco, CA
  4. RailsConf in Portland, OR
  5. Advanced Ruby in Reston, VA
  6. RubyConf in Charlotte, NC

So that’s 2 Ruby conferences, 3 Rails conferences, and one Cocoa conference. I actually was scheduled to go to another Cocoa conference, C4[1] over in Chicago, but had to cancel due to personal reasons.

So which ones were good and which ones were bad? I think they were all quite good. Obviously, if you want to make Mac applications like I do with WebnoteHappy, you’ll want to go WWDC.

In terms of being a good Ruby on Rails developer, I’d have to say that assuming that you already have a good background in object-oriented programming and web development, have worked through a beginning Rails book like Agile Web Development with Rails, then you really should take both the Advanced Ruby course by Pragmatic Studio, followed by the Advanced Rails course. Both taught me quite a lot of things that I hadn’t known before.

Once you’ve got that though, I think its important to keep up with the latest in techniques and also be involved in your programming community. I think The Rails Edge Conference is top notch in keeping up with what’s new in the Rails world. I hope that a date is announced soon though – I don’t see one for 2008 as of today.

RailsConf is also good for keeping up with Rails, but I think is maybe even better for just being involved in the Rails community. There were a lot of opportunities, scheduled and unscheduled, to get together with fellow RoR developers and you could sense that Rails is really changing the way that web development is being done.

RubyConf on the other hand reminded me that Ruby is not just about Rails. There’s certainly been a lot of growth of Ruby use because of Rails, but there is a deep and wide pool of talent that has fallen in love with Ruby. It was interesting to see all the different uses that people have made of Ruby. And it was definitely an honor and a pleasure to meet Matz in person. In the end, it does seem like most people who are doing Ruby full-time are making their money with Rails.

I’m trying to plan out my training in 2008 now. So I’m curious to hear what good conferences or classes other people went to in 2007. Also if there were any bad ones.

RailsConf 2006 registration is open and selling fast

RailsConf 2006 is the first conference for Rails. It’s capped at 400 participants and there were already 100+ people who signed up by Thursday the 2nd of February 12 hours after it opened!

I would like to go, but my spare time other than my Eclipse work during the day and spending time with my family is all taken up doing Cocoa apps on the Mac. Also my “invest in my technical knowledge” conference money is already spent on EclipseCon for Eclipse (paid by the company I do Eclipse work for) and WWDC for Cocoa (paid for myself).

It’s taking place in Chicago, IL from June 22 to June 25. If you register before Feb 28th, it is $400. That’s pretty cheap for a conference. By comparison, EclipseCon ranges from $925 without tutorials to $1450 with tutorials. These are the early bird prices which means you have to register before February 15th. Member company employees and Committers get a discount. WWDC is the pricest of the three I’ve mentioned, with last years WWDC coming in at $1595. Of course, WWDC is 5 days compared to the others which are only 4. And WWDC has a Steve-note at the beginning plus a visit to the Apple campus which is probably worth a good chunk of change right there. :)

WWDC 2005 Recap

WWDC was great. It was my first time attending and will probably not be my last. At first it was a bit intimidating, especially with the huge crowds waiting to get into the Keynote. But after a while, I really felt… at home. Like these were my people. How many places does every other person have a PowerBook? Where can you wander the halls and chat with any random person about Macs?

There was a lot of good content too. I couldn’t attend all the ones I wanted to go to, but hopefully the DVDs will come out soon and I can watch all the ones I missed. Like David, a fellow Mac developer from the DC area said “I felt like a kid in the candy store” when I looked at the conference schedule. But as good as the content was, meeting the people there was even better.

It felt kind of like a reunion of sorts. I met all these folks whom I had some contact with from all these different contexts, mostly Mac-related. It was great to go to the MacSB and Blogger Dinner on Monday. Thanks Mike and Buzz for setting those up! I only wish there were more small group meetings like that at conferences. I managed to find several East Coast developers at WWDC and at the airport. I also met a bunch of Apple folks including Andrew (thanks for the new Subversion on Tiger post) and bbum.

WWDC 2005 Keynote Revisited

As everyone on the planet and their mother knows by now, Apple is officially stopping the use of PowerPC chips and will phase them out over the next 2 years. They will be going with the 800lb Gorilla of the Chip Market: Intel.

Some people, OK, a lot of people on their blogs have questioned this move, but here’s my take on it. Just to let you know, I am an Eclipse on Mac programmer by day and a Cocoa on Mac programmer by night. I use a PowerBook G4 mainly and I’ve got a Mac mini and a decommissioned generic Pentium II at home. And I’ve seen change…

…But this was huge.

When I walked into the room where the Keynote was, there were speakers blaring and it seemed more like a concert than a conference. U2 and all the techno from the iPod ads was shaking the room. Everything seemed larger than life. There were ushers trying to find room for everyone and I got a seat about 10 rows back, all the way to the right. The lighting was top notch, with big glowing Apple logos floating above the stage.

So Steve Jobs steps out and the crowd goes crazy. Some guy yells out “Steve, we love you!” I’m guessing if Steve were to jump out in the crowd, he could probably surf it. But he seemed to have something on his mind. And we had something on our mind. We had seen the TV crews outside and all the rumors and news reports over the weekend. Honestly, I think most of us wanted it not to be true.

Steve went over how the user base was growing, the retail stores were growing (with a great little movie about it), how the developer base was growing, how attendance at WWDC was the highest in a decade, and how iPod and iTunes is this huge digital music juggernaut. So we were pretty pumped. There was going to be 2 million copies of Tiger shipped soon. I thought about how Spotlight was a partial fulfillment of Jef Raskin’s dream to not have to remember where you put a file or what you named it.

Then the bomb dropped.

It seemed like time was standing still. Or that the all the air had gone out of the room. It was surreal. But it was true. Steve gave the official answer that the performance per watt projected into the future spelled the effective end of the AIM alliance. (That was Apple, IBM, and Motorola.) Basically, by mid 2006, Intel would be over 4 times as powerful as the PowerPC chips per watt. This seems like a huge difference especially as more people buy laptops instead of desktops. We’re still waiting on the dual 3.0Ghz G5 desktop and the PowerBook G5. And not being able to deliver those were two big straws on a camel that was straining to stand.

You might think that this seems like a bad move because there will be a lot of volume in the Power line soon. Yes, Sony, Microsoft, and Nintendo all run Power, but they are all customized versions of Power. So PowerPC wouldn’t get all the volume from the game consoles because they are effectively four different lines of chips: one for Apple, one for Sony, one for Microsoft, one for Nintendo. This is all good for IBM chip manufacturing, but it wouldn’t have helped Apple.

After the initial shock came some comforting news: Apple had a plan B all along. I think they got this from NeXT, which had ported OpenStep to a variety of platforms. Apple had been running OS X on Intel for the past 5 years (which is when OS X came out.) I wonder if they have it running on any other platforms.

Then came the big surprise ending: Steve had been running his presentation on a copy of OS X on a Pentium 4 the entire time!

OK, so what does that mean for us Mac developers?

Well, a lot of us won’t have to do much. Java programmers won’t have to do anything. I guess Eclipse will port over SWT to OS X/Intel. Even if it doesn’t, there is a PPC to Intel translator built into OS X/Intel called Rosetta. It reminded me of HotSpot and it seemed quite good.

Cocoa programmers will have to get Xcode 2.1, upgrade their project, set a flag to compile for both PPC and Intel, recompile, and deploy their new Universal binary which contains both executables. Pretty simple.

There’ll be plenty of time to do this, since Apple isn’t scheduled to ship Mac/Intel computers until around this time next year.

On a personal level, this is on one hand exciting and nerve-tingling, but on the other hand, no big deal. I’ve been through a lot of different transitions, at the language level (Smalltalk -> Java), at the OS level (too many to count), and at the hardware level (I’ve had a Timex Sinclair, a PCjr, a Mac, an Amiga, a 10th Anniversary Gateway, several custom built-PCs and now the PowerBook and Mac mini.) I think this will be smoother than the rest, because the OS, language, and frameworks will stay stable, and only parts of the hardware will change.

I’m at WWDC 2005

It’s less than an hour until Steve Job’s keynote and the place is buzzing. There is a HUGE line to get into the keynote. Its like they released Star Wars Episode 7 or there was a release of The Hobbit. Its big.

I don’t really enjoy waiting in lines, so I thought I’d get a little blogging done. Apple set up some tables with power strips, ethernet connections and also provided us with some breakfast. So I’m blogging in style…

WWDC is going to be completely different blog-wise from EclipseCon. EclipseCon is all about openness. All the sessions were released under the Eclipse Public License. WWDC on the other hand is all about confidentiality, except for The Keynote. It doesn’t affect the attendee in any way, except you won’t see too much on my blog about what happens here at WWDC. I’ll probably blog about people I’ve met or at least have seen.

Speaking of which, I saw Aaron Hillegass of Big Nerd Ranch with his trademark cowboy hat. I almost came sporting my Eclipse cap, but I thought I’d save it for later. I remember at EclipseCon, there was Ed of Cisco who was sporting purple fuzzy slippers. We all thought: who is that guy? And why is he in his pajamas? Well I asked him after the scripting languages BOF and he explained that it helps people identify him and remember him. Yup. It sure does. :)

Intel… that’s the big rumor right now. There’s TV cameras in front of the Moscone Center. I woke up this morning to CNBC reporting the story, saying that IBM would be fine because they have all the game console chip business (which I talked about in my PowerPC Inside post.) We’ll see… I’m still personally holding out for PowerBook G5s, but I guess I’m an optimist.

I’m going to WWDC 2005!

I did it. I booked my hotel, my flight, and then signed up early for WWDC 2005 with the Tiger Early Start Kit. Getting that “kit” means that you’re an ADC Select member, where you get beta relases, a special Tiger training DVD, and other perks.

Why hotel, flight, then conference? To nail down the most price volatile components first. I’ve worked in both the hotel reservation industry as well as for a major airline and trust me, you really should book as early as possible if you want to get a room/seat at a good price. As for WWDC 2005, if you’re thinking about going, I would book by April 22nd so you save $300. BTW, If you’re looking for a hotel near the Moscone Center, send me an email because my wife and I have done plenty of research. :)

Why go to WWDC? Well, I really like developing apps for the Mac, I think OS X is a great platform for people who really care about a first class user experience, Cocoa is a fascinating application framework, and going to WWDC is like diving in head first into all of that. (Hmmm… that could be a book: Head First Cocoa.) Plus, conferences are a great way to grow your brain, to meet people who are interested and passionate about the same things you are and to get you excited about new ideas and new technology.