Office Hours: Compute max population given a list of people’s birth and death year

I recently came across a brief programming puzzle prompt (say that three times fast) which asked to return the year that population peaked.

The actual algorithm to compute it can be done several ways and is not particularly difficult, but I have recently been challenging myself to write .. ahem .. “more functional” code.

There are several tenets of FP, but a chief one is not producing what developers call “side effects”. I’m hoping to get to a point where I do not rely as much on classic object-oriented patterns and feel more at ease diving right into the functional style. Of course this takes practice, so I decided to spend some extra time polishing up my code to meet my internal requirements:

This is a demonstration of what I created after a few minutes of iteration.

I was readily able to produce a list of population changes and from there, performed further transformations to arrive at a list of total populations for each year. From there determining the year that population peaked was trivial.

However, I’m not fully satisfied with this solution. I could be being too dogmatic, but in my mind I would not be breaking scope of a map function to reference external values, even though it proved expedient in this case.

I’ve cross posted this on Stack Exchanges’s CodeReview.

Update:

User jwvh posted a great improvement on CodeReview

My favorite part of jwvh’s contribution is the excellent use of foldLeft. After seeing it in practice, and fulfilling the exact tension I felt with my original solution, it motivated me to spend a few hours working through lots, and lots of examples to become proficient at this pattern!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s