DEV Community

Cover image for Bill Division (HackerRank Javascript Solution)
Ibukun Demehin
Ibukun Demehin

Posted on

Bill Division (HackerRank Javascript Solution)

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 Description

Complete the bonAppetit function in the editor below. It should print Bon Appetit if the bill is fairly split. Otherwise, it should print the integer amount of money that Brian owes Anna.

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

Solution

function bonAppetit(bill, k, b) {
    // Write your code here
    let result = ''
    bill.splice(k,1)
    const billCost = bill.reduce((previous, next) => previous+next, 0) / 2
    if (billCost == b){
        result = 'Bon Appetit'
    } else {
        result = b - billCost
    }
    console.log(result)

} 
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
aylarose profile image
Ayla Rose

The provided solution for the "Bill Division" problem effectively calculates whether Anna's share of the dinner bill is correct, taking into account the item she declined. If Brian's calculation aligns with the actual cost, it prints "Bon Appetit"; otherwise, it shows how much he owes her. For those managing their expenses, exploring options like pesco online bill can help streamline bill payments and tracking.