0

There is a tree:

  • Each row is a path parent node --> child node
  • data means the value of this path.
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));

My question is:

  • For every non-leaf node (Red node in the chart), we can get a subtree based on this non-leaf node as root.
  • Then we can get paths: root -> every leaf node
  • plus, we can get a value to every path, value = multiply each data on this path

This chart shows what I want to say.


For myself, I can get every paths like this. But, I was stuck on how to calculate the data when walkthrough the tree.

map: exec child by parent from tree;
pl:exec distinct parent from tree; / parent list
(map\)pl / get all paths from every non-leaf node

enter image description here

Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36
seizetheday
  • 333
  • 1
  • 6
  • 15

2 Answers2

1

You can try something like that:

q)show paths:(distinct tree`parent),'1; /init paths
`A 1
`B 1
`E 1
q)show paths:{raze{wp:flip value exec child,data from tree where parent in x 0;$[count wp;wp,\:;enlist]x}each x}/[paths]; /build paths
(`G;6;`E;4;`B;1;`A;1)
(`H;7;`E;4;`B;1;`A;1)
(`F;5;`B;1;`A;1)
(`C;2;`A;1)
(`D;3;`A;1)
(`G;6;`E;4;`B;1)
(`H;7;`E;4;`B;1)
(`F;5;`B;1)
(`G;6;`E;1)
(`H;7;`E;1)
q)paths:{reverse 2 cut x}each paths;
q)show res:raze{(x[0;0],'(1_x)[;0])!1_prds x[;1]}each paths; / results include waypoints as well
A B| 1
A E| 4
A G| 24
A H| 28
A F| 5
A C| 2
A D| 3
B E| 4
B G| 24
B H| 28
B F| 5
E G| 6
E H| 7
q)waypoints:(!/)tree`parent`child;
q)end:end where not(end:value waypoints)in key waypoints;
q)show res:(k where(k:key res)[;1]in end)#res; / to get only child from parent
A G| 24
A H| 28
A F| 5
A C| 2
A D| 3
B G| 24
B H| 28
B F| 5
E G| 6
E H| 7

The solution provided is not optimized but provides a general idea on how such a problem should be approached.

  • Keeping a list of paths while iterating through all possible paths and keeping a score
  • To improve the solution, you can do the product within the loop and just keep the start and end position with the final score, instead of storing all the waypoints and scores.
Maurice Lim
  • 468
  • 2
  • 5
0

Steps through the tree from leaves to roots and maintains the running product at each step.

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);

sort:{x iasc 2#/:x:x@'(-1+count each x),\:1 0}
step:{.[z;(::;0);*;]y -2#/:z:(z,'x l)where(l:last each z)in key x}

walk:{
    d:exec child!parent from x;
    w:exec(child,'parent)!data from x;
    sort raze 1_(step[d;w;]\)1,'(except/)x`child`parent
    }

walk tree
`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
cillianreilly
  • 733
  • 4
  • 12