totalCost.js (8kyu 98)
Codewars 알고리즘 풀이
Problem
- There’s a 3 for 2offer on mangoes.- 2 + 1 망고 할인이 있다. (3 for 2)
 
- For a given quantity and price(per mango), calculate the total cost of the mangoes.- 주어진 수량과 가격(개당)에 대한 망고의 총 비용을 계산한다.
 
Solution 01
function totalCost(quantity, price) {
  let qty = quantity - Math.floor(quantity / 3);
  return qty * price;
}
totalCost(2, 1);  // 2
totalCost(3, 1);  // 2 (1 mango for free)
totalCost(4, 1);  // 3
totalCost(5, 1);  // 4
totalCost(6, 1);  // 4 (2 mangoes for free)
Math.floor()메소드가장 가까운 정수로 반내림하고, 결과를 반환한다.
Solution 02
function totalCost(quantity, price) {
  let divider = Math.floor(quantity / 3);
  let remainder = quantity % 3;
  
  return divider * 2 * price + remainder * price;
}
totalCost(2, 1);  // 2
totalCost(3, 1);  // 2 (1 mango for free)
totalCost(4, 1);  // 3
totalCost(5, 1);  // 4
totalCost(6, 1);  // 4 (2 mangoes for free)