Skip to content

Instantly share code, notes, and snippets.

@olafurw
Created December 21, 2022 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olafurw/1e76bbe98bb8ef306c3f1e12c2aba156 to your computer and use it in GitHub Desktop.
Save olafurw/1e76bbe98bb8ef306c3f1e12c2aba156 to your computer and use it in GitHub Desktop.
Find out what video has the most sponsored segments
use std::env;
use std::error::Error;
use std::ffi::OsString;
use std::fs::File;
use std::process;
use std::collections::{HashMap, HashSet};
use csv::StringRecord;
fn get_first_arg() -> Result<OsString, Box<dyn Error>> {
match env::args_os().nth(1) {
None => Err(From::from("expected 1 argument, but got none")),
Some(file_path) => Ok(file_path),
}
}
fn get_sponsor_average(record: &StringRecord) -> u64 {
let video_length = record[13].parse::<f64>().unwrap();
let start = record[1].parse::<f64>().unwrap();
let end = record[2].parse::<f64>().unwrap();
let average = ((start + end) / 2.0).round();
((average / video_length) * 100.0).round() as u64
}
fn get_videos() -> Result<HashMap<String, u32>, Box<dyn Error>> {
let file_path = get_first_arg()?;
let file = File::open(file_path)?;
let mut rdr = csv::Reader::from_reader(file);
let mut sponsor_count = HashMap::new();
let mut duplicate_check = HashSet::new();
for result in rdr.records() {
let record = result?;
let video_votes = record[3].parse::<i32>().unwrap();
if video_votes < 20 {
continue;
}
let category = record[10].to_string();
let action = record[11].to_string();
if category != "sponsor" || action != "skip" {
continue;
}
let video_id = record[0].to_string();
let sponsor_average = get_sponsor_average(&record);
let sponsor_key = format!("{}{}", video_id, sponsor_average);
if duplicate_check.contains(&sponsor_key) {
continue;
}
*sponsor_count.entry(video_id).or_insert(0) += 1;
duplicate_check.insert(sponsor_key);
}
Ok(sponsor_count)
}
fn main() {
let count_result = get_videos();
if let Err(err) = count_result {
println!("error running example: {}", err);
process::exit(1);
}
let sponsor_count = count_result.unwrap();
for count in &sponsor_count {
println!(
"{}, {}",
count.1, count.0
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment