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 }
  • 相关阅读:
    JSP | 基础 | 加载类失败:com.mysql.jdbc.Driver
    5.Nginx的session一致性(共享)问题配置方案1
    4.Nginx配置文件Nginx.conf_虚拟主机配置规则
    3.Https服务器的配置
    2.Nginx基本配置
    1.Nginx安装
    DA_06_高级文本处理命令
    7.控制计划任务crontab命令
    6.Shell 计划任务服务程序
    5.Shell 流程控制语句
  • 原文地址:https://www.cnblogs.com/hiluna/p/8629245.html
Copyright © 2011-2022 走看看