A functional implementation of Depth-First Search
For the last few weeks I have been learning Racket. Coincidentally, Advent Of Code is back one more year. I decided to try to solve it with Racket, to force myself to learn more about the syntax and, well, use it.
In particular, Day 7 is a graph problem. Basically we want to see how many vertices can reach a particular destination.
This is straighforward. We can use breadth-first search (BFS) or depth-first search (DFS) on every vertex, and that way we’ll know how many can reach it.
OOP and cars
When I first learned Object Oriented Programming (OOP) a few years ago the book I was reading had a strange obsession with cars.
Imagine you have a car, it said. A car is composed of a body, four tires, and an engine. Furthermore, you can have a Ferrari, which is a specific type of car, or you could build cars with different types of wheels. This is the way it explained the concepts of Polymorfism, Inheritance, Composition, and Instantiation.
Shuffling and permutations
How would you shuffle a deck of cards? A couple of weeks ago I was talking to a friend about the problem of shuffling a deck of cards. His take on it was to do:
for i = 1 to n do a[i] = i for i = 1 to n-1 do swap[a[i],a[Random[i,n]] My idea was:
for i = 1 to n do a[i] = i for i = n to 1 do swap[a[i],a[random[1,i]] Both of them seemed reasonable, but were any of them correct?