
Inhalt
Die Fakten:
Plattform: | codewars.com |
Name: | Wealth equality, finally! |
Level: | 7 kyu |
Sprache: | TypeScript |
Beschreibung:
The year is 2088 and the Radical Marxist Socialist People's Party (RMSPP) has just seized power in Brazil.
Their first act in power is absolute wealth equality through coercive redistribution.
Create a function that redistributes all wealth equally among all citizens.
Wealth is represented as an array/list where every index is the wealth of a single citizen.
The function should mutate the input such that every index has the same amount of wealth.
See example:
- Input:
[5, 10, 6] >>> This represents:
# citizen 1 has wealth 5
# citizen 2 has wealth 10
# citizen 3 has wealth 6
- Should be after the test:
[7, 7, 7] >>> wealth has now been equally redistributed
Info:
- MUTATE the input array/list, don't return anything
- Input is guaranteed to hold at least 1 citizen
- Wealth of a citizen will be an integer with minimum equal to 0 (negative wealth is not possible)
- Handling of floating point error will not be tested
Quelle: codewars.com
Lösung
Pseudo-Code
Wie immer gibt's reichlich Varianten, hier ist eine meiner.
Erst die Lösungsschritte in Pseudo-Code. Los geht’s:
Lösungsschritte
Schritt 1
Als Erstes brauchen wir die Anzahl der Bürger.
Schritt 2
Dann müssen wir berechnen, was jeder Bürger bekommt.
Schritt 3
Am Schluss noch das wealth
-Array ändern, ohne etwas zu returnen.
Code
Geil. Übersetzen wir unseren Pseudo-Code in TypeScript:
Lösungsschritte
Meine erste Zeile:
export function redistributeWealth(wealth: number[]): void {
Die Anzahl der Bürger berechnen:
const numCitizens = wealth.length;
Die Anzahl der Bürger ist einfach die Anzahl der Elemente im Array.
Den Betrag berechnen, der jedem Bürger zusteht:
const equalWealth = wealth.reduce((sum, num) => sum + num, 0) / numCitizens;
Dafür berechnen wir erstmal die Summe aller Vermögen im Input-Array, z.B. mit .reduce()
. Diese Summe Teilen wir dann durch die Anzahl der Bürger und erhalten so den Durchschnitt. Also das, was jedem Bürger im Sozialismus zusteht.
Und zum Schluss noch das Input-Array ändern:
wealth.fill(equalWealth);
Das geht zum Beispiel mit .fill()
. Damit wird jedes Element im Array überschrieben. Returnt wird nüscht!
Voilá! 💪
Komplettlösung
export function redistributeWealth(wealth: number[]): void {
const numCitizens = wealth.length;
const equalWealth = wealth.reduce((sum, num) => sum + num, 0) / numCitizens;
wealth.fill(equalWealth);
}