Number Place(数独)とSwift 3 (2)

numberplace2

プログラムは常にシンプルであるべきなのですが、まだその段階に達していません。

struct Place {
    var row: Int = -1
    var col: Int = -1
}

class NumBoard {
    var table       = [[Int]]()
    var emptyPlaces = [Place]()
    var place       = Place()
    let nplaces : Int
    var putCount: Int

    init() {
        table = [[7,0,3, 0,0,0, 0,0,0],
                 [0,5,1, 3,7,0, 4,0,0],
                 [6,0,0, 0,1,0, 0,2,0],
                 [0,0,4, 6,0,0, 0,0,0],
                 [0,0,0, 0,0,7, 0,8,0],
                 [5,0,0, 2,3,1, 9,0,0],
                 [3,0,0, 0,2,4, 0,9,1],
                 [0,0,0, 0,0,0, 8,4,0],
                 [0,0,7, 0,9,0, 2,0,0]]

        for rr in 0...8 {
            for cc in 0...8 {
                if table[rr][cc] == 0 {
                    place.row = rr
                    place.col = cc
                    emptyPlaces.append(place)
                 }
            }
        }
        putCount = 0
        nplaces = emptyPlaces.count
        myprint(table: table)
    }

    func myprint(table: [[Int]]) {
        print("-----------------")
        for rr in 0...8 {
            for cc in 0...8 {
                print(table[rr][cc], terminator: " ")
            }
            print("")
        }
        print("-----------------")
    }
    
    func isSafeForNum(place: Place, num: Int) -> Bool {
        for rr in 0...8 {
            if num == table[rr][place.col] { return false }
        }
        for cc in 0...8 {
            if num == table[place.row][cc] { return false }
        }
        let rowBase = (place.row / 3) * 3
        let colBase = (place.col / 3) * 3
        for rr in 0...2 {
            for cc in 0...2 {
                if num == table[rowBase+rr][colBase+cc] { return false }
            }
        }
        return true
    }

    func dropNum(index: Int) {
        /* could be better */
    }

    func play() {
        dropNum(index: 0)
        myprint(table: table)
    }
}

let myboard = NumBoard()
myboard.play()

ところで、あなたは以下のような行が気に入らないかもしれません。

let rowBase = (place.row / 3) * 3
let colBase = (place.col / 3) * 3
  for rr in 0...2 {
    for cc in 0...2 {
      if num == table[rowBase+rr][colBase+cc] { return false }
    }
  }

私の意見では、この方がずっと目に優しいと思います。3blockSizeに、そして、2blockSize-1に置き換えるよりは。

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.