read from file and fix bug which selected same winner again
This commit is contained in:
@@ -1 +1,2 @@
|
||||
/target
|
||||
*.txt
|
||||
|
||||
+41
-11
@@ -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<String> = 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<Vec<usize>> = lines
|
||||
.map(|m| {
|
||||
m.split(VALUE_SEPARATOR)
|
||||
.map(|v| {
|
||||
if v.parse::<usize>().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<usize>],
|
||||
candidate_count: usize,
|
||||
amount_of_winners: usize,
|
||||
) -> Vec<usize> {
|
||||
@@ -31,6 +59,8 @@ fn select_winners(
|
||||
let mut winners: Vec<usize> = 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), usize) {
|
||||
let (mut a_votes, mut b_votes): (usize, usize) = (0, 0);
|
||||
for vote in votes {
|
||||
|
||||
Reference in New Issue
Block a user