From eaa1e5250925629c7f858365877c8c3c16bb1cb0 Mon Sep 17 00:00:00 2001 From: Vegard Bieker Matthey Date: Thu, 7 May 2026 16:57:39 +0200 Subject: [PATCH] read from file and fix bug which selected same winner again --- .gitignore | 1 + src/main.rs | 52 +++++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index ea8c4bf..eed3cc5 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +*.txt diff --git a/src/main.rs b/src/main.rs index ef7f84b..35dd63a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,19 +1,47 @@ use combinatorial::Combinations; +const VOTE_SEPARATOR: &str = "- Vote Separator -\n"; +const ANIME_SEPARATOR: &str = " | "; +const VALUE_SEPARATOR: &str = ","; + fn main() { - let anime = [ - "Hunter x Hunter", - "Steins;Gate", - "Fullmetal Alchemist: Brotherhood", - "Monster", - "Attack on Titan", - ]; - let votes: Vec<&[usize]> = vec![&[0, 1, 2, 3, 4], &[1, 0, 2, 4, 3], &[1, 0, 2, 3, 4]]; - println!("winners: {:?}", select_winners(&votes, anime.len(), 2)); + let args: Vec = std::env::args().skip(1).collect(); + if args.len() != 1 { + eprintln!("ERROR: Expected one argument: filepath"); + std::process::exit(1); + } + + let data = std::fs::read_to_string(&args[0]).unwrap(); + for vote_data in data.split(VOTE_SEPARATOR) { + let mut lines = vote_data.lines(); + let animes: Vec<&str> = lines + .next() + .expect("Expected list of animes") + .split(ANIME_SEPARATOR) + .collect(); + println!("animes: {animes:?}"); + let votes: Vec> = lines + .map(|m| { + m.split(VALUE_SEPARATOR) + .map(|v| { + if v.parse::().is_err() { + println!("Failed to parse value: \"{v}\""); + std::process::exit(1); + } + v.parse().expect("Expected integer value") + }) + .collect() + }) + .collect(); + println!( + "winners: {:?}", + select_winners(&votes, animes.len(), animes.len()) + ); + } } fn select_winners( - votes: &[&[usize]], + votes: &[Vec], candidate_count: usize, amount_of_winners: usize, ) -> Vec { @@ -31,6 +59,8 @@ fn select_winners( let mut winners: Vec = Vec::new(); for _ in 0..amount_of_winners { let winner = (0..candidate_count) + // Find new winners each time. + .filter(|c| !winners.contains(&c)) .map(|c| { ( c, @@ -54,7 +84,7 @@ fn select_winners( fn single_election( (candidate_a, candidate_b): (usize, usize), - votes: &[&[usize]], + votes: &[Vec], ) -> ((usize, usize), usize) { let (mut a_votes, mut b_votes): (usize, usize) = (0, 0); for vote in votes {