Quantcast
Viewing all articles
Browse latest Browse all 766

Ruby

def palindrome?(string)
    letters = string.downcase.scan(/\w/)
    return letters == letters.reverse
end

palindrome?("A man, a plan, a canal -- Panama")  # => true
palindrome?("Madam, I'm Adam!")                  # => true
palindrome?("Abracadabra")                       # => false (nil is also ok)

def count_words(string)
    words = string.downcase.split(/[^a-zA-Z]/).reject{|e| e.empty?}
    wf = Hash.new(0)
    words.each { |word| wf[word] += 1 }
    return wf
end
count_words("A man, a plan, a canal -- Panama")
    # => {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1}
count_words "Doo bee doo bee doo"
    # => {'doo' => 3, 'bee' => 2}

class WrongNumberOfPlayersError <  StandardError ; end
class NoSuchStrategyError <  StandardError ; end
 
def rps_game_winner(game)
    raise WrongNumberOfPlayersError unless game.length == 2
    s0 = game[0][1].upcase
    s1 = game[1][1].upcase
    raise NoSuchStrategyError unless ["R", "S", "P"].include? s0
    raise NoSuchStrategyError unless ["R", "S", "P"].include? s1
    if ( s0 == s1) 
        return game[0]
    end
    if (s0 == "R")
		return (s1 == "S" ? game[0] : game[1])
    elsif (s0 == "S") 
		return (s1 == "P" ? game[0] : game[1])
	else
		return (s1 == "R" ? game[0] : game[1])
    end
end

rps_game_winner([ ["Armando", "P"], ["Dave", "S"] ])

def rps_tournament_winner(tournament)
   s0 = tournament[0][1]
   if (s0.is_a? String) 
      return rps_game_winner(tournament)
   else
      return rps_game_winner([rps_tournament_winner(tournament[0]), rps_tournament_winner(tournament[1])])
   end
end
rps_tournament_winner([
    [
        [ ["Armando", "P"], ["Dave", "S"] ],
        [ ["Richard", "R"],  ["Michael", "S"] ],
    ],
    [
        [ ["Allen", "S"], ["Omer", "P"] ],
        [ ["David E.", "R"], ["Richard X.", "P"] ]
    ]
])

def combine_anagrams(words)
    hash = Hash.new()
    words.each do |word|
        sorted_word = word.downcase.split('').sort.join
        if hash.has_key?(sorted_word)
            hash.store(sorted_word, hash.fetch(sorted_word).push(word))
        else
            hash.store(sorted_word, Array.new(1,word))
        end
    end
    return hash.values
end

combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream'])

class Dessert
    attr_accessor :name
    attr_accessor :calories
    def initialize(name, calories)
        # Your code here
    end

    def healthy?
        if (calories < 200) 
		    return true
		else 
		    return false
		end
    end

    def delicious?
        return true
    end
end


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 766

Trending Articles