Spiral matrix: Difference between revisions

Updated to work with Nim 1.4 + removed “^” procedure, removed “newSeqWith”, removed useless type “Pos”
(Updated to work with Nim 1.4 + removed “^” procedure, removed “newSeqWith”, removed useless type “Pos”)
Line 3,145:
 
=={{header|Nim}}==
<lang nim>import sequtils, strutils
 
type Pos = tuple[x, y: int]
 
proc newSeqWith[T](len: int, init: T): seq[T] =
result = newSeq[T] len
for i in 0 .. <len:
result[i] = init
 
proc `^`*(base: int, exp: int): int =
var (base, exp) = (base, exp)
result = 1
 
while exp != 0:
if (exp and 1) != 0:
result *= base
exp = exp shr 1
base *= base
 
proc `$`(m: seq[seq[int]]): string =
result = ""
for r in m:
let lg = result.len
for c in r:
result.addaddSep(" align($c", 2lg) & " "
result.add "\n"align($c, 2)
result[i].add = init'\n'
 
proc spiral(n: Positive): autoseq[seq[int]] =
result = newSeqWith(n, newSeqWith[int]repeat(n, -1, n))
var dx = 1
var dy, x, y = 0
for i in 0 .. < (n^2 * n):
result[y][x] = i
let (nx, ny) = (x+dx, y+dy)
if nx in 0 .. < n and ny in 0 .. < n and result[ny][nx] == -1:
x = nx
y = ny
Line 3,184 ⟶ 3,168:
swap dx, dy
dx = -dx
x = x += dx
y = y += dy
 
echo spiral(5)</lang>
Anonymous user