ラングトンのアリの描画
Posted feedbacks - Groovy
面白いですね。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | // 盤面の幅
WIDTH=100
HEIGHT=100
// 盤面の値
WHITE=0
BLACK=1
// 上下左右移動する際のリニア増減分
UP_DIFF=-WIDTH
RIGHT_DIFF=+1
DOWN_DIFF=+WIDTH
LEFT_DIFF=-1
// 上下左右移動に対応するリニア増減分を保存してある配列
direcVec=[UP_DIFF,RIGHT_DIFF,DOWN_DIFF,LEFT_DIFF]
// 上下左右の方向を表す定数値
UP=0
RIGHT=1
DOWN=2
LEFT=3
def move(x, y, dir) {
def pos = x + y*WIDTH
pos += direcVec[dir]
if (! (pos in (0 ..< WIDTH*HEIGHT))) {
throw new Exception("over")
}
x = pos % WIDTH
y = pos.intdiv(WIDTH)
return [x, y]
}
def reverse(x, y) {
def pos = x + y*WIDTH
bd[pos] = -(bd[pos]-1)
}
def color(x, y) {
def pos = x + y*WIDTH
bd[pos]
}
def turnRight(dir) {
(dir+1) % 4
}
def turnLeft(dir) {
(dir-1) % 4
}
def displayBoard() {
for (int y=0; y<HEIGHT; y++) {
for (int x=0; x<WIDTH; x++) {
print bd[x + y*WIDTH] == WHITE ? ' ' : '*'
}
println ""
}
}
def doit() {
def dir = RIGHT
while (true) {
def oldX=x
def oldY=y
if (color(x,y) == WHITE) { // 白なら右回転
dir = turnRight(dir)
}
else { // 白ではないなら左回転
dir = turnLeft(dir)
}
(x,y) = move(x,y,dir)
reverse(oldX, oldY)
}
}
// 盤面
bd = new int[WIDTH*HEIGHT]
// 画面の中央に配置
x = WIDTH.intdiv(2)
y = HEIGHT.intdiv(2)
try {
doit()
}
catch (Exception e) {
displayBoard()
}
|

Songmu #9331() [ JavaScript ] Rating8/10=0.80
- 黒いマスにアリがいた場合、90°右に方向転換し、そのマスの色を反転させ、1マス前進する。
- 白いマスにアリがいた場合、90°左に方向転換し、そのマスの色を反転させ、1マス前進する。
詳しくはWikipedia等で調べるか、参考ページに拙作のデモがありますのでご覧下さい。
see: JavaScriptでラングトンの蟻
Rating8/10=0.80-0+
[ reply ]