HR - Bill Division

Goody·2021년 2월 5일
0

알고리즘

목록 보기
31/122

문제

Two friends Anna and Brian, are deciding how to split the bill at a dinner. Each will only pay for the items they consume. Brian gets the check and calculates Anna's portion. You must determine if his calculation is correct.

For example, assume the bill has the following prices:bill = [2,4,6] . Anna declines to eat item k = bill[2] which costs 6 . If Brian calculates the bill correctly, Anna will pay (2+4)/2 = 3 . If he includes the cost of bill[2] , he will calculate (2+4+6)/2 = 6 . In the second case, he should refund 3 to Anna.

function bonAppetit has the following parameter(s):

  • bill: an array of integers representing the cost of each item ordered
  • k: an integer representing the zero-based index of the item Anna doesn't eat
  • b: the amount of money that Anna contributed to the bill

예시

INPUT_0

4 1
3 10 2 9
12

OUTPUT_0

5

INPUT_1

4 1
3 10 2 9
7

OUTPUT_1

Bon Appetit

풀이

  • 하나의 배열을 가지고 각기 다른 합을 도출해내는 문제이다.
  • 브라이언은 주어진 배열 내 원소들을 reduce 로 모두 합한다.
  • 안나는 주어진 배열에서 k 번째 원소만 빼고 reduce 로 모두 합한다.

코드

    let initBill = bill; 
    const brianPay = initBill.reduce((acc,cur) => acc += cur) / 2; 
    initBill.splice(k,1);
    const annaPay = initBill.reduce((acc, cur) => acc += cur) / 2;

    if(annaPay === b) {
        console.log("Bon Appetit");
    } else {
        console.log(brianPay - annaPay);
    }

2개의 댓글

comment-user-thumbnail
2021년 2월 6일

와 구디!! 미션도 바빴을텐데 알고리즘까지 부지런히 하고 있네용 세상에 👍🤭

1개의 답글