Skip to content

Instantly share code, notes, and snippets.

@broguinn
Created August 30, 2013 00:59
Show Gist options
  • Save broguinn/6385241 to your computer and use it in GitHub Desktop.
Save broguinn/6385241 to your computer and use it in GitHub Desktop.
queens
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
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