Skip to content# Bill Division code challenge

### Problem

### Function Description

### Sample Input

### Sample Output

### Solution

## Newsletter

— 1 min read

My approach to solving HackerRank’s Bill Division code challenge.

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.

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

`14 123 10 2 9312`

`15`

We start by creating a total (`ttl`

) variable and counting the amount needed to pay using the `Array.reduce`

method.

Then we create a refund (`ref`

) variable equal to the amount of money Brian owes Anna. The idea is that we deduct the item which Anna didn't eat (`bill[k]`

) from the total (`ttl`

) divided by `2`

, and then we deduct the result from the amount Anna paid (`b`

).

We print out the refund number if it's not equal to `0`

. If it is, we print `Bon Appetit`

.

```
1function bonAppetit(bill, k, b) {2 const ttl = bill.reduce((a, b) => a + b);3 const ref = b - (ttl - bill[k]) / 2;4
5 console.log(ref !== 0 ? ref : 'Bon Appetit');6}
```

Sign up to get updates when I write something new. No spam ever.

Subscribe to my Newsletter