Babylonian spiral: Difference between revisions

Content added Content deleted
m (→‎{{header|Julia}}: iterator version)
m (priority queue)
Line 150: Line 150:
=== iterator version ===
=== iterator version ===
See Python iterator version.
See Python iterator version.
<syntaxhighlight lang="julia">using Plots
<syntaxhighlight lang="julia">using DataStructures
using Plots


struct SquareSums end
struct SquareSums end


function Base.iterate(ss::SquareSums, state = (1, Tuple{Int, Int, Int}[]))
function Base.iterate(ss::SquareSums, state = (1, PriorityQueue{Tuple{Int, Int, Int}, Int}()))
i, sums = state
i, sums = state
while isempty(sums) || i^2 <= sums[1][1]
while isempty(sums) || i^2 <= peek(sums)[2]
push!(sums, (i^2, i, 0))
enqueue!(sums, (i^2, i, 0) => i^2)
i += 1
i += 1
end
end
nextsum, xy = peek(sums)[2], Tuple{Int, Int}[]
sort!(sums)
while !isempty(sums) && peek(sums)[2] == nextsum # pop all vectors with same length
nextsum, xy = sums[1][1], Tuple{Int, Int}[]
while !isempty(sums) && sums[1][1] == nextsum # pop all vectors with same length
nextsum, a, b = dequeue!(sums)
nextsum, a, b = popfirst!(sums)
push!(xy, (a, b))
push!(xy, (a, b))
if a > b
if a > b
push!(sums, (a^2 + (b + 1)^2, a, b + 1))
hsq = a^2 + (b + 1)^2
enqueue!(sums, (hsq, a, b + 1) => hsq)
end
end
end
end