fork download
  1. POINTS = {
  2. 'P' => 1,
  3. 'B' => 3,
  4. 'N' => 3,
  5. 'R' => 5,
  6. 'Q' => 9
  7. }
  8.  
  9. Result = Struct.new :points, :lines
  10.  
  11. def solve(lines, crt_pos=p)
  12. crt_row, *next_rows = lines.map &:dup
  13. pos = crt_pos||crt_row.index(?L)
  14.  
  15. next_row = next_rows[0]
  16.  
  17. points = POINTS[crt_row[pos]]||0
  18. crt_row[pos] = ?X if crt_pos
  19.  
  20. unless next_row
  21. return Result.new points, crt_row
  22. end
  23.  
  24. next_moves = []
  25. next_moves << solve(next_rows, pos) if next_row[pos] == ?-
  26. next_moves << solve(next_rows, pos-1) if pos > 0 && next_row[pos-1] > ?-
  27. next_moves << solve(next_rows, pos+1) if pos < 8 && next_row[pos+1] > ?-
  28.  
  29. # pp next_moves
  30.  
  31. best_move = next_moves.compact.max_by{ |m| m.points }
  32.  
  33. if best_move
  34. return Result.new(best_move.points + points, crt_row + best_move.lines)
  35. end
  36. end
  37.  
  38. F=
  39. ->board{
  40. solve(board.lines).lines
  41. }
  42.  
  43. require 'minitest/autorun'
  44.  
  45. describe F do
  46. def test_case_1
  47. input = <<-EOS
  48. ----L---
  49. -----P--
  50. ------P-
  51. --R--P-Q
  52. ----P-P-
  53. ---P-P-P
  54. --P-N---
  55. -P------
  56. EOS
  57.  
  58. F[input].must_equal <<-EOS
  59. ----L---
  60. -----X--
  61. ------X-
  62. --R--P-X
  63. ----P-X-
  64. ---P-X-P
  65. --P-X---
  66. -P--X---
  67. EOS
  68. end
  69.  
  70. def test_case_2
  71. input = <<-EOS
  72. --L-----
  73. -P------
  74. P-------
  75. -P------
  76. P--Q----
  77. -P------
  78. P-------
  79. -P------
  80. EOS
  81.  
  82. F[input].must_equal <<-EOS
  83. --L-----
  84. -PX-----
  85. P-X-----
  86. -PX-----
  87. P--X----
  88. -P-X----
  89. P--X----
  90. -P-X----
  91. EOS
  92. end
  93.  
  94. end
  95.  
  96.  
Success #stdin #stdout 0.1s 10784KB
stdin
Standard input is empty
stdout
Run options: --seed 16480

# Running tests:

..

Finished tests in 0.001952s, 1024.4364 tests/s, 1024.4364 assertions/s.

2 tests, 2 assertions, 0 failures, 0 errors, 0 skips