Advertisement
Guest User

Untitled

a guest
Aug 16th, 2021
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.57 KB | None | 0 0
  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.  
  3. //    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!).
  4.  
  5. #include <stdbool.h>
  6. #include <stdint.h>
  7.  
  8. #define SPACETIME(t, x, y) ((t << 16) + (x << 8) + y)
  9.  
  10. bool isValidWalk(const char *walk) {
  11.     uint32_t  pos; // position in spacetime
  12.     char     *idx;
  13.  
  14.     pos = SPACETIME(0, 0x80, 0x80);
  15.  
  16.     for(idx = (char *)walk; *idx; ++idx)
  17.         switch(*idx)
  18.         {
  19.             case 'n': pos += SPACETIME(1,  0,  1); break;
  20.             case 's': pos += SPACETIME(1,  0, -1); break;
  21.             case 'w': pos += SPACETIME(1, -1,  0); break;
  22.             case 'e': pos += SPACETIME(1,  1,  0); break;
  23.         }
  24.    
  25.     return pos == SPACETIME(10, 0x80, 0x80);
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement