{ }codelper
classesmethodsP0078

Bank account objects

Write an account class.
An account object has a name, a balance and a refusal count as fields, and its balance changes only through deposit, withdraw and transfer methods.
The first line gives the number of accounts n, the next n lines give "name starting_balance", the next line gives the number of commands q, and the next q lines give one command each.
There are three commands: "deposit name x" puts x into that account.
"withdraw name x" takes x out of that account.
"transfer from_name to_name x" takes x out of the sending account and puts it into the receiving account.
If the amount x is greater than the balance, that withdrawal or transfer is refused: no balance changes, and only the refusal count of the account money was to come out of (the sender, for a transfer) goes up by 1.
If x equals the balance it is not refused (the balance becomes 0).
After processing all commands in order, print "name balance refusals" for each account, one per line, in the order the accounts appear in the input.

Input
1 ≤ n ≤ 1000, 1 ≤ q ≤ 5000.
Names are 1 to 10 lowercase English letters or digits and are distinct.
0 ≤ starting_balance ≤ 1,000,000,000, 1 ≤ x ≤ 1,000,000,000 (integers).
Every name in a command is an existing account, and the two names of a transfer differ
Output
n lines, each with name, balance and refusal count separated by one space (a balance can grow to about 5 trillion)
Example 1 · stdin
3
mina 100
jun 50
seo 0
5
withdraw mina 100
transfer jun seo 30
withdraw jun 21
deposit mina 7
transfer seo mina 31
stdout
mina 7 0
jun 20 1
seo 30 1
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 6 languages

This problem takes only the languages with classes: Python, JavaScript, TypeScript, Java, C# and C++ (C has no classes, and Craykon cannot define classes yet).
The first trap is the refusal boundary: an amount equal to the balance can be taken out, so refuse only when amount > balance; writing >= is wrong.
The second is the balance size: putting in 1 billion 5000 times into one account gives about 5 trillion, so Java int, C# int and C++ int (up to about 2.1 billion) silently overflow.
Use long in Java and C# and long long in C++; Python int has no limit and JS/TS number is exact up to 2^53, so they are fine.
The third is whether taking an object out makes a copy.
Python, JS, TS and Java objects and C# class instances are handled by reference, so changing an account you got from a map changes the original.
But in C++ Account acc = accounts[i]; copies the whole object, so take it as a reference Account& acc; and in C#, making it a struct instead of a class gives a value type, so every lookup hands back a copy and the deposit disappears.
Having transfer call deposit only when withdraw succeeds keeps the refusal rule in one place.

Pythonmain.py · 47 lines
import sys  class Account:    def __init__(self, name, balance):        self.name = name        self.balance = balance        self.refused = 0     def deposit(self, amount):        self.balance += amount     def withdraw(self, amount):        """잔액이 모자라면 거절하고 False를 돌려준다."""        if amount > self.balance:            self.refused += 1            return False        self.balance -= amount        return True     def transfer(self, other, amount):        if self.withdraw(amount):            other.deposit(amount)  lines = sys.stdin.read().split("\n")n = int(lines[0])accounts = []by_name = {}for line in lines[1:n + 1]:    name, balance = line.split()    acc = Account(name, int(balance))    accounts.append(acc)    by_name[name] = acc q = int(lines[n + 1])for line in lines[n + 2:n + 2 + q]:    p = line.split()    if p[0] == "deposit":        by_name[p[1]].deposit(int(p[2]))    elif p[0] == "withdraw":        by_name[p[1]].withdraw(int(p[2]))    else:        by_name[p[1]].transfer(by_name[p[2]], int(p[3])) for acc in accounts:    print(acc.name, acc.balance, acc.refused)
JavaScriptmain.js · 46 lines
class Account {  constructor(name, balance) {    this.name = name;    this.balance = balance;    this.refused = 0;  }   deposit(amount) {    this.balance += amount;  }   // 잔액이 모자라면 거절하고 false를 돌려준다  withdraw(amount) {    if (amount > this.balance) {      this.refused++;      return false;    }    this.balance -= amount;    return true;  }   transfer(other, amount) {    if (this.withdraw(amount)) other.deposit(amount);  }} const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const accounts = [];const byName = new Map();for (let i = 1; i <= n; i++) {  const [name, balance] = lines[i].trim().split(" ");  const acc = new Account(name, Number(balance));  accounts.push(acc);  byName.set(name, acc);} const q = Number(lines[n + 1]);for (let i = n + 2; i < n + 2 + q; i++) {  const p = lines[i].trim().split(" ");  if (p[0] === "deposit") byName.get(p[1]).deposit(Number(p[2]));  else if (p[0] === "withdraw") byName.get(p[1]).withdraw(Number(p[2]));  else byName.get(p[1]).transfer(byName.get(p[2]), Number(p[3]));} console.log(accounts.map((a) => `${a.name} ${a.balance} ${a.refused}`).join("\n"));
TypeScriptmain.ts · 56 lines
import { readFileSync } from "node:fs"; class Account {  readonly name: string;  private balance: number;  private refused = 0;   constructor(name: string, balance: number) {    this.name = name;    this.balance = balance;  }   deposit(amount: number): void {    this.balance += amount;  }   // 잔액이 모자라면 거절하고 false를 돌려준다  withdraw(amount: number): boolean {    if (amount > this.balance) {      this.refused++;      return false;    }    this.balance -= amount;    return true;  }   transfer(other: Account, amount: number): void {    if (this.withdraw(amount)) other.deposit(amount);  }   describe(): string {    return `${this.name} ${this.balance} ${this.refused}`;  }} const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const accounts: Account[] = [];const byName = new Map<string, Account>();for (let i = 1; i <= n; i++) {  const [name, balance] = lines[i].trim().split(" ");  const acc = new Account(name, Number(balance));  accounts.push(acc);  byName.set(name, acc);} const q: number = Number(lines[n + 1]);for (let i = n + 2; i < n + 2 + q; i++) {  const p: string[] = lines[i].trim().split(" ");  const acc = byName.get(p[1])!;  if (p[0] === "deposit") acc.deposit(Number(p[2]));  else if (p[0] === "withdraw") acc.withdraw(Number(p[2]));  else acc.transfer(byName.get(p[2])!, Number(p[3]));} console.log(accounts.map((a) => a.describe()).join("\n"));
JavaMain.java · 66 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; class Account {    private final String name;    private long balance; // 5000번 넣으면 int(약 21억)를 넘는다    private int refused = 0;     Account(String name, long balance) {        this.name = name;        this.balance = balance;    }     void deposit(long amount) { balance += amount; }     /** 잔액이 모자라면 거절하고 false를 돌려준다. */    boolean withdraw(long amount) {        if (amount > balance) {            refused++;            return false;        }        balance -= amount;        return true;    }     void transfer(Account other, long amount) {        if (withdraw(amount)) other.deposit(amount);    }     String describe() { return name + " " + balance + " " + refused; }} public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        List<Account> accounts = new ArrayList<>();        Map<String, Account> byName = new HashMap<>();        for (int i = 0; i < n; i++) {            String[] p = in.readLine().trim().split(" ");            Account acc = new Account(p[0], Long.parseLong(p[1]));            accounts.add(acc);            byName.put(p[0], acc);        }         int q = Integer.parseInt(in.readLine().trim());        for (int i = 0; i < q; i++) {            String[] p = in.readLine().trim().split(" ");            Account acc = byName.get(p[1]);            switch (p[0]) {                case "deposit" -> acc.deposit(Long.parseLong(p[2]));                case "withdraw" -> acc.withdraw(Long.parseLong(p[2]));                default -> acc.transfer(byName.get(p[2]), Long.parseLong(p[3]));            }        }         StringBuilder out = new StringBuilder();        for (Account acc : accounts) out.append(acc.describe()).append('\n');        System.out.print(out);    }}
C#Main.cs · 69 lines
using System;using System.Collections.Generic;using System.Text; class Account{    public string Name { get; }    public long Balance { get; private set; } // 5000번 넣으면 int(약 21억)를 넘는다    public int Refused { get; private set; }     public Account(string name, long balance)    {        Name = name;        Balance = balance;    }     public void Deposit(long amount) => Balance += amount;     // 잔액이 모자라면 거절하고 false를 돌려준다    public bool Withdraw(long amount)    {        if (amount > Balance)        {            Refused++;            return false;        }        Balance -= amount;        return true;    }     public void Transfer(Account other, long amount)    {        if (Withdraw(amount)) other.Deposit(amount);    }} class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        var accounts = new List<Account>();        var byName = new Dictionary<string, Account>();        for (int i = 0; i < n; i++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            var acc = new Account(p[0], long.Parse(p[1]));            accounts.Add(acc);            byName[p[0]] = acc;        }         int q = int.Parse(Console.ReadLine());        for (int i = 0; i < q; i++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            Account acc = byName[p[1]];            switch (p[0])            {                case "deposit": acc.Deposit(long.Parse(p[2])); break;                case "withdraw": acc.Withdraw(long.Parse(p[2])); break;                default: acc.Transfer(byName[p[2]], long.Parse(p[3])); break;            }        }         var sb = new StringBuilder();        foreach (var acc in accounts) sb.Append($"{acc.Name} {acc.Balance} {acc.Refused}\n");        Console.Write(sb);    }}
C++main.cpp · 68 lines
#include <iostream>#include <string>#include <unordered_map>#include <utility>#include <vector> class Account {public:    Account(std::string name, long long balance) : name_(std::move(name)), balance_(balance) {}     void deposit(long long amount) { balance_ += amount; }     // 잔액이 모자라면 거절하고 false를 돌려준다    bool withdraw(long long amount) {        if (amount > balance_) {            refused_++;            return false;        }        balance_ -= amount;        return true;    }     void transfer(Account& other, long long amount) {        if (withdraw(amount)) other.deposit(amount);    }     void print() const { std::cout << name_ << ' ' << balance_ << ' ' << refused_ << '\n'; } private:    std::string name_;    long long balance_; // 5000번 넣으면 int(약 21억)를 넘는다    int refused_ = 0;}; int main() {    std::ios::sync_with_stdio(false);    int n;    std::cin >> n;    std::vector<Account> accounts;    std::unordered_map<std::string, int> index; // 이름 → 자리(벡터가 자라도 바뀌지 않는다)    for (int i = 0; i < n; i++) {        std::string name;        long long balance;        std::cin >> name >> balance;        accounts.emplace_back(name, balance);        index[name] = i;    }     int q;    std::cin >> q;    for (int i = 0; i < q; i++) {        std::string cmd, a;        long long x;        std::cin >> cmd >> a;        Account& acc = accounts[index[a]]; // &를 빼면 복사본이 바뀐다        if (cmd == "transfer") {            std::string b;            std::cin >> b >> x;            acc.transfer(accounts[index[b]], x);        } else {            std::cin >> x;            if (cmd == "deposit") acc.deposit(x);            else acc.withdraw(x);        }    }     for (const Account& acc : accounts) acc.print();}