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?

  • Laura

    Administrator
    April 18, 2023 at 12:00 am

    Really like this solution, haven’t seen a scan indexing before. Just wanted to add to it so the user doesn’t have to define calc and outputTree:

    tree:([]parent:`A`A`A`B`B`E`E;child:`B`C`D`E`F`G`H;data:(1;2;3;4;5;6;7)); 
    traverse_dict:exec child!parent from tree; root:`A; // value pairing appending root node with 1 factor 
    calc:(root, exec child from tree)!1,exec data from tree; // calc:`A`D`C`B`F`E`G`H!1 3 2 1 5 4 6 7; 
    traverse_func:{[st;end;dict;calc] prd calc except[(dict) end;(dict) st] }[;;traverse_dict;calc]; 
    outputTree:exec child by parent from tree; 
    outputTree:key[outputTree]!raze each (value outputTree),' outputTree value outputTree; 
    outputTree:(key outputTree)!except[;key outputTree]each distinct each (raze/) each (outputTree)each value outputTree; 
    p:raze (count each value outputTree)#'key[outputTree]; 
    c:raze value outputTree; 
    outputTree:([] parent:p;child:c); // outputTree:([] parent:`A`A`A`A`A`B`B`B`E`E;child:`C`D`F`G`H`F`G`H`G`H); // output update 
    val:traverse_func'[parent;child] from outputTree

    There’s probably a more concise way to do the above so keen to see any further improvements.