The graph array has edges: 1->2 with weight 3, 2->3 with weight 4, 3->1 with weight 5.
Step 2: Trace the for loop output
The loop prints each edge in the format 'from -> to (weight: weight)'. So output matches 1 -> 2 (weight: 3)
2 -> 3 (weight: 4)
3 -> 1 (weight: 5) exactly.
Which code snippet correctly calculates the total weight of edges connected to vertex 2?
hard
A. const total = graph[2].map(edge => edge.weight).length;
B. const total = graph[2].reduce((sum, edge) => sum + edge.weight, 0);
C. const total = graph[2].filter(edge => edge.weight > 0);
D. const total = graph.reduce((sum, edges) => sum + edges.weight, 0);
Solution
Step 1: Understand adjacency list structure
graph[2] is an array of edges connected to vertex 2, each with a weight property.
Step 2: Calculate total weight
Use reduce to sum all edge weights in graph[2]. const total = graph[2].reduce((sum, edge) => sum + edge.weight, 0); correctly sums weights. const total = graph[2].map(edge => edge.weight).length; counts edges, not sum. const total = graph[2].filter(edge => edge.weight > 0); filters edges, no sum. const total = graph.reduce((sum, edges) => sum + edges.weight, 0); tries to reduce graph object, invalid.
Final Answer:
const total = graph[2].reduce((sum, edge) => sum + edge.weight, 0); -> Option B
Quick Check:
Sum weights with reduce = const total = graph[2].reduce((sum, edge) => sum + edge.weight, 0); [OK]
Hint: Use reduce to sum weights in adjacency list [OK]
Common Mistakes:
Using map length instead of sum
Filtering without summing
Reducing wrong data structure
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.