DEV Community

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

Posted on

4 2

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →