Last active
August 29, 2015 14:17
-
-
Save revdan/c0fc581afbdedbe0c3eb to your computer and use it in GitHub Desktop.
Algorithm to find a poker straight
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
x = [5,6,7,8,9] | |
y = x.map(&:succ) | |
(x - y) + (y - x) == [(x+y).min, (x+y).max] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Successive | |
refine Array do | |
def successive? | |
y = self.map(&:succ) | |
(self - y) + (y - self) == [(self + y).min, (self + y).max] | |
end | |
end | |
end | |
class Hand | |
using Successive | |
def initialize(hand) | |
@hand = hand | |
end | |
def straight? | |
@hand.successive? | |
end | |
end | |
require 'minitest/autorun' | |
describe 'Successive' do | |
using Successive | |
before do | |
@straight = [1,2,3,4,5] | |
@also_straight = [5,6,3,4,1,7,2] | |
@not_straight = [1,2,3,4,9] | |
@also_not_straight = [10,2,3,4,9] | |
end | |
it "takes an array as input" do | |
assert_equal [1,2,3,4,5].successive?, true | |
end | |
it "doesn't like non-arrays" do | |
assert_raises NoMethodError do | |
"toot".successive? | |
end | |
end | |
it "is successive" do | |
assert_equal @straight.successive?, true | |
end | |
it "is also successive" do | |
assert_equal @also_straight.successive?, true | |
end | |
it "is not successive" do | |
assert_equal @not_straight.successive?, false | |
end | |
it "is also not successive" do | |
assert_equal @also_not_straight.successive?, false | |
end | |
end | |
describe 'Hand' do | |
before do | |
@straight = Hand.new [1,2,3,4,5,6,7,8] | |
@also_straight = Hand.new [5,3,4,1,2,6] | |
@not_straight = Hand.new [1,2,3,4,9] | |
@also_not_straight = Hand.new [10,2,3,4,9,1,5] | |
end | |
it "is a straight" do | |
assert_equal @straight.straight?, true | |
end | |
it "is also a straight" do | |
assert_equal @also_straight.straight?, true | |
end | |
it "is not a straight" do | |
assert_equal @not_straight.straight?, false | |
end | |
it "is also not a straight" do | |
assert_equal @also_not_straight.straight?, false | |
end | |
it "raises an error for a nil initialize" do | |
assert_raises ArgumentError do | |
Hand.new | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment