3

Question is:

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 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.

Test case: [n,n,n,s,n,s,n,s,n,s] is true.

I am having difficulty to understand how to ensure that the person reached his starting point.

I know it must be a simple shortest path mathematics.

But I am really not getting starting point reached logic.

Please help.

6
  • I am not sure i understand it correctly, but why don't you store the starting point and then set it as new destination? Commented Apr 1, 2016 at 11:34
  • If you're going ask for help with homework, at least try to figure it out. Commented Apr 1, 2016 at 11:34
  • @John In the above test case starting point is 'n' whereas end point is 's' then how the test case result is true ? Am I misunderstood ? Commented Apr 1, 2016 at 11:37
  • Oh i thought nand s are standing for north, south, etc. That is a bit confusing. Commented Apr 1, 2016 at 11:40
  • @john please check what Sorin said. I think i.e the correct logic to check if the person reached starting point. Commented Apr 1, 2016 at 11:46

2 Answers 2

6

Count the number of each characters. number of 'n' must be equal to the number of 's' and the number of 'e' must be equal to the number of 'w' and the total sum must be 10.

The example is wrong, because at the end you are 2 blocks north of your starting point so the answer should be false.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for helping me to understand the logic. :-) . I was also wondering how the example returns true.
1

This may help

    function isValidWalk(walk) {
        let n = walk.filter(a => a =='n').length;
        let s = walk.filter(a => a=='s').length;
        let w = walk.filter(a => a=='w').length;
        let e = walk.filter(a => a=='e').length;

        return walk.length == 10 && n == s && w == e

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.