DAY 26
0

# 今日kata

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.

``````['n','s','n','s','n','s','n','s','n','s','n','s']  ==> fail
['n','w','n','w','n','w','n','w','n','w']          ==> fail
['n','s','e','w','n','s','e','w','n','s']          ==> pass
['n','n','n','s','s','s','e','w','n','s']          ==> pass

``````

## 構想&解法

``````function isValidWalk(walk) {
let position={'x':0, 'y':0}

for (let step of walk){
switch(step){
case 'n':
position.y++
break;
case 's':
position.y--
break;
case 'w':
position.x--
break;
case 'e':
position.x++
break;
}
}
return position.x===0 && position.y===0 && walk.length===10? true: false

}
``````

「10分鐘」內要回到原點，座標軸概念，用`x``y軸`劃分東西南北，往北:y++；往南:y--；往東:x++；往西:x--

## 其他解法觀摩

``````function isValidWalk(walk) {
function count(val) {
return walk.filter(function(a){return a==val;}).length;
}
return walk.length==10 && count('n')==count('s') && count('w')==count('e');
}
``````

• walk.length==10，是否能剛好在10分鐘回來
• count('n')==count('s')，南北向抵銷
• count('w')==count('e')，東西向抵銷

## 感想

### 什麼code才是好?

code能正常work是基本....不算好

『程式的可讀性、可維護性、可變動性都很重要』

`````` function count(val) {
return walk.filter(function(a){return a==val;}).length;
}
``````