fork download
  1. def charDiff(String c1, String c2) {
  2. return (c1 as char) - (c2 as char)
  3. }
  4.  
  5. def decodeCoords(String s) {
  6. return [charDiff(s[0], 'a'), charDiff(s[1], '1')]
  7. }
  8.  
  9. def checkCoords(coords) {
  10. return ((coords[0] in (0..7)) && (coords[1] in (0..7)))
  11. }
  12.  
  13. def knightMove(legitKnightPositions) {
  14. def knightMoves = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]]
  15. def result = ([0]*64).collate(8)
  16. (0..<8).each { x ->
  17. (0..<8).each { y ->
  18. if (legitKnightPositions[x, y]) {
  19. knightMoves.each { move ->
  20. def newCoord = [x + move[0], y + move[1]]
  21. if (checkCoords(newCoord)) {
  22. result[newCoord[0]][newCoord[1]] = 1
  23. }
  24. }
  25. }
  26. }
  27. }
  28. return result
  29. }
  30.  
  31. def draughtsmanMoves(c) {
  32. return [[-1, -1], [1, -1]].collect { [c[0] + it[0], c[1] + it[1]] }.findAll { checkCoords(it) }
  33. }
  34.  
  35. boolean solve(k, d, move) {
  36. if (d[1] == 0) return false
  37. if (k.flatten().find() == null) return false
  38. if (move == 'white') {
  39. if (k[d[0]][d[1]]) return true
  40. k = knightMove(k)
  41. return solve(k, d, 'black')
  42. }
  43. else {
  44. def moves = draughtsmanMoves(d)
  45. moves.each {
  46. if (it[0] in [1..6]) {
  47. if (k[it[0]][it[1]]) k[it[0]][it[1]] = 0
  48. }
  49. }
  50. def blackWinStrategy = moves.find { solve(k, it, 'white') == false }
  51. return (blackWinStrategy == null)
  52. }
  53.  
  54. return false //d wins
  55. }
  56.  
  57. //def s = new Scanner('a1 b6 white')
  58. def s = new Scanner(System.in)
  59. def tokens = s.nextLine().split(/\s/).toList()
  60. def (knight, draughtsman) = tokens[0..<2].collect(this.&decodeCoords)
  61. def firstMove = tokens[2]
  62. def knightPos = ([0]*64).collate(8)
  63. knightPos[knight[0]][knight[1]] = 1
  64. println solve(knightPos, draughtsman, firstMove) ? "white wins" : "black wins"
  65.  
Success #stdin #stdout 1.61s 333056KB
stdin
e4 e3 white
stdout
white wins