javascript - Find head of link chain -
using lodash, have created array of pairs, each representing source , destination of link. given path of links, have:
[ [a, b], [a, c], [d, c] ]
it given first element first link in chain. wanted map pairs key/value map object , go through keys and/or values find head.
simplified algorithm:
keys.contains(a) || values.contains(a)
if either returns true (excluding pair itself, naturally), not head. so, starting first pair, keys.contains(a) || values.contains(a) returns true not head, , keys.contains(b) || values.contains(b) returns false - must head.
the problem: can't map pairs object, since there might key/value duplicates override each other.
i.e., examples above, resulting object be:
{ a: c, d: c }
i know can loop through them, reluctant many loops unless have to...
any ideas of more efficient solution?
i assume source key , destination value. roots of directed graph keys not occur value. (the leafs: vice versa).
a
root, d
. b
, c
not. condition should keys.contains(a) && !values.contains(a)
.
you might not have root @ though if objects point each other ([ [a, b], [b, a] ]
) or if points ([ [a, a] ]
).
now if eliminate self references, can collect keys , values. roots iterate on keys , test if aren't value. leafs, iterate on values , test if aren't key.
hth, i'm not sure understood question correctly.
Comments
Post a Comment