1. 程式人生 > >JavaScript學習 CodeWars 打怪升級日記 你最少需要準備幾把傘

JavaScript學習 CodeWars 打怪升級日記 你最少需要準備幾把傘

CodeWars 是一個線上程式設計網站,其獎勵機制像打怪升級。你不能檢視高於你級別的問題的答案。除非自己通過提交測試。通過提交之後可以看到各種解法排行榜 。通過對比自己解法和排行榜對比,可以找到差距,提高能力。

題目意思:

題目地址 我簡單的翻譯: 一個人每天從家去公司,如果早晨下雨就從家帶把傘到公司,如果下午不下雨就不把傘帶回家。 如果早晨不下雨,則不帶傘去公司,但是下午下雨會從公司帶傘回家。 輸入為 一個數組值為未來幾天的天氣預報,一天兩次,分別為早上和下午的天氣預報。只有"rainy" 和 "thunderstorms" 需要下雨,其他天氣不需要。 計算出 為了保證不淋雨至少需要幾把傘。 函式名為: minUmbrellas e.g. minUmbrellas(["rainy", "clear", "rainy", "cloudy"]) // should return 2 // Because on the first morning, he needs an umbrella to take, and he leaves it at work. // So on the second morning, he needs a second umbrella.

我的解法

function isRainy(w) {
	if(w === 'rainy'|| w === 'thunderstorms') {
		return true;
	}
	return false;
}

function isHome(day) {
  if(day % 2 === 0) {
    return true; 
  }
  return false;
}
function minUmbrellas(weather) {
  // TODO
  let s = 0,
    h = 0, 
    w = 0,
    ha = [],
    wa = [];
    weather.forEach( (item, index) => {
    	
      if(isRainy(item)) {
        if(isHome(index)) {
          h = h - 1;
          w = w + 1;
        } else {
          w = w -1;
          h = h + 1;
        }
        ha.push(h);
        wa.push(w);
      }
    })
    
    let min = 0;
    ha.forEach( un => {
      if(un < min)  {
        min = un;
      }
    });
    let minW = 0;
    wa.forEach( un => {
    	if( un < minW) {
    		minW = un;
    	}
    })
    return -min - minW;
}

codewars最佳實踐

function minUmbrellas(w) {
  var rain="rainy,thunderstorms",home=0,office=0
  for(var i=0;i<w.length;i+=2){
    if(rainingAtMorning()){
      if(noUmbrellaInHome()) buyAnUmbrellaAtHome()
      takeUmbrellaToOffice()
      if(rainingAtAfternoon()) takeUmbrellaToHome()
    }
    else if(rainingAtAfternoon()) {
      if(noUmbrellaInOffice()) buyAnUmbrellaAtOffice()
      takeUmbrellaToHome()
    }
  }
  return home+office
  
  function rainingAtMorning(){return rain.includes(w[i])}
  function rainingAtAfternoon(){return rain.includes(w[i+1]+"")}
  function noUmbrellaInHome(){return home==0}
  function noUmbrellaInOffice(){return office==0}
  function buyAnUmbrellaAtHome(){home++}
  function buyAnUmbrellaAtOffice(){office++}
  function takeUmbrellaToOffice(){home--;office++}
  function takeUmbrellaToHome(){home++;office--}
}

幾個測試用例

有幾個測試用例,看到這道題目的同學自己試一下吧 minUmbrellas(["sunny", "windy", "sunny", "clear"]) // should return 0 // Because it doesn't rain at all

minUmbrellas(["rainy", "rainy", "rainy", "rainy", "thunderstorms", "rainy"]) // should return 1