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 }
  • 相关阅读:
    深入理解加密、解密、数字签名和数字证书
    支付网关的设计
    spring boot Rabbitmq集成,延时消息队列实现
    五一之起一台服务器玩玩-u盘安装centos
    shell初识
    用户身份切换之初窥企业远程用户没root还有root权限
    man帮助文档打印
    开源镜像软件下载网址{转载}
    bash shell第一课
    jQuery常用ajax操作
  • 原文地址:https://www.cnblogs.com/hiluna/p/8629245.html
Copyright © 2011-2022 走看看