Skip to content

Instantly share code, notes, and snippets.

@cuckookernel
Last active June 18, 2026 14:58
Show Gist options
  • Select an option

  • Save cuckookernel/c35d7ae964cf422eac1558fe49685045 to your computer and use it in GitHub Desktop.

Select an option

Save cuckookernel/c35d7ae964cf422eac1558fe49685045 to your computer and use it in GitHub Desktop.
Hackerrank helpers for Rust
use std::env;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Write};
use std::error::Error;
mod hrh {
use std::error::Error;
use std::io::BufRead;
use std::str::FromStr;
pub fn read_line_as<T: FromStr>(reader: &mut dyn BufRead) -> Result<T, Box<dyn Error>>
where
<T as FromStr>::Err: Error + 'static,
{
let mut t_temp = String::new();
reader.read_line(&mut t_temp).unwrap();
let value = t_temp.trim().parse::<T>()?;
Ok(value)
}
pub fn read_line_as_vec<T: FromStr>(reader: &mut dyn BufRead) -> Result<Vec<T>, Box<dyn Error>>
where
<T as FromStr>::Err: Error + 'static,
{
let mut t_temp = String::new();
reader.read_line(&mut t_temp)?;
let value: Result<Vec<T>, <T as FromStr>::Err> = t_temp
.split_whitespace()
.map(|s| s.trim().parse::<T>())
.collect();
Ok(value?)
}
}
#[allow(dead_code)]
fn example_read_to_stdin_write_to_output_path() -> Result<(), Box<dyn std::error::Error>> {
let output_path = env::var("OUTPUT_PATH").unwrap_or("data/out.txt".into());
let mut fout = BufWriter::new(File::create(output_path).expect("Failed to create output file"));
let stdin = io::stdin();
let mut reader = BufReader::new(stdin.lock());
let n: usize = hrh::read_line_as(&mut reader)?;
for line_num in 0..n {
let s: String = hrh::read_line_as(&mut reader)?;
let i: i32 = hrh::read_line_as(&mut reader)?;
let vi: Vec<i32> = hrh::read_line_as_vec(&mut reader)?;
let vf: Vec<f32> = hrh::read_line_as_vec(&mut reader)?;
writeln!(fout, "{} {} {} - {:?} - {:?}", line_num, s, i, vi, vf)?;
}
fout.flush()?;
Ok(())
}
fn example_read_to_stdin_write_to_stdout() -> Result<(), Box<dyn std::error::Error>> {
// read to stdin an
let stdout = io::stdout();
let mut fout = BufWriter::new(stdout.lock());
let stdin = io::stdin();
let mut reader = BufReader::new(stdin.lock());
let n: usize = hrh::read_line_as(&mut reader)?;
for line_num in 0..n {
let s: String = hrh::read_line_as(&mut reader)?;
let i: i32 = hrh::read_line_as(&mut reader)?;
let vi: Vec<i32> = hrh::read_line_as_vec(&mut reader)?;
let vf: Vec<f32> = hrh::read_line_as_vec(&mut reader)?;
writeln!(fout, "{} {} {} - {:?} - {:?}", line_num, s, i, vi, vf)?;
}
fout.flush()?;
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// example_read_to_stdin_write_to_output_path();
example_read_to_stdin_write_to_stdout()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment