CoderByte Challenges

My solutions on GitHub

CoderByte has numerous programming challenges in many languages. Here I will post and discuss solving and thinking about the solutions.

first_reverse

``````def first_reverse(str)
str.reverse
end
``````

first_factorial

``````def first_factorial(num)
(1..num).reduce(:*) || 1
end

def first_factorial(num)
num == 0 ? 1 : num * first_factorial(num - 1)
end
``````

I have been doing the verbose way of the second version when I was starting out, but I have been trying to refactor the factorial method to something shorter and more elegant. I actually saw the use of reduce online, and I had to learn what it did. There was a great walkthrough of Reduce on RailSpikes that helped me tremendously.

longest_word

``````def longest_word(sen)
sen_array = sen.split(/\W/)
sen_array.max_by(&:length)
end
``````

Here I’m splitting the sentence on non-word characters. My initial attempt at solving this problem tried to split via the white space then replace all non-alphabet characters with a empty string. For one reason or another, irb was throwing errors. Either way I had an array split up, and now I had to find the longest word. I first tried `max()`, but I noticed that the first element of the max must be returned. So `['a', 'b']` would need to return `a` not `b` because it occurred first. `b` is greater in value based on the char-code, but I needed to get the max by either `size` or `length`. After looking in the Ruby docs I saw max_by used similarly.

letter_changes

``````def letter_changes(str)
alphabet = ('a'..'z').to_a + ('A'..'Z').to_a
new_string = ''

str.split(//).each do |letter|
if letter == 'z'
new_string << alphabet[0]
elsif letter == 'Z'
new_string << alphabet[26]
elsif letter =~ /[a-zA-Z]/
new_string << alphabet[alphabet.index(letter) + 1]
else
new_string << letter
end
end
return new_string.gsub(/[aiueo]/, &:upcase)
end
``````

I was stuck on this problem for a while, so I looked up the solution. I found the solution, but I was unhappy with it. I took some parts of that solution and refactored.

First there was unnecessary `placeholder` variable that was being used to set what character would be added to the `new_string` Next was the loop for each letter in the alphabet array. Finally there was unnecessary declaration of the `new_string` with a `placeholder` being interpolated. Instead of have a `placeholder` variable, I chose to modify the `new_string` variable directly with `<<`. `<<` has the added benefit of modifying the original object, instead of create a new one. I eliminated the need to loop through the alphabet by just finding the `letter`‘s index, adding one, then getting the next character in the series. `alphabet[alphabet.index(letter) + 1]`.