arrays - Efficient way of flattening a recursive data structure in golang -
i have recursive data structure can contain few different type of data:
type data interface{ // methods } type pair struct { // implements data fst data snd data } type number float64 // implements data
now want flatten chain of pair
s []data
. however, data
in fst
field should not flattened, data in snd
should flattened. e.g:
chain := pair{number(1.0), pair{number(2.0), pair{number(3.0), nil}}} chain2 := pair{pair{number(1.0), number(4.0)}, pair{number(2.0), pair{number(3.0), nil}}}
becomes:
data := []data{number(1.0), number(2.0), number(3.0)} data2 := []data{pair{number(1.0), number(4.0)}, number(2.0), number(3.0)}
my naive approach be:
var data []data chain := pair{number(1.0), pair{number(2.0), pair{number(3.0), nil}}} chain != nil { data = append(data, chain.fst) chain = chain.snd }
is there more efficient approach can flatten data structure 1 in variable chain
[]data
array?
you can use recursive function. on way down, add number of pairs, @ bottom, allocate array, , on way up, fill array front.
if need support arbitrary trees, can add size
method data
, , tree traversal fill array.
Comments
Post a Comment