76 lines
1.6 KiB
Text
76 lines
1.6 KiB
Text
let xInc = [0, 1, -1, 0]
|
|
let yInc = [-1, 0, 0, 1]
|
|
let north = 0
|
|
let east = 1
|
|
let west = 2
|
|
let south = 3
|
|
|
|
let leftTurns = [ west, north, south, east ]
|
|
let rightTurns = [ east, south, north, west ]
|
|
|
|
func move(ant) {
|
|
ant.position.x += xInc[ant.direction]
|
|
ant.position.y += yInc[ant.direction]
|
|
}
|
|
|
|
func Array.Step(ant) {
|
|
var ptCur = (var x: ant.position.x + ant.origin.x, var y: ant.position.y + ant.origin.y)
|
|
var leftTurn = this[ptCur.x][ptCur.y]
|
|
ant.direction =
|
|
if leftTurn {
|
|
leftTurns[ant.direction]
|
|
} else {
|
|
rightTurns[ant.direction]
|
|
}
|
|
this[ptCur.x][ptCur.y] = !this[ptCur.x][ptCur.y]
|
|
move(ant)
|
|
ptCur = (x: ant.position.x + ant.origin.x, y: ant.position.y + ant.origin.y)
|
|
ant.outOfBounds =
|
|
ptCur.x < 0 ||
|
|
ptCur.x >= ant.width ||
|
|
ptCur.y < 0 ||
|
|
ptCur.y >= ant.height
|
|
ant.position
|
|
}
|
|
|
|
func newAnt(width, height) {
|
|
(
|
|
var position: (var x: 0, var y: 0),
|
|
var origin: (x: width / 2, y: height / 2),
|
|
var outOfBounds: false,
|
|
var isBlack: [],
|
|
var direction: east,
|
|
var width: width,
|
|
var height: height
|
|
)
|
|
}
|
|
|
|
func run() {
|
|
let w = 100
|
|
let h = 100
|
|
let blacks = Array.Empty(w, () => Array.Empty(h, false))
|
|
let ant = newAnt(w, h)
|
|
|
|
while !ant.outOfBounds {
|
|
blacks.Step(ant)
|
|
}
|
|
|
|
var iRow = 0;
|
|
|
|
while iRow < w {
|
|
var iCol = 0;
|
|
var ln = ""
|
|
while iCol < h {
|
|
ln += if blacks[iCol][iRow] {
|
|
"#"
|
|
} else {
|
|
" "
|
|
}
|
|
iCol += 1
|
|
}
|
|
print(ln)
|
|
iRow += 1
|
|
}
|
|
}
|
|
|
|
run()
|