Saturday, August 31, 2013

Coderbyte: Letter Count I (Ruby)

PROBLEM

Have the function LetterCountI(str) take the str parameter being passed and return the first word with the greatest number of repeated letters. For example: "Today, is the greatest day ever!" should return greatest because it has 2 e's (and 2 t's) and it comes before ever which also has 2 e's. If there are no words with repeating letters return -1. Words will be separated by spaces.

SOLUTION

def LetterCountI(str)
    highest_word = ""
    highest_number = 0 
    
    str.split(' ').each do |word|
        word.split('').each do |letter|
            if word.count(letter) > highest_number
                highest_word = word
                highest_number = word.count(letter)
            end
        end
    end
    
    highest_number == 1 ? "-1" : highest_word
end

print LetterCountI(STDIN.gets)