Ruby challenge

Jreyes
2 min readAug 22, 2021

--

This week I encounter one challenge while job hunting. I was asked to do an algorithm that will take an array of numbers, and, will print out the sum of all the numbers within that array.

Let's start with a very small array:

array = [1, 2, 3, 4, 50, 6, 7, 88, 9, 90]

if we go back to BIG O and time complexity this will be an O(n) algorithm because we need to go over each element and do the math. We need to start from index 0 to index 9 one by one and keep adding the sum from the previews index to the next one until there are no more elements.

Let's define the method we are going to use and that method will take an input/array as an argument.

def sum_all_number(array)end

We need to add the first variable of total and that will have a value of 0.

def sum_all_number(array)
total = o
end

In order to access the array, we need an array method that will choose every element in the array one by one. For this example, I will use the method EACH and will be iterating between each element to do the math. Here is when we use the total variable to store the result of the sum.

def sum_all_number(array)
total = o
array.each {|i| total += i }
end

In the previews code, we are taking the total and adding the value of the next element in the array starting from the beginning. Now we need to return the result of the total at the end.

def sum_all_number(array)  total = 0  array.each {|i| total += i }  puts totalend

Now we need to test out if this code will work by calling the method and passing the array we created.

array = [1, 2, 3, 4, 50, 6, 7, 88, 9, 90]def sum_all_number(array)  total = 0  array.each {|i| total += i }  puts totalendputs sum_all_number(array)The result is: 260

Remember O(n) is the worst-case scenario because it runs one by one. let's try another one with bigger numbers.

array = [188, 245, 35, 48, 508, 656, 77, 88, 91, 910]def sum_all_number(array)
total = 0
array.each {|i| total += i } puts totalendputs sum_all_number(array) this result is 2846 and it took 10 seconds to run

Hope this helps someone else and happy coding.

--

--

Jreyes
Jreyes

Written by Jreyes

I'm a software engineer making his way into the tech industry.

No responses yet