6__Take_a_Ten_Minute_Walk.js 1.5 KB

12345678910111213141516171819202122232425262728
  1. // You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.
  2. // Note: you will always receive a valid array containing a random assortment of direction letters ('n', 's', 'e', or 'w' only). It will never give you an empty array (that's not a walk, that's standing still!).
  3. function isValidWalk(walk) {
  4. if (walk.length != 10) return false;
  5. let ns = 0;
  6. let ew = 0;
  7. walk.forEach((el) => {
  8. switch (el) {
  9. case "n":
  10. ns++;
  11. break;
  12. case "s":
  13. ns--;
  14. break;
  15. case "e":
  16. ew++;
  17. break;
  18. case "w":
  19. ew--;
  20. break;
  21. }
  22. });
  23. return ns || ew ? false : true;
  24. }
  25. isValidWalk(["n", "s", "n", "s", "n", "s", "n", "s", "n", "s"]);