题目:
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.
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!).
我的答案:
1 function isValidWalk(walk) { 2 //insert brilliant code here 3 if(walk.length!=10){ return false;} 4 var x=0,y=0; 5 for(var i=0;i<walk.length;i++){ 6 switch(walk[i]){ 7 case "n":y++;break; 8 case "s":y--;break; 9 case "w":x++;break; 10 case "e":x--;break; 11 } 12 } 13 return x==0 && y==0; 14 15 }
优秀答案:
1 function isValidWalk(walk) { 2 function count(val) { 3 return walk.filter(function(a){return a==val;}).length; 4 } 5 return walk.length==10 && count('n')==count('s') && count('w')==count('e'); 6 }
1 function isValidWalk(walk) { 2 var dx = 0 3 var dy = 0 4 var dt = walk.length 5 6 for (var i = 0; i < walk.length; i++) { 7 switch (walk[i]) { 8 case 'n': dy--; break 9 case 's': dy++; break 10 case 'w': dx--; break 11 case 'e': dx++; break 12 } 13 } 14 15 return dt === 10 && dx === 0 && dy === 0 16 }