Where's Waldo?
You are given a vector of vectors, representing a grid. The grid is filled with values. Your job is to find a given value and return the path into the grid that will get to it.
Here's an example:
(wheres-waldo :W ;; look for :W
[[:A :B :C]
[:D :E :F]
[:G :H :I]
[:J :K :L]
[:M :N :O]
[:P :Q :R]
[:S :T :U]
[:V :W :X]
[:Y :and :Z]]);=> [7 1]
Notice that I can pass [7 1]
to get-in
to find the value.
Notes
- The nested vectors will all be the same length. This is a rectangular grid.
- If the value occurs more than once, you can return coordinates to any of them.
- Return
nil
if you can't find the value.
Bonus
Can you make it work with arbitrarily nested vectors of different sizes?
Have fun with this one! Try out different ways to implement it.
Thanks to to this site for the challenge idea!
I should note that my example of using
reduce-kv
is a bit unusual in that thereduced
result short-circuits the process. In this case,reduce-kv
is being used to efficiently step through the vector. Normally, a reduce process boils the entire collection down to a single value. The usage ofreduced
is a slightly more advanced technique. I would say you rarely need it. It just turns out to be a way of using the efficient machinery to get a desired result in this special case.