Hey there, it's time to get moving.
Today’s challenge is modified from user @JKphobic on CodeWars:
You live in a city where all roads are laid out in a perfect grid. You have the unfortunate habit of arriving too early or too late to your appointments, so you decide to create a Walk Generating App.
Any time you press the button, it will send you an array of one-letter strings representing directions to walk (eg. [‘n’,’s’,’w’,’e’]). You always walk only a single block in a direction. It takes one minute to traverse one city block.
Create a program that will return an array of one-letter strings representing the walk. The program should accept input for the amount of time the user decides to walk and should bring the user back to their starting location.
I wish the streets in my town were structured like this, it would make driving so much easier.
Good luck, happy coding!
Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (21)
My first attempt at one of these coding challenge things!
I'm not great with maths, but I'm guessing that all walks must have an even length, otherwise you can't end up back at your starting location, you'd always be one away...
If that assumption is true, then I think this works:
Basically, for each "pair" of blocks you want to walk, either add
["n", "s"]
or["e", "w"]
to an array, then flatten and shuffle! Because you're always adding both a movement and it's inverse, you'll always end up where you started!Ruby's proc / block thing still confuses me a little so I'm not sure if this is the most elegant one-liner (excluding checking for even walk length), but ayy it works!
Great solution! I believe your assumption holds up and makes this solution nice and elegant!
Great job on your first challenge too!!
nice 🤩
Here my contribution with javascript language:
Here's a trivial solution in Python
If you add the requirement that you can't walk the same street twice...
JS
Not a great solution, but a solution.
And a one-liner but not really randomized, just going north-then-south:
And the link to a demo on CodePen
Just make sure the number of s's and n's is the same, and the same for w's and e's.
Perl solution:
Barely in before/at midnight!
But here is my Rust version!
I took a bit of a different route! @spaciecat killed the simple algorithm answer so I wanted to do something different!
I decided to make a program that lets the user build the path they want to take! Cause why not let the User choose where to explore! I might clean this up and turn it into a full post sometime soon!
Here is a really quick demo GIF
Spacie's algo, in Clojure:
PHP
My solution in Swift language :
Some comments may only be visible to logged-in visitors. Sign in to view all comments.