I am following coursera's saas-class online, and using this post for keeping track of progress/notes/links etc. These notes are very rough, mostly a personal log of progress…
/ save/ save or save! (! throws exception if operation fails)
def palindrome?(str) x = str.downcase.gsub(/\W/, "") return x.reverse == x end
require 'pp'
def count_words(str)
counts = Hash.new(0)
str.downcase.gsub(/\W/," ").scan(/\b\S+/) {|key| counts[key] = counts[key] + 1 }
return counts;
end
require 'pp'
class WrongNumberOfPlayersError < StandardError ;end
class NoSuchStrategyError < StandardError ;end
def rps_game_winner(game)
raise WrongNumberOfPlayersError unless game.length == 2
game.each {|player, move| raise NoSuchStrategyError unless move =~ /(p|s|r)/i }
rules = {:s => :r, :p => :s, :r => :p}
:player1 = 0; :player2=1; :name=0; :strategy = 1
case game[:player1][:strategy].downcase.to_sym
when game[:player2][:strategy].downcase.to_sym
return game[:player1]
when rules[game[:player2][:strategy].downcase.to_sym]
return game[:player1]
else
return game[:player2]
end
end
pp rps_game_winner([ [ "Armando", "S" ], [ "Dave", "P" ] ])
ruby
The logic here is to flatten the whole array, and pick four elements at a time and play the game. We keep doing this iteratively till we are only left with two elements and thus know the winners!
require 'enumerator'
def rps_tournament_winner(tournament)
tournament = tournament.flatten
while tournament.length > 2 do
tournament = tournament.each_slice(4).map { |p1,s1,p2,s2| rps_game_winner [[p1,s1],[p2,s2]] }.flatten
end
return tournament
end
# participants = [
# [[ ["Armando", "P"], ["Dave", "S"] ], [["Richard", "R"], ["Michael", "S"]]],
# [[ ["Allen", "S"], ["Omer", "P"] ], [ ["David E.", "R"], ["Richard X.", "P"]]]
# ]
# pp participants
# pp rps_tournament_winner(participants)
# pp participants
def combine_anagrams(words)
results = Hash.new([]);
words.each {|word| results[word.downcase.split(//).sort.join] += [word]}
return results.values;
end
#pp combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream']);