-
-
Save Wikunia/89379a6ac014ea58b332671ff78c3648 to your computer and use it in GitHub Desktop.
Collatz Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using CairoMakie | |
using LightGraphs | |
using GraphMakie | |
using NetworkLayout | |
function create_collatz_node_rec(g, n::Int, max_n::Int) | |
child1n = n*2 | |
if child1n <= max_n | |
add_edge!(g, n, child1n) | |
create_collatz_node_rec(g, child1n, max_n) | |
end | |
if (n-1) % 3 == 0 | |
child2n = (n-1) ÷ 3 | |
if child2n > 1 && child2n <= max_n && child2n % 2 == 1 | |
add_edge!(g, n, child2n) | |
create_collatz_node_rec(g, child2n, max_n) | |
end | |
end | |
return | |
end | |
function build_tree(max_n) | |
g = SimpleDiGraph(max_n) | |
create_collatz_node_rec(g, 1, max_n) | |
return g | |
end | |
function mylayout(g) | |
layout = Buchheim()(g) | |
l = map(layout) do p | |
return Point2(p[1], p[2]*5.0) | |
end | |
return l | |
end | |
function main() | |
fig = Figure(resolution=(500,1000)) | |
fig[1,1] = ax = Axis(fig) | |
g = build_tree(100) | |
intree = connected_components(g)[1] | |
g = g[intree] | |
nlabels_align = [(:center, :bottom) for v in vertices(g)] | |
nlabels_offset = [Point2(0.0,0.0) for v in vertices(g)] | |
nlabels = string.(intree) | |
p = graphplot!(ax, g; layout=mylayout, | |
nlabels=nlabels, | |
nlabels_offset=nlabels_offset, | |
nlabels_align, | |
arrow_show=false | |
) | |
hidedecorations!(ax); hidespines!(ax) | |
xlims!(ax, -3, 3) | |
ylims!(ax, -290, 10) | |
for v in vertices(g) | |
if isempty(inneighbors(g, v)) # root | |
nlabels_offset[v] = Point2(0.0, 0.1) | |
elseif isempty(outneighbors(g, v)) #leaf | |
@show v | |
nlabels_offset[v] = Point2(0.0,-8.0) | |
else | |
# check if child of a parent of two | |
parent = inneighbors(g, v)[1] | |
if length(outneighbors(g, parent)) == 2 | |
nlabels_offset[v] = Point2(0.0,0.2) | |
else | |
nlabels_offset[v] = Point2(0.12*length(nlabels[v]),-2.0) | |
end | |
end | |
end | |
p.nlabels_offset = nlabels_offset | |
fname = "collatz_tree" | |
save(fname, fig) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment