Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function ballots(input) {
- let galaxy = new Map();
- let winners = new Map();
- let winnerTotalVotes = new Map();
- let totalVotes = 0;
- let systems = input.map(system => system.system);
- let votes = input.map(votes => votes.votes);
- for (let system = 0; system < systems.length; system++) {
- let candidate = input.map(candidate => candidate.candidate);
- if (!galaxy.has(systems[system])) {
- galaxy.set(systems[system], new Map());
- }
- if (!galaxy.get(systems[system]).has(candidate[system])) {
- galaxy.get(systems[system]).set(candidate[system], 0);
- }
- galaxy.get(systems[system])
- .set(candidate[system], galaxy.get(systems[system])
- .get(candidate[system]) + votes[system]);
- totalVotes += votes[system];
- }
- //sort candidates of each system by their votes in descending order
- for (let [system, candidates] of galaxy) {
- galaxy.set(system, new Map([...candidates].sort((a,b) => b[1] - a[1])));
- }
- //sum the votes of repeating candidates in repeating systems and put them into new Map
- for (let [system, candidates] of galaxy) {
- let winner = [...candidates.keys()][0];
- if (!winners.has(winner)) {
- winners.set(winner, new Map());
- }
- winners.get(winner).set(system, [...candidates.values()].reduce((a,b) => a + b));
- }
- //sort the winners in each system by votes in descending order
- for (let [winner, systems] of winners) {
- winners.set(winner, new Map([...systems].sort((a,b) => b[1] - a[1])));
- }
- //assign the total votes from system elections to the winner of the system
- for (let [winner, systems] of winners) {
- winnerTotalVotes.set(winner, [...systems.values()].reduce((a,b) => a + b));
- }
- //get winners from each system by total votes in descending order
- winnerTotalVotes = new Map([...winnerTotalVotes].sort((a,b) => b[1] - a[1]));
- let winnerName = [...winnerTotalVotes][0][0];
- let winnerVotes = [...winnerTotalVotes][0][1];
- let winnerPercentage = (winnerVotes / totalVotes) * 100;
- if ([...winnerTotalVotes].length === 1) {
- console.log(`${winnerName} wins with ${winnerVotes} votes`);
- console.log(`${winnerName} wins unopposed!`);
- return;
- }
- let runnerUpName = [...winnerTotalVotes][1][0];
- let runnerUpPercentage = ([...winnerTotalVotes][1][1] / totalVotes) * 100;
- if (winnerPercentage > 50) {
- console.log(`${winnerName} wins with ${winnerVotes} votes`);
- console.log(`Runner up: ${runnerUpName}`);
- for (let [system, votes] of winners.get(runnerUpName)) {
- console.log(`${system}: ${votes}`);
- }
- return;
- }
- console.log(`Runoff between ${winnerName} with ${Math.floor(winnerPercentage)}% and ${runnerUpName} with ${Math
- .floor(runnerUpPercentage)}%`);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement