Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Pyramid BankAccounts


Here is my solution:

using System;

public class BankAccount {

   private string owner;
   private decimal balance;
   private BankAccount leftAccount, rightAccount;

   public BankAccount(string owner, decimal balance) {
      this.owner = owner; 
      this.balance = balance;
      this.leftAccount = null;
      this.rightAccount = null;
   }

   public BankAccount(string owner, decimal balance, BankAccount leftAccount, BankAccount rightAccount) {
      this.owner = owner; 
      this.balance = balance;
      this.leftAccount = leftAccount;
      this.rightAccount = rightAccount;
   }

   private bool LeafAccount(){
      return leftAccount == null && rightAccount == null;
  }

   public decimal Balance () {
      if (this.LeafAccount())
         return balance;
      else 
         return balance + leftAccount.Balance() + rightAccount.Balance();
   }

   public void Withdraw (decimal amount) {
      if (this.LeafAccount())
        balance -= amount;
      else{
        this.leftAccount.Withdraw(amount/2);
        this.rightAccount.Withdraw(amount/2);
      }
   }

   public void Deposit (decimal amount) {
      if (this.LeafAccount())
         balance += amount;         
      else {
         balance += amount/3;
         leftAccount.Deposit(amount/3);
         rightAccount.Deposit(amount/3);
      }
   }

   public void DistributeEven(){
     int number = this.CountAccounts();
     decimal totalAmount = this.Balance();
     this.ForceBalance(totalAmount/number);
   }

   private int CountAccounts(){
      if (this.LeafAccount())
        return 1;
      else return 1 + 
           leftAccount.CountAccounts() + rightAccount.CountAccounts();
   }

   private void ForceBalance(decimal amount){
      balance = amount;
      if (!(this.LeafAccount())){
         leftAccount.ForceBalance(amount);
         rightAccount.ForceBalance(amount);
      }
   }

   public override string ToString() {
      return String.Format("{0} {1,12:c2} (local amount: {2,12:c2})", owner, Balance(), balance);
  }
}