zoukankan      html  css  js  c++  java
  • codewars--js--ten minutes walk

    题目:

    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 }
  • 相关阅读:
    js中的投掷筛子的小游戏
    js俩习题
    python中socket理论
    python实现计时器(装饰器)
    python之正则表达式(re模块)用法总结
    python练习题之随机生成验证码
    python中模块介绍
    python中的装饰器基本理论
    python类与对象练习题扑克牌
    Java抓取网页数据
  • 原文地址:https://www.cnblogs.com/hiluna/p/8629245.html
Copyright © 2011-2022 走看看