Skip to content

Instantly share code, notes, and snippets.

@somacdivad
Created August 12, 2022 03:10
Show Gist options
  • Save somacdivad/a3c5914d78ba9b81c6bc1fc0183edc6b to your computer and use it in GitHub Desktop.
Save somacdivad/a3c5914d78ba9b81c6bc1fc0183edc6b to your computer and use it in GitHub Desktop.
using Base.Iterators
RIGHT = (0, 1)
DOWN = (1, 0)
LEFT = (0, -1)
UP = (-1, 0)
function involute(n::Int)::Matrix{Int}
directions = cycle((RIGHT, DOWN, LEFT, UP))
repeats = pushfirst!(collect(flatten(zip(n-1:-1:1, n-1:-1:1))), n-1)
moves = flatten(repeated(d, r) for (d, r) in zip(directions, repeats))
indices = pushfirst!(accumulate(.+, moves), (0, 0))
sorted_nums = sort(1:n^2, by=(i)->indices[i])
return transpose(reshape(sorted_nums, (n, n)))
end
display(involute(5))
# 5×5 transpose(::Matrix{Int64}) with eltype Int64:
# 1 2 3 4 5
# 16 17 18 19 6
# 15 24 25 20 7
# 14 23 22 21 8
# 13 12 11 10 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment