diff options
author | Aria <me@aria.rip> | 2023-01-02 21:58:56 +0000 |
---|---|---|
committer | Aria <me@aria.rip> | 2023-01-02 21:58:56 +0000 |
commit | 5eb58ad076f2cd435b11b140820da224b60b73d5 (patch) | |
tree | 2a67939595fbf993ff04f69b9cd3f0aa20827d96 /2022/src/utils.rs |
initial commit
Diffstat (limited to '2022/src/utils.rs')
-rw-r--r-- | 2022/src/utils.rs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/2022/src/utils.rs b/2022/src/utils.rs new file mode 100644 index 0000000..8230c69 --- /dev/null +++ b/2022/src/utils.rs @@ -0,0 +1,59 @@ +#![allow(unused)] +use std::{fs::File, io::Read, str::FromStr}; + +pub fn read_input() -> String { + let mut args = std::env::args(); + + let mut file = File::open( + args.nth(1) + .expect("first argument should be input filename"), + ) + .expect("could not open input"); + let mut out = String::new(); + file.read_to_string(&mut out) + .expect("could not read input file"); + + out +} + +pub fn max_n<T: Ord>(vec: &mut Vec<T>, n: usize) -> &[T] { + top_n_by(vec, |a, b| a > b, n) +} + +pub fn top_n_by<T, F: FnMut(&T, &T) -> bool>(vec: &mut Vec<T>, mut f: F, n: usize) -> &[T] { + for _ in 0..n { + for i in 0..vec.len() - 1 { + if f(&vec[i], &vec[i + 1]) { + vec.swap(i, i + 1); + } + } + } + + &vec[vec.len() - n..] +} + +pub fn iter_pair<T>(mut i: impl Iterator<Item = T>) -> (T, T) { + (i.next().unwrap(), i.next().unwrap()) +} + +pub fn iter_triple<T>(mut i: impl Iterator<Item = T>) -> (T, T, T) { + (i.next().unwrap(), i.next().unwrap(), i.next().unwrap()) +} + +#[inline(always)] +pub fn parse_num<T: FromStr>(string: &str) -> (T, &str) +where + <T as FromStr>::Err: std::fmt::Debug, +{ + let count = string + .chars() + .take_while(|x| x.is_numeric() || *x == '-') + .count(); + + (string[..count].parse().unwrap(), &string[count..]) +} + +#[inline(always)] +pub fn parse_static<'a>(exp: &'static str, source: &'a str) -> &'a str { + &source[exp.len()..] +} |