Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Queen Attack in the Ruby Track

Published at Jul 13 2018 · 1 comment
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Given the position of two queens on a chess board, indicate whether or not they are positioned so that they can attack each other.

In the game of chess, a queen can attack pieces which are on the same row, column, or diagonal.

A chessboard can be represented by an 8 by 8 array.

So if you're told the white queen is at (2, 3) and the black queen at (5, 6), then you'd know you've got a set-up like so:

_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ W _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ B _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _

You'd also be able to answer whether the queens can attack each other. In this case, that answer would be yes, they can, because both pieces share a diagonal.


For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

gem install minitest

If you would like color output, you can require 'minitest/pride' in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

ruby queen_attack_test.rb

To include color from the command line:

ruby -r minitest/pride queen_attack_test.rb

Source

J Dalbey's Programming Practice problems http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

queen_attack_test.rb

require 'minitest/autorun'
require_relative 'queen_attack'

# Common test data version: 2.0.0 44a1e12
class QueenAttackTest < Minitest::Test
  def test_queen_with_a_valid_position
    # skip
    assert Queens.new(white: [2, 2])
  end

  def test_queen_must_have_positive_row
    skip
    assert_raises ArgumentError do
      Queens.new(white: [-2, 2])
    end
  end

  def test_queen_must_have_row_on_board
    skip
    assert_raises ArgumentError do
      Queens.new(white: [8, 4])
    end
  end

  def test_queen_must_have_positive_column
    skip
    assert_raises ArgumentError do
      Queens.new(white: [2, -2])
    end
  end

  def test_queen_must_have_column_on_board
    skip
    assert_raises ArgumentError do
      Queens.new(white: [4, 8])
    end
  end

  def test_can_not_attack
    skip
    queens = Queens.new(white: [2, 4], black: [6, 6])
    refute queens.attack?
  end

  def test_can_attack_on_same_row
    skip
    queens = Queens.new(white: [2, 4], black: [2, 6])
    assert queens.attack?
  end

  def test_can_attack_on_same_column
    skip
    queens = Queens.new(white: [4, 5], black: [2, 5])
    assert queens.attack?
  end

  def test_can_attack_on_first_diagonal
    skip
    queens = Queens.new(white: [2, 2], black: [0, 4])
    assert queens.attack?
  end

  def test_can_attack_on_second_diagonal
    skip
    queens = Queens.new(white: [2, 2], black: [3, 1])
    assert queens.attack?
  end

  def test_can_attack_on_third_diagonal
    skip
    queens = Queens.new(white: [2, 2], black: [1, 1])
    assert queens.attack?
  end

  def test_can_attack_on_fourth_diagonal
    skip
    queens = Queens.new(white: [2, 2], black: [5, 5])
    assert queens.attack?
  end

  # Problems in exercism evolve over time, as we find better ways to ask
  # questions.
  # The version number refers to the version of the problem you solved,
  # not your solution.
  #
  # Define a constant named VERSION inside of the top level BookKeeping
  # module, which may be placed near the end of your file.
  #
  # In your file, it will look like this:
  #
  # module BookKeeping
  #   VERSION = 1 # Where the version number matches the one in the test.
  # end
  #
  # If you are curious, read more about constants on RubyDoc:
  # http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html

  def test_bookkeeping
    skip
    assert_equal 2, BookKeeping::VERSION
  end
end
# Queens
class Queens
  DEFAULTS = { white: [0, 3], black: [7, 3] }.freeze
  attr_reader :white, :black
  attr_accessor :board
  def initialize(positions = DEFAULTS)
    raise ArgumentError if positions[:white] == positions[:black]
    @board = Array.new(8) { Array.new(8, '_') }
    @white = [*positions[:white]]
    @black = [*positions[:black]]
    set_queens
  end

  def attack?
    same_row? || same_col? || same_diagonal?
  end

  def to_s
    board.map { |row| row.join(' ') }.join("\n")
  end

  private

  def set_queens
    set_queen('W', white.first, white.last)
    set_queen('B', black.first, black.last)
  end

  def set_queen(color, x, y)
    board[x][y] = color
  end

  # BUG hard-coded indices
  def same_row?
    white[0] == black[0]
  end

  def same_col?
    white[1] == black[1]
  end

  def same_diagonal?
    (white[1] - white[0]).abs == (black[1] - black[0]).abs
  end
end

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of petertseng

The code seems very readable with the self-explanatory method names.

One disadvantage seems to be that we wouldn't be able to specify the location of just one of the queens, leaving the other defaulted, for example $ ruby -r./queens -e'Queens.new(white: [5, 5])' /home/pt/exercism/solutions/rootulp/ruby/queen-attack/03ce5042abab476cbd839f0709797da2/queens.rb:30:in []': no implicit conversion from nil to integer (TypeError) from /home/pt/exercism/solutions/rootulp/ruby/queen-attack/03ce5042abab476cbd839f0709797da2/queens.rb:30:in set_queen' from /home/pt/exercism/solutions/rootulp/ruby/queen-attack/03ce5042abab476cbd839f0709797da2/queens.rb:26:in set_queens' from /home/pt/exercism/solutions/rootulp/ruby/queen-attack/03ce5042abab476cbd839f0709797da2/queens.rb:11:in initialize' from -e:1:in new' from -e:1:in ' zsh: exit 1 ruby -r./queens -e'Queens.new(white: [5, 5])'

If using a Ruby version 2.0 or greater, could look into keyword arguments to make this possible.

What can you learn from this solution?

A huge amount can be learned from reading other peopleโ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?