Skip to main content
Code Review

Return to Revisions

9 of 9
Commonmark migration

Expense Sharing Calculation

The following is my solution to the problem presented on this CodeReview post:

Friends A, B, C, D go for a trip. They spend on various expenses. Cost of the expense is shared.

Example :

  • A spends 100 for breakfast for A, B, C and D
  • D spends 500 for cab for B and C
  • B spends 300 for lunch for A, B and C

Write a program to calculate how much each should get or each should give to one another. App should be scalable that number of friends can change


Design:

We need two data sets, which each respectively:

  • record transactions
  • tally amount due to each person

Simply strip off the info we need from the transactions and record either how much each person is owed, or how much each person should give.

Any input is welcome!

using System;
using System.Collections.Generic;
namespace CodeReview
{
 class Transaction
 {
 class Account
 {
 private int totalDebt = 0;
 private Dictionary<char, int> debtors = new Dictionary<char, int>();
 public Account(char initialDebtor, int initialDebt)
 {
 debtors.Add(initialDebtor, initialDebt);
 }
 public Dictionary<char, int> Debtors
 {
 get
 {
 return debtors;
 }
 }
 public int TotalDebt
 {
 get
 {
 foreach (char debtor in debtors.Keys)
 {
 totalDebt += debtors[debtor];
 }
 return totalDebt;
 }
 }
 }
 static void Main(string[] args)
 {
 Queue<Tuple<char, int, List<char>>> transactions = new Queue<Tuple<char, int, List<char>>>();
 Dictionary<char, Account> ledger = new Dictionary<char, Account>();
 transactions.Enqueue(Tuple.Create('A', 100, new List<char>() { 'A', 'B', 'C', 'D' }));
 transactions.Enqueue(Tuple.Create('D', 500, new List<char>() { 'B', 'C' }));
 transactions.Enqueue(Tuple.Create('B', 300, new List<char>() { 'A', 'B', 'C' }));
 while (transactions.Count > 0)
 {
 Tuple<char, int, List<char>> transaction = transactions.Dequeue();
 foreach (char beneficiary in transaction.Item3)
 {
 if (!beneficiary.Equals(transaction.Item1))
 {
 if (ledger.ContainsKey(beneficiary))
 {
 Dictionary<char, int> debtors = ledger[beneficiary].Debtors;
 if (debtors.ContainsKey(transaction.Item1))
 {
 debtors[transaction.Item1] += transaction.Item2;
 }
 else
 {
 debtors.Add(transaction.Item1, transaction.Item2);
 }
 }
 else
 {
 ledger.Add(beneficiary, new Account(transaction.Item1, transaction.Item2));
 }
 }
 }
 }
 foreach (char beneficiary in ledger.Keys)
 {
 Account account = ledger[beneficiary];
 Console.WriteLine("User " + beneficiary + " owes $" + account.TotalDebt + ":");
 foreach (char debtor in account.Debtors.Keys)
 {
 int debt = account.Debtors[debtor];
 Console.WriteLine(" - $" + debt + " to " + debtor);
 }
 }
 Console.ReadKey();
 }
 }
}
T145
  • 3.1k
  • 2
  • 23
  • 44
lang-cs

AltStyle によって変換されたページ (->オリジナル) /