Created
August 30, 2013 00:59
-
-
Save broguinn/6385241 to your computer and use it in GitHub Desktop.
queens
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
def queens_attack?(white_coords, black_coords) | |
raise ArgumentError.new "Takes only two coordinates" if white_coords.length != 2 || !(white_coords.is_a?(Array)) | |
raise ArgumentError.new "Takes only two coordinates" if black_coords.length != 2 || !(black_coords.is_a?(Array)) | |
raise ArgumentError.new "The coordinates must not be the same" if black_coords == white_coords | |
white_coords.zip(black_coords).flatten.each do |coordinate| | |
raise TypeError.new "The coordinates must be between 0 and 7" if coordinate < 0 || coordinate > 7 | |
end | |
x_diff = (white_coords[0] - black_coords[0]).abs | |
y_diff = (white_coords[1] - black_coords[1]).abs | |
can_attack = false | |
can_attack = true if white_coords[0] == black_coords [0] || white_coords[1] == black_coords[1] | |
can_attack = true if x_diff == y_diff | |
return can_attack | |
end |
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
require 'rspec' | |
require 'queens' | |
describe 'queens_attack?' do | |
it 'raises an exception if not given coordinates' do | |
expect { queens_attack?("foo", [5, 6]) }.to raise_exception | |
expect { queens_attack?(5, [5, 6]) }.to raise_exception | |
expect { queens_attack?([5, 7, 4], [5, 6]) }.to raise_exception | |
expect { queens_attack?([5, 6], [5, 6]) }.to raise_exception | |
expect { queens_attack?([5, 7, 4], [5, 6]) }.to raise_exception | |
expect { queens_attack?([5, 9], [5, 6]) }.to raise_exception | |
expect { queens_attack?([5, -2], [5, 6]) }.to raise_exception | |
end | |
it 'finds two queens in the same row' do | |
queens_attack?([2, 3], [5, 3]).should be_true | |
end | |
it 'finds two queens in the same column' do | |
queens_attack?([1, 2], [1, 5]).should be_true | |
end | |
it 'finds two queens diagonally' do | |
queens_attack?([1, 3], [3, 5]).should be_true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment