Today I had a rest day. I watched a few videos on Big O Notation and practice the Ruby section on HackerRank
I pushed it to my Github here
In addition, I did one coding challenge on HackerRank.
The question ask: Given an array of integers, print each element in reverse order as a single line of space-separated integers.
Now the simple way to do this was to use the .reverse
method like the following:
def reverseArray(a)
a.reverse
end
But that is too easy and it would not really make it a challenge now would it? I decided to use repl.it and work this example out using [1,2,3,4,5]
as my sample array.
This first thing I wanted to do was iterate over the array like so:
def reverseArray(a)
a.each_with_index do |num, index|
end
end
Now essentially you want to change the index of the array, but first its easier to reference it if the numbers are by 1 so lets add the (index+1)
def reverseArray(a)
a.each_with_index do |num, index|
puts (index+1)
end
end
which will return your indexes plus one:
1
2
3
4
5
So if you want to reference all an index in the a
array you might try this:
def reverseArray(a)
a.each_with_index do |num, index|
puts (a[index+1])
end
end
But that wont work because when you think about it the code above is looking for the following in your array:
a[1] // 2
a[2] // 3
a[3] // 4
a[4] // 5
a[5] // N/A
I had to find a way to reference the index in reverse. I had to think back to what can reverse/negate something. The negative(-) sign helped me with this:
def reverseArray(a)
a.each_with_index do |num, index|
puts (a[-(index+1)])
end
end
Which returned the following:
5
4
3
2
1
Look at that, I returned a reversed array.
Next, using the array review I accomplished on HackerRank, I was able to complete this challenge. I knew that the .push()
method adds new items to the end of an array, and returns the new length. I needed to push the a
array into a new_array so that it could be returned, like so:
def reverseArray(a)
new_array = []
a.each_with_index do |num, index|
new_array.push(a[-(index+1)])
end
return new_array
end
This took me a hour and a half and I do not want people who read this to think this was simple. I am a code newbie and although I was able to figure this code out, it was not easy. Keep that in mind as you code. It may take hours, but you will get it and feel great when you accomplish something you never thought was possible.
Top comments (0)