Solving the Collatz Problem with an Audience

Before my first technical interview (scheduled, unfortunately, at 7:00 PM on a Friday), I spent some time on the interwebs trying to figure out what to expect. My initial google search was actively unhelpful:Image


Well, I wasn’t worried about tears before, but I certainly am now. Thanks, Google!

I also spent some time on Interview Cake, which was less Ruby-specific than I’d like, and Project Euler, which is fairly language-agnostic but math-heavy. And, incurable procrastinator that I am, much of my hands-on-keyboard time leading up to my interview was spent down rabbit holes and cleaning my kitchen.

Even so, I made it through my first mock technical interview tear-free; my interviewer was helpful and friendly and gave objective, specific feedback at the end. Maybe I didn’t hit a home run, but I didn’t strike out and it was actually pretty fun. When I signed out of the Google Hangout, I actually went and refactored my code. Here’s the problem and how I solved it the second time around:

The Problem


Starting Out

Since we’re solving this problem in Ruby, we know that we want to construct our answer in an object-oriented way. On a basic level, an object-oriented program is made up of classes and objects; a class is like the recipe that shows you how to make an individual object like a red velvet cake. In other words:

Object-oriented applications are made up of parts that interact to produce the behavior of the whole. The parts are objects; interactions are embodied in the messages that pass between them.

– Sandi Metz, Practical Object-Oriented Design in Ruby (p. 3)

This fits perfectly into my Collatz problem because I want to test a bunch of numbers to see which one produces the longest array. To do this, I’ll put all of the behavior in a Collatz class and then ask it to churn out a million instances.


To move on with this, I’ll have to figure out how to pass my number argument through to any other methods I create. I’ll also have to save each answer in a chain to count its length later. I chose to do this by defining an array as an instance variable – which, by definition, is available to any other methods in a given class – and started out by shoving my argument number into the array I just made. I could have done this one of two ways:

Screen Shot 2014-04-18 at 8.55.10 PM

Making It Do Stuff

Now the hard part: Adding the logic. I won’t go into the gory details of how I arrived at my first answer, because it took me the better part of an hour. It can generally be expressed in psuedocode as “until the last element in my array is 1, check to see what n looks like. Do the first thing if it’s even, the second thing if it’s odd, and give me your answer.”


This solution works, but unfortunately takes a long time:

Collatz benchmarked

Yikes. That’s slow. I’m no computer science expert, but I did some research on calculating the Big O value of this function to see just how slow it is. Here’s the super high-level overview:

1. Multiply the n value for nested loops
2. Add the n value for sequential loops
3. Drop everything but the largest term
5. Conditional checks (e.g., “if n is even” in our case) are constant-time operations, or O(1)

So what really kills me here is the combination of two loops. When you’re counting up to a million, that adds up fast. But how could I do it better?

One option is memoization, which lets us store a computed value in a table and retrieve it later. Since we’re iterating over something a million times (twice!), this could be pretty useful. I can do this by setting up a hash in my class and then writing values to it, like this:

Screen Shot 2014-05-02 at 12.31.27 PM

I can also make my solution faster by taking advantage of Ruby’s attr_reader and attr_accessor (as this blog post demonstrates nicely). Now, my setup looks like this:

Screen Shot 2014-05-02 at 12.34.23 PM

Ultimately, the logic of the solution is very similar, but it does a better job of harnessing some of Ruby’s built-in strengths to move faster:

Screen Shot 2014-05-02 at 1.08.01 PM

How much faster? A lot faster:

Screen Shot 2014-05-02 at 1.07.28 PM

Much better 🙂

Posted in Uncategorized | Tagged , , | Leave a comment

Open-Source Data and Personal Analytics

I considered authoring a lengthy one-sided debate about my personal struggle with the openness of the Twitter era and/or my recent fascination with open-source code, business, and everything, but thought better of it. That’s a lot of typing. Instead, I’ll walk you through my thought progression by showing the highlight reel of relevant Internet discoveries.

  1. A Brief History of Open-Source Code

Following up on an earlier post about open-source business, I discovered this infographic (worth more words/commits than I could count) and thought it was an excellent illustration even for those unfamiliar with the datasets displayed:

A brief history of open-source code


“The 16 languages represented account for 90% of total commits”

2. A 2009 Tim Berners-Lee TEDTalk worth revisiting.

In this impassioned talk, Berners-Lee spoke about the importance of linked data and its role in shaping our future as a society. Through a variety of clear visuals and his eminently persuasive perspective, he ignited a linked data revolution and urged the audience to stop holding their knowledge to themselves and thus limiting the potential of our interconnected world and to apply this philosophy to their personal as well as professional lives. In the slide below, he illustrates the power of data linkages through the example of DBpedia.

The graphic is impressive on its own, but stood out to me in large part because it illustrates the powerful connections that can be drawn between “personal” (e.g., Flickr or MySpace) and academic (e.g., US Census Data and Project Gutenberg).

3. Stephen Wolfram on Personal Analytics

Berners-Lee makes his point clearly: Linked data is the key to unlocking the untapped potential of technology, and we all have a responsibility to contribute. We love to consume data, he points out, but so many of us engage in this practice of “data-hugging,” protecting our own information as though it represented our souls.

The debate over access to personal data is heated, so I won’t deal with that now. But personal data can give us power even if we keep it to ourselves – you manage what you measure, right? Stephen Wolfram, creator of Wolfram Alpha (among many other things), shows us how.

By recording his own activities over nearly two decades, Wolfram has amassed a powerful database from which he can derive real, data-driven meaning about his own activities. Take, for example, this chart of emails sent between 1990 and today:

Pretty cool in isolation, but it’s only one piece of the habit puzzle. Now, take this plot and plot it against data captured over the years illustrating the patterns of other life activities, and you start to see some fascinating trends:

Life habits plot

Stephen Wolfram’s life habits, plotted by hour

As humans, we’re endlessly inclined to make decisions based on our “gut feelings.” Constantly, even – perhaps especially – when we don’t realize we’re doing it, we take in impressions of our surroundings and our own behavior. These impressions then inform our assumptions about our realities that may very well be off-base; by collecting data about ourselves, we equip ourselves to make decisions based on reality rather than our assumptions.

4. Web Timer (Chrome)

I was inspired by Stephen Wolfram’s dataset, so I searched around for some tools that would allow me to mimic his controlled data-collection. Specifically, since my professional life does and will continue to exist predominantly online, I thought I’d start by tracking my digital activity in order to understand my own productivity.

The Chrome app store provides an app that will do just that (or so it claims). It tracks the amount of time I spend on a given page in a session and globally over time. Through this, I will be able to see what kinds of websites I view, when, how much time I spend on each, and how often I flip between pages.

A Chrome extension that tracks how you spend your time on the web (from

A Chrome extension that tracks how you spend your time on the web (from

5. iPhone Tracker (via GitHub)

This is an inevitably controversial but undeniably incredible project: using location data collected from your iPhone on import, iPhone Tracker displays a heat map of your activities based on the number of cell phone towers utilized in a given area. Check mine out:

Posted in Uncategorized | Leave a comment

Famous People Say: Blogging?

I became a person who writes things down the very minute I learned how. By definition, I guess that makes me a writer, but if I’m a writer I’m the unusual kind that doesn’t like to be read. Keeping a blog, to me, sounded a bit like keeping a pet parrot who screams out my thoughts in an infinite loop and always needs to be fed.

And then someone (my Ruby curriculum) told me to keep a pet parrot (this blog) and tell it to scream about code.

Clearly, I have to reconcile my personal issues with web-based communication, but I have a mean stubborn streak that’s hard to break. So I did what every millennial would do: I asked Google to tell me what someone else thinks.


This is pretty much how that went:





An hour later, I’ve overdosed on advice from my famous (and mostly dead) role models; I’m more conflicted than I was before and also kind of hungry. And what do I have to show for it? An empty wine glass and the realization that even the wisest people can’t form my opinions for me.

Oh, yeah – and also a blog post.

Posted in Uncategorized | Leave a comment

Matz-ian Ergonomics

Three weeks ago today, I fell down the Ruby rabbit hole when I started as a student at the Flatiron School. Since then, I have been mentally, emotionally, and physically consumed by code.  Like most of my classmates, I am almost literally attached at the wrists with my MacBook.

That’s great for the brain, but not always so for the body. Last week, I watched one of my classmates deal with the frustrating physical implications of such intensity – his brain loved the hours of coding, but his wrists were over it.  They hurt badly enough from the hours of tension and discomfort that they actually limited his capability to work. It struck me that I, for one, maintained a cavalier attitude towards physical health that was both youthful and silly. Professional athletes take extreme precautions with physical health because their bodies are the tools they need to do their jobs. Sure, our computers are our tools, but how can we use them if our hands won’t cooperate?

Before coming to the Flatiron School, I worked in operations management in a distribution facility and a data entry department. In those settings, where productivity needed to be consistent and worker safety was paramount, I learned a lot about work-related injuries such as carpal tunnel disorder and discovered the study of ergonomics.

WTF is Ergonomics?

The word “ergonomics” is rooted in the Greek words ergon (work) and nomos (laws). Our modern interpretation shifts the focus to our interactions with the things we work with; by one definition, ergonomics is the science of

“designing the job to fit the worker, not the worker to fit the job.”

That’s interesting. Matz, the creator of the Ruby language, said in an interview that he wanted to focus on “making the computer work for humans” rather than the other way around.


“… in fact we need to focus on humans, on how humans care about doing programming or operating the application of the machines.”

Hmm… Suddenly, ergonomics sounds pretty Matz-ian. If we’re going to spend our time focusing on how humans operate the machines, it seems we should have some respect for what that means in a physical sense.

Here’s the Bad News…

Well, the very design of a laptop – the connected screen and keyboard – violates a key ergonomic principle and, it turns out, is pretty bad for our bodies to begin with. Actually, the single-unit screen-and-keyboard combo was the standard in the early days of personal computing.

For example, check out the Tandy Radio Shack TRS-80 to the left (seriously… one of the first personal computing devices ever was sold exclusively at Radio Shack?!)

Tandy Radio Shack TRS-80

Eventually, so many users complained of musculoskeletal discomfort that ergonomic guidelines mandated the separation of the two pieces by the end of the 70’s. Modern laptops are excused from following these requirements because the very concept is so completely incompatible with ergonomic standards.

As one paper explains,

“Laptop computer screens and keyboards are joined, and are therefore unable to be adjusted separately in terms of screen height and distance, and keyboard height and distance. The posture required for their use is likely to be constrained, as little adjustment can be made for the anthropometric differences of users.”


So if your screen is at a comfortable level, your keyboard isn’t, and vice-versa. That means it’s on us to understand and work around it so we don’t end up looking like this guy:

On the bright side, there are some easy things we can do to help.

Thing #1: Basic Body Position

I guess we’d need to understand what that optimal position looks like in order to figure out how to make it happen. A study conducted on college students at Tufts University differentiates the two basic positions in this way:

Prone Homer Simpson

“Seated positions are typified by flexed neck, neutral shoulders and elbows…. The prone posture was characterized by comparatively non-neutral shoulders, elbows and wrists, and pronounced neck extension.”

I had a particularly horrible Hebrew school teacher who made us sit a notebook on our heads for slouching (i.e., slouching and sassing). Good thing I got a lot of practice, because this study confirmed: “the prone posture elicited significantly greater discomfort and intensity.” So sit up straight.

The Point: When possible, opt for a seated position that allows relaxed shoulders and elbows, ideally at a 45-degree angle.

Thing #2: Laptop Placement

Palm pads

Another study hoped to differentiate comfort levels through a typing test with body monitoring with and without palm rests as well as on and off the lap.
In a 10-page report, you’ll learn that they didn’t learn much. They did, however, provide a tip that could help us choose a less uncomfortable position depending on which part of our body is aching:

“Greater physical (muscular and articular) constraints seem to be imposed to the shoulder region in the desk situation whereas the head-neck and wrist segments appear to be more stressed in the lap situation.”

The Point: If your shoulders hurt, try putting your laptop on your lap for a bit. If your head/neck or wrists hurt, go find a desk/table/ledge to hack away at.

Thing #3: Separate Responsibilities

To move one step further, follow the recommendations laid out in one study published in the International Journal of Industrial Economics. They really put the hard sell on switching to a traditionally separated monitor (or getting a different job), but provide

“a general recommendation for the use of an external mouse, or mouse and keyboard (without number pad) when using a notebook computer for an extended period of time, as in a desktop replacement scenario.”

Keyboard positions

The Point: If you can, get a keyboard and mouse. Pick the keyboard without the numerical keypad, which can throw your posture off to the left side slightly; a negative-tilt keyboard tray is ergonomically ideal and will ease wrist pain further.Take a look at the hand position charts to the left and try to correct yourself if you feel yourself slipping into the WRONG zone.

Apple's Magic Mouse

Grab a mouse, but know that the magic trackpad isn’t ideal because it forces tension in your arm and wrist; the magic mouse is more ergonomically friendly.

The Main Message

Ergonomics and Matz both want us to make the computer work for us, not the other way around, and you don’t want to sustain a CRI (coding-related injury). Sit up straight; relax your shoulders and elbows, try to keep them at a right angle. Computer on your lap relieves your shoulders, but on the desk is better for your wrists. Accessorize your notebook if you’re using it a lot, and watch your hand position. Also, Radio Shack was cool in the ’70s. Still shocked.

Try out these wrist stretches every so often – you’ll look a little weird but feel good. And if you’ve got to sit on the bench for a few hours, do some aerobic emailing courtesy of Google:


Good luck!

Posted in Uncategorized | Tagged , , | Leave a comment