Sha256: 8ecefbbc09ca5b273d666e53de090eb56055715ebc1f9cc158191e176290f194

Contents?: true

Size: 1015 Bytes

Versions: 2

Compression:

Stored size: 1015 Bytes

Contents

pad = (n, len) ->
  len ?= 3
  res = n.toString()
  res = ' '+res while res.length < len
  res

shifts = [[-2, +1], [-1, +2], [+1, +2], [+2, +1], [+2, -1], [-2, -1]]

class Solver

  constructor: (@n, @left_free) ->
    @nn = @n * @n
    @n2 = @n + @n
    @desk = []
    @depth = 0
    for r in [0...@n]
      @desk.push (0 for col in [0...@n])
    @solve 0, 0

  solve: (r, c) ->
    @desk[r][c] = ++@depth
    return true if @depth + @left_free >= @nn
    for [r1, c1] in @moves(r, c)
      return true if @solve(r1, c1)
    @desk[r][c] = 0
    @depth--
    false

  # Coffeescript does not support generators
  moves: (r, c) ->
    res = []
    for [sr, sc] in shifts
      r1 = r + sr
      if 0 <= r1 < @n
        c1 = c + sc
        if 0 <= c1 < @n && @desk[r1][c1]==0
          res.push [r1, c1]
    res

  toString: ->
    res = []
    for r in [0...@n]
      res.push ( (if x==0 then '  .' else pad(x,3)) for x in @desk[r]).join('')
    res.join "\n"

return (n, left) ->
  new Solver(n, left).toString()

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
h8-0.2.4 benchmark/knightsmove.coffee
h8-0.2.3 benchmark/knightsmove.coffee