KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ How to walkthrough a tree and calculate value on path? Re: How to walkthrough a tree and calculate value on path?

  • gyorokpeter-kx

    Member
    April 17, 2023 at 12:00 am

    This gets it done while remaining somewhat readable:

    child:select (child,'data) by parent from tree; 
    res:(); 
    a:([]start:key[child];end:key[child];val:1); 
    while[count a; res,:select from a where not end in key child; b:ungroup update nxt:child end from (delete from a where not end in key child); a:select start, end:nxt[;0], val*nxt[;1] from b; ];

    The answer is given by

    q)`start`end xasc res 
    start end val 
    ------------- 
    A     C   2 
    A     D   3 
    A     F   5 
    A     G   24 
    A     H   28 
    B     F   5 
    B     G   24 
    B     H   28 
    E     G   6 
    E     H   7