Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Created September 23, 2018 12:18
Show Gist options
  • Save harrisonmalone/5b1f7dcd8297c0e3118370c96339b594 to your computer and use it in GitHub Desktop.
Save harrisonmalone/5b1f7dcd8297c0e3118370c96339b594 to your computer and use it in GitHub Desktop.
def word_battle(word_one, word_two)
# we split the words into an array
arr_word_one = word_one.split("")
arr_word_two = word_two.split("")
# we get the letters that are common to each word (using a comparison loop) and push them into an array
common_letters = []
arr_word_one.each do |letterone|
arr_word_two.each do |lettertwo|
if letterone == lettertwo
common_letters << letterone
end
end
end
# we remove the duplicates so that we only have one letter of the alphabet
common_letters = common_letters.uniq
# we create an alphabet
alpha = ("a".."z").to_a
# we compare the common letters to the alphabet (using a comparison loop), when a common letter equals an alphabet letter we make that corresponding alphabet letter nil and then create a mutated alphabet with nil values
mutated_alpha = []
alpha.each do |l1|
common_letters.each do |l2|
if l1 == l2
l1 = nil
end
end
mutated_alpha << l1
end
# now we can do a simple comparison again where if letterone equals lettertwo we put the index number in the array, we do this for both words
total_one = []
arr_word_one.each do |letterone|
mutated_alpha.each_with_index do |lettertwo, index|
if letterone == lettertwo
total_one << (index + 1)
end
end
end
total_two = []
arr_word_two.each do |letterone|
mutated_alpha.each_with_index do |lettertwo, index|
if letterone == lettertwo
total_two << (index + 1)
end
end
end
# here we sum the arrays
total_one = total_one.sum
total_two = total_two.sum
# we see if the result is a tie before we declare a winner
if total_one == total_two
return "It's a tie"
end
# we declare a winner
if total_one > total_two
return "#{word_one} is the winner with a score of #{total_one}"
else
return "#{word_two} is the winner with a score of #{total_two}"
end
end
p word_battle("helloo", "hello")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment