Created
June 13, 2023 05:24
-
-
Save cceasy/bbe1d89463602cb73af956e0b48fd2f6 to your computer and use it in GitHub Desktop.
Tmp Bank Transfer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class TmpMain { | |
List<One2OneTransfer> makeTransfer(List<AccountBalance> accounts, int baseAmount) { | |
if (accounts == null || accounts.isEmpty()) { | |
return Collections.emptyList(); // TODO we treat this case as doing nothing | |
} | |
int sum = accounts.stream().mapToInt(a -> a.balance).sum(); // TODO we assume amount sum would not exceed MAX INT | |
if (sum / accounts.size() < baseAmount) { | |
return null; // null means unable to do such a transfer | |
} | |
List<One2OneTransfer> transfers = new ArrayList<>(); | |
int high = 0, low = 0; | |
while (true) { | |
while (high < accounts.size() && accounts.get(high).balance <= baseAmount) ++high; | |
while (low < accounts.size() && accounts.get(low).balance >= baseAmount) ++low; | |
if (low < accounts.size() && high < accounts.size()) { | |
int highExt = accounts.get(high).balance - baseAmount; | |
int lowExt = baseAmount - accounts.get(low).balance; | |
int amount = Math.min(highExt, lowExt); | |
accounts.get(high).balance -= amount; | |
accounts.get(low).balance += amount; | |
transfers.add(new One2OneTransfer(accounts.get(high).id, accounts.get(low).id, amount)); | |
if (highExt == lowExt) { | |
++high; | |
++low; | |
} else if (highExt < lowExt) { | |
++high; | |
} else { | |
++low; | |
} | |
} else { | |
break; | |
} | |
} | |
return transfers; | |
} | |
public static void main(String[] args) { | |
TmpMain m = new TmpMain(); | |
List<AccountBalance> accounts = List.of( | |
new AccountBalance("a1", 110), | |
new AccountBalance("a2", 110), | |
new AccountBalance("a3", 90), | |
new AccountBalance("a4", 100), | |
new AccountBalance("a5", 130), | |
new AccountBalance("a6", 70) | |
); | |
System.out.println(accounts); | |
System.out.println(m.makeTransfer(accounts, 100)); | |
} | |
} | |
class AccountBalance { | |
String id; | |
int balance; | |
public AccountBalance(String id, int balance) { | |
this.id = id; | |
this.balance = balance; | |
} | |
@Override | |
public String toString() { | |
return id + ": " + balance; | |
} | |
} | |
/** | |
* transfer from -> to with amount money | |
* amount must be positive integer | |
*/ | |
class One2OneTransfer { | |
String from; | |
String to; | |
int amount; | |
public One2OneTransfer(String from, String to, int amount) { | |
this.from = from; | |
this.to = to; | |
this.amount = amount; | |
} | |
@Override | |
public String toString() { | |
return from + " -> " + to + " : " + amount; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment