Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.pharmeasy.demo;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
- import org.springframework.transaction.annotation.Transactional;
- public class DemoApplication {
- public static void main(String[] args) {
- Wallet walletAccount = new WalletAccount();
- String input = "1,100,200,200,1000,1";
- walletAccount.load(input);
- System.out.println("Balance :" + walletAccount.getBalance());
- System.out.println("Coins :" + walletAccount.peek());
- walletAccount.spend(30L);
- System.out.println("Balance :" + walletAccount.getBalance());
- System.out.println("Coins :" + walletAccount.peek());
- }
- }
- interface Wallet {
- /**
- * Load money into my wallet
- */
- void load(String coins);
- /**
- * Return current balance of my wallet
- */
- Long getBalance();
- /**
- * Return the coins in the wallet. (peek does NOT need to be performant as to be used solely for
- * testing)
- */
- Collection<Long> peek();
- /**
- * Spend an [amount] of money from Wallet and ensure the wallet is updated (any change should be
- * added back to the wallet as a single amount) Return single change amount (if any change due) or
- * zero.
- */
- Long spend(Long amount);
- }
- class WalletAccount implements Wallet {
- Long balance = 0L;
- List<Long> coins = new ArrayList<>();
- @Transactional
- public void addCoin(String coin) {
- Long coinDenomintaion = Long.valueOf(coin);
- this.coins.add(coinDenomintaion);
- this.addBalance(coinDenomintaion);
- }
- private void addBalance(Long coinDenomintaion) {
- this.balance = (this.getBalance() + coinDenomintaion);
- }
- @Override
- public void load(String input) {
- List<String> coins = List.of(input.split(","));
- for (String coin : coins) {
- this.addCoin(coin);
- }
- }
- @Override
- public Long getBalance() {
- return this.balance;
- }
- public List<Long> peek() {
- return this.coins;
- }
- @Override
- public Long spend(Long amount) {
- Long currentAmount = 0L;
- /*
- * 30
- * [1, 100, 200, 200, 1000, 1]
- * ^
- * 101 --> return 101 --> Give us back 71
- * coins = [200, 200, 1000, 1]
- * add 71;
- * [200, 200, 1000, 1, 71]
- * */
- int i = 0;
- for (i = 0; i < this.coins.size(); i++) {
- Long currentCoin = this.coins.get(i);
- currentAmount += currentCoin;
- if (currentAmount >= amount) {
- break;
- }
- }
- this.balance -= currentAmount;
- this.coins = this.coins.subList(i + 1, this.coins.size());
- Long change = (currentAmount - amount);
- if (change > 0) {
- this.coins.add(change);
- addBalance(change);
- }
- return change;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment