How to resolve the algorithm Spiral matrix step by step in the E programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Spiral matrix step by step in the E programming language
Table of Contents
Problem Statement
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Spiral matrix step by step in the E programming language
Source code in the e programming language
/** Missing scalar multiplication, but we don't need it. */
def makeVector2(x, y) {
return def vector {
to x() { return x }
to y() { return y }
to add(other) { return makeVector2(x + other.x(), y + other.y()) }
to clockwise() { return makeVector2(-y, x) }
}
}
/** Bugs: (1) The printing is specialized. (2) No bounds check on the column. */
def makeFlex2DArray(rows, cols) {
def storage := ([null] * (rows * cols)).diverge()
return def flex2DArray {
to __printOn(out) {
for y in 0..!rows {
for x in 0..!cols {
out.print(.format("%3d", [flex2DArray[y, x]]))
}
out.println()
}
}
to get(r, c) { return storage[r * cols + c] }
to put(r, c, v) { storage[r * cols + c] := v }
}
}
def spiral(size) {
def array := makeFlex2DArray(size, size)
var i := -1 # Counter of numbers to fill
var p := makeVector2(0, 0) # "Position"
var dp := makeVector2(1, 0) # "Velocity"
# If the cell we were to fill next (even after turning) is full, we're done.
while (array[p.y(), p.x()] == null) {
array[p.y(), p.x()] := (i += 1) # Fill cell
def next := p + dp # Look forward
# If the cell we were to fill next is already full, then turn clockwise.
# Gimmick: If we hit the edges of the array, by the modulo we wrap around
# and see the already-filled cell on the opposite edge.
if (array[next.y() %% size, next.x() %% size] != null) {
dp := dp.clockwise()
}
# Move forward
p += dp
}
return array
}
? print(spiral(5))
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
You may also check:How to resolve the algorithm Show ASCII table step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Roman numerals/Encode step by step in the Cowgol programming language
You may also check:How to resolve the algorithm Copy a string step by step in the X86-64 Assembly programming language
You may also check:How to resolve the algorithm Pernicious numbers step by step in the 360 Assembly programming language
You may also check:How to resolve the algorithm Arithmetic/Rational step by step in the PicoLisp programming language