fork download
  1. # coding: utf-8
  2. require 'minitest/autorun'
  3.  
  4. F=->s{
  5. l=s.split ?\n
  6. m=l.size
  7. n=l[0].size
  8.  
  9. # Make an array with lowercase letters and their coords (`b`)
  10. # Make a hash that for each target (uppercase letter) holds
  11. # its coordinates
  12. b=[]
  13. t={}
  14. [*0...m].product([*0...n]).map{|y,x|
  15. c=l[y][x]
  16. c!=' '&&(c>?Z?b<<[c,y,x]:t[c.downcase]=[y,x])
  17. }
  18.  
  19. # `l` is a function that, given an array of the form
  20. # [lowercase_letter, y-coord, x-coord] will append to that array
  21. # the number of steps required for the letter to reach its
  22. # uppercase correspondent
  23. l=->q{
  24. c,y,x=q
  25. u,i=t[c]
  26. d=c.ord-97
  27. (m*n).times{|w|
  28. e=([u-y,i-x].map &:abs).max
  29. e<=d&&q<<w+e
  30. y=(y+1)%m
  31. x=(x+1)%n
  32. }
  33. }
  34.  
  35. # apply function `l` to each of the lowercase letter...
  36. b.map &l
  37.  
  38. # ...then sort accordingly and return the array
  39. b.map{|x|[x[3],x[0]]}.select{|a,b|a}.sort.map{|a,b|b}
  40. }
  41.  
  42.  
  43. describe '#F' do
  44. def test_case_1
  45. assert_equal %w[d a], F[%q{
  46. D
  47. d Aa
  48.  
  49. }]
  50. end
  51.  
  52. def test_case_2
  53. assert_equal %w[w b], F[%q{
  54. W B
  55. A
  56. b
  57.  
  58. a
  59. w
  60. }]
  61. end
  62.  
  63. def test_case_3
  64. assert_equal %w[a], F[%q{
  65.  
  66. A
  67.  
  68.  
  69. a
  70. }]
  71. end
  72.  
  73. def test_case_4
  74. assert_equal %w[i d f], F[%q{
  75.  
  76. i
  77. f d
  78.  
  79.  
  80. DI F }]
  81. end
  82.  
  83. def test_case_5
  84. assert_equal %w[g w j], F[%q{
  85.  
  86.  
  87. g a
  88.  
  89.  
  90. G W
  91.  
  92.  
  93.  
  94.  
  95. j
  96. w
  97.  
  98.  
  99.  
  100. A J
  101.  
  102.  
  103. }]
  104. end
  105. end
  106.  
  107.  
  108.  
Success #stdin #stdout 0.07s 8536KB
stdin
Standard input is empty
stdout
Run options: --seed 1415

# Running tests:

.....

Finished tests in 0.012371s, 404.1769 tests/s, 404.1769 assertions/s.

5 tests, 5 assertions, 0 failures, 0 errors, 0 skips