Codewars Kata: Looking for a benefactor 1 of 2
The Looking for a Benefactor challenge on Codewars was fun. Challenging, but fun. It’s been a while since I’ve written anything in Java that wasn’t related to Android.
Based on the description, I figured the solution was to store a list of n donation amounts, prompt the
user to enter a target average of n + 1 donations and determine the next donation amount needed to meet this average.
There was a list of donations provided for this example: $14, $30, $5, $7, $9, $11, and $15. In the example, the target average
is $30; meaning, the next donation should cause the average of donations to become $30.
I wanted to model this information with a formula. I already had the list of donations and the target average. I stored the
values in an array so I could easily determine additional information such as the sum and number of all current donations. I
imported the Array class for additional resources.
When first reading the prompt, I figured I could find the sum using a for loop to cycle through the array.
But it’s 2018! Surely Java has an easier way to do this. After some researcch, I found the IntStream class.
IntStream had methods for manipulating data in an array, which happened to be exactly what I needed. Using
the IntStream sum() method and the Arrays length method, I could quickly calculate the average of the array.
Taking a quick math break, I had to validate user input to make sure the program does not return a negative number.
I figure if the current average is a number r, and the user enters a target average that is less than r, it
would require a donation of a negative amount. Since people on Earth don’t carry negative currency, I
included an if statement that would end the program if a user enters a target average less than the current average.
Next was the fun part. Determining the donation needed to reach the target average. Using the array sum A,
array length C, and target average D, I created a formula for finding the donation needed, B:
B = D(C + 1) – A
The program displayed the user’s needed donation amount with a friendly message. I felt pretty accomplished.
As usual, I enjoyed learning about new classes in Java. The sum() method of IntStream probably utilizes for loops and
invokes the lenth method of the Arrays class. The data structures we learn in early computer science classes
help shape how we analyze both problems, and solutions.
After all this hard work, I returned to the codewars website triumpant and ready to receive my reward…only
to find out I wasn’t supposed to write the entire program…CONTINUED IN PART 2