You have a hierarchical structure with items and associated vectors for P, Q, and C, and you want to roll up the cost structure. Let's clarify the data and the goal:
Given:
- I (items):
{"Phase A" "Device 1" "Widget I" "Widget J" "Device 2"}
- P (parent index):
[¯1 0 1 1 0]
This means:
- "Phase A" has no parent (¯1)
- "Device 1" parent is "Phase A" (index 0)
- "Widget I" parent is "Device 1" (index 1)
- "Widget J" parent is "Device 1" (index 1)
- "Device 2" parent is "Phase A" (index 0)
- Q (quantity):
[1 1 100 50 1]
- C (unit cost):
[0 1000 2 16 9000]
- T = Q * C (element-wise multiplication)
Goal:
Roll up the cost structure so that each parent node accumulates the total cost of its children.
Step 1: Calculate total cost per item
T ← Q × C
T is:
| Item | Q | C | T = Q*C |
|---|
| Phase A | 1 | 0 | 0 |
| Device 1 | 1 | 1000 | 1000 |
| Widget I | 100 | 2 | 200 |
| Widget J | 50 | 16 | 800 |
| Device 2 | 1 | 9000 | 9000 |
Step 2: Roll up costs from children to parents
We want to add the children's costs to their parents recursively.
APL code to roll up costs
⍝ I: item names
⍝ P: parent indices (¯1 means no parent)
⍝ T: total cost per item (Q*C)
rollUpCosts ← {
T ← ⍵
P ← ⍺
n ← ≢T
done ← 0
:while ~done
done ← 1
:for i :in ⍳n
p ← P[i]
:if p≥0
old ← T[p]
T[p] ← T[p] + T[i]
:if T[p] ≠ old
done ← 0
:endif
:endif
:endfor
:endwhile
T
}
⍝ Usage:
rolledCosts ← P rollUpCosts T
Explanation:
- We iterate over all items.
- For each item, if it has a parent (p≥0), add its cost to the parent's cost.
- Repeat until no changes occur (costs fully rolled up).
- This handles multiple levels of hierarchy.
Result:
rolledCosts
will give the total cost rolled up to each node, including the root "Phase A".
Example output for your data:
- Widget I and Widget J costs roll up into Device 1.
- Device 1 and Device 2 costs roll up into Phase A.
So:
| Item | Rolled-up Cost |
|---|
| Phase A | 0 + 1000 + 200 + 800 + 9000 = 11000 |
| Device 1 | 1000 + 200 + 800 = 2000 |
| Widget I | 200 |
| Widget J | 800 |
| Device 2 | 9000 |
If you want me to provide the code in another language or a more specific format, just ask!