Skip to content

Instantly share code, notes, and snippets.

@johand
Created January 27, 2013 10:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johand/4647766 to your computer and use it in GitHub Desktop.
Save johand/4647766 to your computer and use it in GitHub Desktop.
saas course week2-hw1
#hw 1-1: fun with strings
def palindrome?(str)
letters = str.downcase.scan(/\w/)
letters == letters.reverse
end
def count_words(str)
str = str.downcase.split
words = {}
str.each do |word|
if words.include? word
words[word] += 1
else
words[word] = 1
end
end
words
end
#hw 1-2: rock-paper-scissors
class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end
def rps_result(m1, m2)
@winner=0 if (m1=="P" || m1=="S") && m2=="P"
@winner=1 if m1=="P" && m2=="S"
@winner=0 if (m1=="P" || m1=="R") && m2=="R"
@winner=1 if m1=="R" && m2=="P"
@winner=0 if (m1=="R" || m1=="S") && m2=="S"
@winner=1 if m1=="S" && m2=="R"
return @winner
end
def rps_game_winner(game)
raise WrongNumberOfPlayersError unless game.length == 2
game.each do |games|
raise NoSuchStrategyError unless
games[1].casecmp("s")==0 ||
games[1].casecmp("p")==0 ||
games[1].casecmp("r")==0
end
@win=rps_result(game[0][1].capitalize,game[1][1].capitalize)
if @win==0
@lose = 1
else
@lose = 0
end
@winner=game[@win][0]
@winMove=game[@win][1]
@loseMove=game[@lose][1]
return @winner, @winMove
end
def rps_tournament_winner(tournament)
@winnerNums=tournament.flatten.length/4
i=0
gameWinner=[]
while i<tournament.flatten.length do
gameWinner[i]=tournament.flatten[0+i]
gameWinner[i+1]=tournament.flatten[1+i]
i=i+2
end
while @winnerNums>0 do
i=0
while i<@winnerNums
newGame=[
[gameWinner[0+i*4].to_s, gameWinner[1+i*4].to_s],
[gameWinner[2+i*4].to_s, gameWinner[3+i*4].to_s]
]
newWinner=rps_game_winner(newGame)
gameWinner[i*2]=newWinner[0]
gameWinner[i*2+1]=newWinner[1]
i=i+1
end
@winnerNums=@winnerNums/2
end
return newWinner[0].to_s, newWinner[1].to_s
end
game = [["Richard", "R"], ["Michael", "S"]]
puts rps_game_winner(game)[0]
tournament = [["Armando", "p"], ["Dave", "S"]]
puts rps_tournament_winner(tournament)
puts ["Richard", "R"]
#hw 1-3: anagrams
def combine_anagrams(words)
words.group_by {|i| i.downcase.chars.sort.join}.values
end
a = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream']
p combine_anagrams(a)
#hw 1-4: basic object oriented programming
class Dessert
attr_accessor :name, :calories
def initialize(name, calories)
@name = name
@calories = calories
end
def healthy?
self.calories < 200
end
def delicious?
self.instance_of? Dessert
end
end
class JellyBean < Dessert
attr_accessor :flavor
def initialize(name, calories, flavor)
@name = name
@calories = calories
@flavor = flavor
end
def delicious?
(self.flavor != "black licorice")
end
end
cupcake = Dessert.new "Cupcake", 250
p cupcake.name
p cupcake.calories
p cupcake.healthy?
p cupcake.delicious?
puts
jelly = JellyBean.new "Jelly", 250, "black licorice"
p jelly.name
p jelly.calories
p jelly.flavor
p jelly.healthy?
p jelly.delicious?
puts
jellybean1 = JellyBean.new('jellybean', 5, 'strawberry')
p jellybean1.delicious?
#hw 1-5: advanced OOP, metaprogramming, open classes and duck typing
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
attr_reader attr_name
attr_reader attr_name+"_history"
class_eval %{
def #{attr_name}=(val)
@#{attr_name} = val
@#{attr_name}_history = [nil] if @#{attr_name}_history.nil?
@#{attr_name}_history.push(val)
end
}
end
end
class Foo
attr_accessor_with_history :bar
end
f = Foo.new
f.bar = 1
f.bar = 2
p f.bar_history
#hw 1-6: advanced OOP, metaprogramming, open classes and duck typing
class Numeric
@@currencies = {:yen => 0.013, :euro => 1.292, :rupee => 0.019, :dollar => 1.0}
def dollar
self ; end
def in (cur)
self / @@currencies[cur.to_s.gsub( /s$/, '').to_sym]
end
def method_missing(method_id)
singular_currency = method_id.to_s.gsub( /s$/, '').to_sym
if @@currencies.has_key?(singular_currency)
self * @@currencies[singular_currency]
else
super
end
end
end
class String
def palindrome?
self.gsub!(/(\W|\b)+/i, "").downcase! == self.reverse.downcase!
end
end
module Enumerable
def palindrome?
self.join.gsub!(/(\W|\b)+/i, "") == self.join.reverse
end
end
#hw 1-7: iterators, blocks, yield
class CartesianProduct
include Enumerable
def initialize arry1, arry2
@arry1, @arry2 = arry1, arry2
end
def each
unless @arry1.empty? && @arry2.empty?
resulting_array = []
@arry1.each do |a1|
resulting_array << @arry2.each { |a2| yield [a1] << a2 }
end
end
end
end
c = CartesianProduct.new([:a,:b], [4,5])
c.each { |elt| puts elt.inspect }
puts
c = CartesianProduct.new([:a,:b], (1..5).to_a)
c.each { |elt| puts elt.inspect }
puts
c = CartesianProduct.new([:a,:b], [])
c.each { |elt| puts elt.inspect }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment