Skip to content

Instantly share code, notes, and snippets.

@kmazanec
kmazanec / poker.rb
Created August 19, 2013 22:14
Created some wrapper code to utilize the PokerHand class. Fully interactive from the command line! (and yes, it's a bit of a mess)
# Poker
require_relative "PokerHand.rb"
class Deck
@@CLASSIC_DECK = ['2d','3d','4d','5d','6d','7d','8d','9d','Td','Jd','Qd','Kd','Ad'] +
['2h','3h','4h','5h','6h','7h','8h','9h','Th','Jh','Qh','Kh','Ah'] +
['2s','3s','4s','5s','6s','7s','8s','9s','Ts','Js','Qs','Ks','As'] +
['2c','3c','4c','5c','6c','7c','8c','9c','Tc','Jc','Qc','Kc','Ac']
class PokerHand
attr_reader :hand, :score
def initialize (hand)
@hand = hand
@straight = @flush = @full_house = @quad = @triple = @two_pair = @pair = false
@score = 0
end
def evaluate
hands = @hand.scan(/[cdsh]/) # Creates array for suits
@kmazanec
kmazanec / sum.rb
Created August 16, 2013 19:51
Recursively sum an indefinite number of elements. Use the splat operator to take any number of arguments. When calling this method, be sure to use the splat operator on any arrays that are passed to it or it will not function properly.
def sum ( *args )
args.length > 1 ? args.pop + sum(*args) : args.pop
end
test_array = [1,2,3,4]
puts sum(1,2) # ==> 3
puts sum(*test_array) # ==> 10
@kmazanec
kmazanec / flatten_recursive.rb
Last active December 19, 2015 21:29
Flatten an array entirely using recursion. (I am particularly amazed at how short and simple this is compared to using iteration)
def flatten(array)
return Array(array) unless array.is_a?(Array) && array.length > 0
flatten(array.shift) + flatten(array)
end
array = ["bananas", [1,2,3], ["apple", "cheese", [100, 20]], [true], [4.0, 7, 32]]
puts flatten(array).to_s
array = ["bananas"]
@kmazanec
kmazanec / flatten.rb
Created July 17, 2013 12:52
Flatten an array using a mix of iteration and recursion
def flatten(array)
return nil unless array.is_a?(Array)
array.each do |item|
if item.is_a?(Array)
flatten(item).reverse_each do |inner_item|
#add to array at index of item
array.insert(array.index(item)+1, inner_item)
end
#remove pre-existing array
array.delete(item)
@kmazanec
kmazanec / modern_roman.rb
Last active December 19, 2015 20:19
Modern Roman Numeral generator - am I missing a way to make this simpler? I know I could use a case statement and tighten things up that way, but logically, am I missing something?
def roman input
if input < 0 || input >= 10000
'Out of bounds'
elsif input >= 1000 && input < 10000
'M' * (input / 1000) + roman(input % 1000)
elsif input >=900 && input < 1000
'CM' + roman(input-900)
elsif input >= 500 && input < 900
'D' + roman(input-500)
elsif input >= 400 && input < 500