I’m currently doing the Advent of Code challenges (I’m not asking for help regarding solving it) and for day 4 I’m trying to use an array of vectors.
For the creation I tried fill(Vector{Int}(), (1000, 1000)) however this copies the result of Vector{Int}()
So, whenever I do push!(arr[y, x], elem) all positions get elem added to them since they’re all the same one.
Is this desired behavior? I understand it works for literal values like 3.14 or "hello" however for my use case the only solution I see would be
function array_of_empty_vectors(T, dims...)
array = Array{Vector{T}}(undef, dims...)
for i in eachindex(array)
array[i] = Vector{T}()
end
array
end
# this creates a 2x3 matrix with independent Vector{Int}()'s
array_of_empty_vectors(Int, 2, 3)
You can do (f->f()).(fill(()->Vector{Int}(),2,3)), but it’s not that readable. And unlike the comprehension, it needlessly allocates a temporary array of functions.
In short, fill a matrix with copies of an anonymous function that for any input value produces a fresh empty vector. Then transform that matrix into a new matrix by, element for element, running that function with 0 as input. The result is a matrix of empty vectors.
Sorry about that, I had to trick the dot broadcast syntax into doing what I wanted. That’s why I regarded the comprehension as the standard solution.