Building things that matter
blake-connally-373084.jpg

Code Challenges

CodeWars: Growth of a Population (Ruby)

After Crepe Sunday for breakfast what do you do? A random code challenge of course. 

This one, wanted you to take four parameters, and write a function that would sort the number of years a starting population would exceed a target population factoring in percentage growth and population change due to people moving in and moving out. 

My solution is below.

While most solutions only utilized the single method, I've been really focusing on Single Responsibility and "Do One Thing" earlier in my coding recently.   

So my approach was to create two separate methods for addressing the two calculations that were needed to return the answer.  I set one method, who's only job was to take the population year over year and compute and return the percentage change. 

My third method, ni_increase, which, in retrospect I'd change to ni_change since it can be a decrease, not just an increase, addressed adding inhabitant population increase (or decrease if negative number provided) and returning the change in value. 

I ran these two methods inside of the primary nb_year method to make the full calculation.  

My theory on this is that it is better to break out some of the smaller parts of the computation into their own methods so that if you have errors in calculation, you can debug through smaller methods than larger, more difficult to read mathematics inside a single method. 

This actually worked out in practice on this as I had do debug a calculation error which was coming from my percent_increase method.  by having it separate I was able to identify where the error was and correct it (added .floor to the calculated value to solve for rounding errors) and it cleared all the tests as expected. 

Additionally, many solutions to this used while, instead of until.  Until made more sense to me when writing this, because until the population was greater than or equal to the target population, the loop should continue.  Reasoning about it as a while the value was less than the target population feels more difficult to conceptualize.  

Robert Cornell