Graphs
JavaScript · Unit 23: Data structures
- Full plan
- JavaScript
- 10 exercises
A graph doesn't store a row of data: it stores who is connected to whom. Friendships, streets between neighborhoods, bus stops.
The most common shape is an object: each key is a point and its value is the array of its neighbors.
const g = {
mia: ["leo", "ava"],
leo: ["mia"],
ava: ["mia"],
};
console.log(g.mia);
console.log(g.mia.length);Prints
[ 'leo', 'ava' ] 2
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Fill in the blank to ask whether leo is one of mia's neighbors.
3. Predict the output
What does this code print?
4. Multiple choice
What is true about this graph?
5. Put the lines in order
Put
linked(g, a, b)in order. It says whether a connection leavesatowardsb, and givesfalseifaisn't even in the graph.6. Predict the output
This graph has no way back, so the
Setisn't needed. In what order does it print?7. Complete the code
Fill in the blank so nobody gets visited twice.
8. Find the bug
It should walk breadth-first: a first, then its two neighbors b and c, and d at the very end. Which line has the error?
9. Find the case that fails
howMany(p)returns how many neighbors that person has, or 0 if they aren't in the graph. Which call breaks it?10. Predict the output
The walk starts at mia and
seenkeeps whoever it reached. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.