Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,19 @@
defmodule RC do
def spiral_matrix(n) do
wide = length(to_char_list(n*n-1))
fmt = String.duplicate("~#{wide}w ", n) <> "~n"
runs = Enum.flat_map(n..1, &[&1,&1]) |> tl
delta = Stream.cycle([{0,1},{1,0},{0,-1},{-1,0}])
running(Enum.zip(runs,delta),0,-1,[])
|> Enum.with_index |> Enum.sort |> Enum.chunk(n)
|> Enum.each(fn row -> :io.format fmt, (for {_,i} <- row, do: i) end)
end
defp running([{run,{dx,dy}}|rest], x, y, track) do
new_track = Enum.reduce(1..run, track, fn i,acc -> [{x+i*dx, y+i*dy} | acc] end)
running(rest, x+run*dx, y+run*dy, new_track)
end
defp running([],_,_,track), do: track |> Enum.reverse
end
RC.spiral_matrix(5)

View file

@ -0,0 +1,30 @@
defmodule RC do
def spiral_matrix(n) do
wide = String.length(to_string(n*n-1))
fmt = String.duplicate("~#{wide}w ", n) <> "~n"
right(n,n-1,0,[]) |> Enum.reverse |> Enum.with_index |> Enum.sort |> Enum.chunk(n) |>
Enum.each(fn row ->
:io.format fmt, (for {_,i} <- row, do: i)
end)
end
def right(n, side, i, coordinates) do
down(n, side, i, Enum.reduce(0..side, coordinates, fn j,acc -> [{i, i+j} | acc] end))
end
def down(_, 0, _, coordinates), do: coordinates
def down(n, side, i, coordinates) do
left(n, side-1, i, Enum.reduce(1..side, coordinates, fn j,acc -> [{i+j, n-1-i} | acc] end))
end
def left(n, side, i, coordinates) do
up(n, side, i, Enum.reduce(side..0, coordinates, fn j,acc -> [{n-1-i, i+j} | acc] end))
end
def up(_, 0, _, coordinates), do: coordinates
def up(n, side, i, coordinates) do
right(n, side-1, i+1, Enum.reduce(side..1, coordinates, fn j,acc -> [{i+j, i} | acc] end))
end
end
RC.spiral_matrix(5)

View file

@ -0,0 +1,19 @@
defmodule RC do
def spiral_matrix(n) do
fmt = String.duplicate("~#{length(to_char_list(n*n-1))}w ", n) <> "~n"
Enum.flat_map(n..1, &[&1, &1])
|> tl
|> Enum.reduce({{0,-1},{0,1},[]}, fn run,{{x,y},{dx,dy},acc} ->
side = for i <- 1..run, do: {x+i*dx, y+i*dy}
{{x+run*dx, y+run*dy}, {dy, -dx}, acc++side}
end)
|> elem(2)
|> Enum.with_index
|> Enum.sort
|> Enum.map(fn {_,i} -> i end)
|> Enum.chunk(n)
|> Enum.each(fn row -> :io.format fmt, row end)
end
end
RC.spiral_matrix(5)