Javascript Arrays: Take a Ten Minute Walk
- Get link
- Other Apps
Codewars Problem and solution with approach explained
Objective:
In this challenge, we will learn about arrays in javascript.
Problem statement:
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 – every time 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.
Sample test cases:
Test.expect(isValidWalk(['n','s','n','s','n','s','n','s','n','s']), 'should return true');
Test.expect(!isValidWalk(['w','e','w','e','w','e','w','e','w','e','w','e']), 'should return false');
Test.expect(!isValidWalk(['w']), 'should return false');
Test.expect(!isValidWalk(['n','n','n','s','n','s','n','s','n','s']), 'should return false');
Explanation:
We must figure out a way to check that you have walked exactly ten steps i.e the length of array/object should be 10.
Second point to be considered is the steps taken in each direction should cancel each other (in other words should be equal) so that you land at the same point after the walk, then only we can return true. Else it will return false.
Keeping these 2 points in mind, let’s jump to the solution now:
Solution :
function isValidWalk(walk) {
var input = Array.from(walk);
var nCount = 0,
sCount = 0,
wCount = 0,
eCount = 0;
if (input.length == '10') {
input.forEach((value) => {
if (value == 'n')
nCount++;
if (value == 's')
sCount++;
if (value == 'w')
wCount++;
if (value == 'e')
eCount++;
})
if ((nCount == sCount) && (wCount == eCount)) {
return true;
} else
return false;
} else
return false;
}
- Get link
- Other Apps
Comments
How beautifully pertained to desired solution. ❣️
ReplyDelete