I’m building a directed graph of possible game scores from (0,0) up to a score of N, together with a dictionary pointing from the score to the corresponding node.
I’d like to make it as efficient as possible. Currently for N = 1000 it’s taking about 1.8s to run on my i7-8550U (1.8GHz) machine.
I’d like to know if this is a reasonable speed, or I could squeeze more out of it, and if so, how.
I’m using recursion to create this; using a while-loop together with a queue slightly slows it down. Here’s the complete code:
using StaticArrays
using BenchmarkTools
const NEXT_SCORE_CONSTANT = [SVector(0,1), SVector(1,0)]
const END_SCORE = 1000
struct MyNode{T}
data::T
children::Vector{MyNode{T}}
parents::Vector{MyNode{T}}
MyNode(data::T,children=MyNode{T}[],parents=MyNode{T}[]) where T= new{T}(data,children,parents)
end
function constructorProcessNode!(score::SVector{2,Int64}, node::MyNode{SVector{2,Int64}}, nodeDict::Dict{SVector{2,Int64},MyNode{SVector{2,Int64}}})
if (score[1] < END_SCORE) & (score[2] < END_SCORE)
for j in NEXT_SCORE_CONSTANT
nextScore = score+j
if haskey(nodeDict, nextScore)
previouslyCreatedNode = nodeDict[nextScore]
push!(previouslyCreatedNode.parents, node)
push!(node.children, previouslyCreatedNode)
else
newNode = MyNode(nextScore,[],[node])
push!(node.children, newNode)
nodeDict[nextScore] = newNode
constructorProcessNode!(nextScore, newNode, nodeDict)
end
end
end
end
function constructTree()
nodeDict = Dict(SVector(0,0) => MyNode(SVector(0,0)))
constructorProcessNode!(SVector(0,0),nodeDict[[0,0]], nodeDict)
return nodeDict
end
@benchmark constructTree()
BenchmarkTools.Trial:
memory estimate: 477.79 MiB
allocs estimate: 6006056
--------------
minimum time: 1.646 s (23.85% GC)
median time: 1.765 s (29.88% GC)
mean time: 1.789 s (30.73% GC)
maximum time: 1.958 s (37.29% GC)
--------------
samples: 3
evals/sample: 1