Arjita Mitra
Arjita Mitra

Reputation: 962

Javascript programing on array

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.

Upvotes: 3

Views: 609

Answers (2)

ekocibar
ekocibar

Reputation: 31

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

    }

Upvotes: 1

Sorin
Sorin

Reputation: 11968

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.

Upvotes: 6

Related Questions