Kata: add arrays
Now in english, thanks to Pablo Ruiz 🙂
Let’s start with something simple to loosen up the muscles.
Many times, when we code with a deadline and we need to solve problems with urge we don’t pay attention to performance. At most, we promise to refactorize later on if needed. It would be great to have some coding ruotines embedded in ourselves that will allow us to code in a more efficient way, without even thinking of it.
So the kata I’m proposing is the following:
We have ten large arrays, with 500 integers each. We want to obtain the number that results from adding each of those 10*500=5000 integers. Easy, right?
Choose your favourite programming language and think about two distinct ways of reaching that sum. For instance, you can sum each array separately and then add up the results. Or you can do partial sums between each array’s position. Or blend all arrays in one and then add up all the numbers. Or whichever way that comes to your mind (a recursive function would make sense?). Implement them.
Now, using a loop, measure the time it takes to execute 1000 iterations of each of them.
What are the results? The way you thought was the fastest, was it? Really?
Bonus I: Upon results, do you conceive a third way that could outmatch the performance?
Bonus II: Repeat the exercise in a language you’ve never coded in.
And remember, this isn’t about a competition. It’s a Kata. Practice and improve. Always.
No comments yet.