2020-05-15 5kyu Car Park Escape

2020-05-15  本文已影响0人  苦庭

https://www.codewars.com/kata/591eab1d192fe0435e000014/javascript

My answer

function escape(arr){
  var res = [];
  var curPos, next, diff, dCount = 0, dFlag=false, startFlag=true;
  for(let level=0; level<arr.length; level++){
    if(!arr[level].includes(2) && startFlag) continue;
    if(startFlag) curPos = arr[level].indexOf(2);
    startFlag = false;
    diff = 0;
    
    if(curPos == arr[level].length-1 && level == arr.length-1) return res;

    if(arr[level].reduce((a,b)=>a+b) == 0 || level == arr.length-1){
      next = arr[level].length-1;
      diff = curPos - next;
    }else{
      next = arr[level].indexOf(1);
      diff = curPos - next;
    } 
    
    if(diff>0) {
      res.push("L"+diff);
      curPos = curPos - diff;
      dFlag = false;
    } else if(diff<0) {
      res.push("R"+(-diff));
      curPos = curPos - diff;
      dFlag = false;
    }
    let dCount = 0;
    if(arr[level][curPos]===1 && dFlag) continue;
    for(let l=level; arr[l][curPos]===1;  ++dCount, ++l) ;
    if(dCount!=0) res.push("D"+(dCount));
    dFlag = true;
  }
  return res;
}

哪里要改进?

Best Answer

function escape(carpark){
  var seq = [], i=carpark.findIndex(r=>r.includes(2)), x=carpark[i].indexOf(2);
  while(i<carpark.length-1) {
    let idx = carpark[i].indexOf(1), down = 0,
        dist = idx-x;
    seq.push(dist<0?`L${-dist}`:`R${dist}`);
    for(;carpark[i][idx]===1; down++,i++);
    seq.push(`D${down}`);
    x = idx;
  }
  return x===carpark[0].length-1?seq:seq.concat(`R${carpark[0].length-1-x}`);
}

哪里好?

Recap

上一篇下一篇

猜你喜欢

热点阅读