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!
The Java interop call to .indexOf is going to be slow without a type hint. I suggest you try to use plain Clojure as much as possible. Here's a Clojure implementation (assuming v is vector):
If you find yourself needing to (remove nil? ...), you might want to use something like
keep
instead. In this case, you need the index so usekeep-indexed
. Here's a slight variation of your code:I like to use reduce-kv with vectors so here's another solution that also happens to be pretty fast.