refactor projekt to implement and test other cli libs

This commit is contained in:
Leo Drachenfeuer 2022-12-13 05:02:02 +01:00
parent f091f19a55
commit 8b16296d5e
Signed by: dragonleo
GPG key ID: A8338FC081137CF0
34 changed files with 35 additions and 15 deletions

6
aoc/Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "aoc"
version = "2022.1.0"
edition = "2021"
[dependencies]

4
aoc/src/lib.rs Normal file
View file

@ -0,0 +1,4 @@
pub mod year2022;
pub mod util;
pub use year2022::*;

11
aoc/src/util.rs Normal file
View file

@ -0,0 +1,11 @@
use std::fs::File;
use std::io::{Result, BufRead, BufReader,Lines};
use std::path::Path;
pub fn read_lines<P>(filename: P) -> Result<Lines<BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(BufReader::new(file).lines())
}

View file

@ -0,0 +1,33 @@
use std::path::PathBuf;
use crate::util::read_lines;
pub fn subcmd_day001(file: &Option<PathBuf>, top: &i32, total: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
// Consumes the iterator, returns an (Optional) String
let mut nutri: i32 = 0;
let mut hist: Vec<i32> = Vec::new();
for line in lines {
if let Ok(num) = line {
if num.is_empty() {
hist.push(nutri);
nutri = 0;
} else {
nutri += num.parse::<i32>().unwrap();
}
}
}
hist.sort();
let hist_len = hist.len();
let mut top_total: i32 = 0;
for x in 0..*top{
let index: usize = hist_len - 1 - usize::try_from(x).unwrap();
top_total += hist[index];
println!("{:?}", hist[index]);
}
if *total{
println!("Total:");
println!("{:?}", top_total);
}
}
}

210
aoc/src/year2022/day002.rs Normal file
View file

@ -0,0 +1,210 @@
use std::path::PathBuf;
use crate::util::read_lines;
#[derive(Debug)]
enum Shape {
Rock,
Paper,
Scissor,
}
impl Shape {
fn get_value(&self) -> u32 {
match self {
Shape::Rock => 1,
Shape::Paper => 2,
Shape::Scissor => 3,
}
}
}
#[derive(Debug)]
enum EncrypedShape {
A,
B,
C,
X,
Y,
Z,
}
impl EncrypedShape {
fn from_str(s: &str) -> Self {
match Some(s) {
Some("A") => EncrypedShape::A,
Some("B") => EncrypedShape::B,
Some("C") => EncrypedShape::C,
Some("X") => EncrypedShape::X,
Some("Y") => EncrypedShape::Y,
Some("Z") => EncrypedShape::Z,
_ => panic!(),
}
}
fn get_shape(&self) -> Shape {
match self {
EncrypedShape::A | EncrypedShape::X => Shape::Rock,
EncrypedShape::B | EncrypedShape::Y => Shape::Paper,
EncrypedShape::C | EncrypedShape::Z => Shape::Scissor,
}
}
fn predict_result(&self) -> RpsResult {
match self {
EncrypedShape::X => RpsResult::Loss,
EncrypedShape::Y => RpsResult::Draw,
EncrypedShape::Z => RpsResult::Win,
EncrypedShape::A | EncrypedShape::B | EncrypedShape::C => panic!(),
}
}
fn get_value(&self) -> u32 {
self.get_shape().get_value()
}
}
#[derive(Debug)]
enum RpsResult {
Win,
Draw,
Loss,
}
#[derive(Debug)]
struct RPSPair {
op: EncrypedShape,
me: EncrypedShape,
}
impl RPSPair {
fn from_vec(v: Vec<&str>) -> Self {
RPSPair {
op: (EncrypedShape::from_str(v.first().unwrap())),
me: (EncrypedShape::from_str(v.last().unwrap())),
}
}
fn my_shape_by_predicted_result(&self) -> Shape {
match self.op.get_shape() {
Shape::Rock => match self.me.predict_result() {
RpsResult::Win => Shape::Paper,
RpsResult::Draw => Shape::Rock,
RpsResult::Loss => Shape::Scissor,
},
Shape::Paper => match self.me.predict_result() {
RpsResult::Win => Shape::Scissor,
RpsResult::Draw => Shape::Paper,
RpsResult::Loss => Shape::Rock,
},
Shape::Scissor => match self.me.predict_result() {
RpsResult::Win => Shape::Rock,
RpsResult::Draw => Shape::Scissor,
RpsResult::Loss => Shape::Paper,
},
}
}
fn get_points(&self, alt: &bool) -> u32 {
let extra_points: u32;
let r: RpsResult;
let mv: u32;
if *alt {
r = self.me.predict_result();
mv = self.my_shape_by_predicted_result().get_value();
} else {
r = self.get_result();
mv = self.me.get_value();
}
match r {
RpsResult::Win => {
extra_points = 6;
}
RpsResult::Draw => {
extra_points = 3;
}
RpsResult::Loss => {
extra_points = 0;
}
}
mv + extra_points
}
fn get_result(&self) -> RpsResult {
match self.me.get_shape() {
Shape::Rock => match self.op.get_shape() {
Shape::Rock => RpsResult::Draw,
Shape::Paper => RpsResult::Loss,
Shape::Scissor => RpsResult::Win,
},
Shape::Paper => match self.op.get_shape() {
Shape::Rock => RpsResult::Win,
Shape::Paper => RpsResult::Draw,
Shape::Scissor => RpsResult::Loss,
},
Shape::Scissor => match self.op.get_shape() {
Shape::Rock => RpsResult::Loss,
Shape::Paper => RpsResult::Win,
Shape::Scissor => RpsResult::Draw,
},
}
}
}
pub fn subcmd_day002(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
let mut my_score: u32 = 0;
for line in lines {
if let Ok(ln) = line {
let pair: RPSPair = RPSPair::from_vec(ln.split(" ").collect::<Vec<&str>>());
let my_points: u32 = pair.get_points(alt);
let my_value: u32;
let my_shape: Shape;
let my_result: RpsResult;
if *alt {
my_shape = pair.my_shape_by_predicted_result();
my_value = my_shape.get_value();
my_result = pair.me.predict_result();
} else {
my_shape = pair.me.get_shape();
my_value = pair.me.get_value();
my_result = pair.get_result();
}
my_score += my_points;
println!(
"op: {:?}({:?}), me: {:?}({:?}), result: {:?}, points: {:?}",
pair.op.get_shape(),
pair.op.get_value(),
my_shape,
my_value,
my_result,
my_points
);
}
}
println!("My Total Points: {:?}", my_score)
}
}
pub fn subcmd_day002_op(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
let mut my_score: u32 = 0;
for line in lines {
if let Ok(ln) = line {
let pair: RPSPair = RPSPair::from_vec(ln.split(" ").collect::<Vec<&str>>());
my_score += pair.get_points(alt);
}
}
println!("My Total Points: {:?}", my_score)
}
}
pub fn subcmd_day002_iter(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
let points:u32 = lines
.into_iter()
.map(|line| RPSPair::from_vec(line.unwrap().split(" ").collect::<Vec<&str>>()))
.map(|pair| pair.get_points(alt))
.sum();
println!("My Total Points: {:?}", points)
}
}

111
aoc/src/year2022/day003.rs Normal file
View file

@ -0,0 +1,111 @@
use std::path::PathBuf;
use crate::util::read_lines;
#[derive(Debug,Clone)]
struct Backpack {
complete: Vec<Item>,
compartment1: Vec<Item>,
compartment2: Vec<Item>,
equal_items: Vec<Item>,
}
impl Backpack {
fn from_str(s: &str) -> Self {
let vchar: Vec<char> = s.chars().collect();
let (p1, p2) = vchar.split_at(vchar.len() / 2);
let com1:Vec<Item> = p1.iter().map(|c| Item::from_char(*c)).collect();
let com2:Vec<Item> = p2.iter().map(|c| Item::from_char(*c)).collect();
let mut eqvec:Vec<Item> = Vec::new();
for c in com1.iter(){
if com2.contains(&c) {
eqvec.push(c.clone());
break;
}
}
Backpack {
complete: vchar.iter().map(|c| Item::from_char(*c)).collect(),
compartment1: (com1),
compartment2: (com2),
equal_items: (eqvec),
}
}
fn print(&self){
println!("compartment 1 ({:?})", self.compartment1.len());
for c in self.compartment1.iter() {
println!("{:?}", c);
}
println!("compartment 2 ({:?})", self.compartment2.len());
for c in self.compartment2.iter() {
println!("{:?}", c);
}
println!("found equals ({:?})", self.equal_items.len());
for c in self.equal_items.iter() {
println!("{:?}", c);
}
}
}
#[derive(Debug, Clone)]
struct Item {
itype: char,
prio: u8,
}
impl Item {
fn from_char(c: char) -> Self {
let value:u8;
if c.is_lowercase(){
value = c as u8 - 96;
}else{
value = c as u8 - 38;
}
Item { itype: (c), prio:(value) }
}
}
impl PartialEq for Item {
fn eq(&self, other: &Self) -> bool {
self.itype == other.itype
}
}
fn part1 (bpacks:&Vec<Backpack>){
let mut toatal_prio:u32 = 0;
for bp in bpacks.iter() {
for i in bp.equal_items.iter(){
toatal_prio += i.prio as u32;
}
}
println!("{:?}", bpacks.len()/3);
println!("{:?}", toatal_prio);
}
fn part2 (bpacks:&Vec<Backpack>){
let bpgroup = bpacks.chunks(3);
let mut mark_total: u32 = 0;
for bg in bpgroup {
let temp_vec:Vec<Backpack> = bg.to_vec();
let b1:&Backpack = temp_vec.get(0).unwrap();
let b2:&Backpack = temp_vec.get(1).unwrap();
let b3:&Backpack = temp_vec.get(2).unwrap();
for i in b1.complete.iter() {
if b2.complete.contains(&i) && b3.complete.contains(&i) {
mark_total += i.prio as u32;
break;
}
}
}
println!("{:?}", mark_total);
}
pub fn subcmd_day003(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
let bpacks: Vec<Backpack> = lines.map(|ln| Backpack::from_str(&ln.unwrap())).collect();
if *alt{
part2(&bpacks);
}else {
part1(&bpacks);
}
}
}

View file

@ -0,0 +1,55 @@
use crate::util::read_lines;
use std::fs::File;
use std::io::{BufReader, Lines};
use std::path::PathBuf;
fn part1(lines: Lines<BufReader<File>>) {
let mut full_containt: u32 = 0;
let mut overlapping: u32 = 0;
for line in lines {
let temp_line = line;
let mut team: Vec<u32> = Vec::new();
temp_line
.unwrap()
.split(",")
.collect::<Vec<&str>>()
.iter()
.for_each(|s| {
s.split("-")
.into_iter()
.for_each(|s| team.push(s.parse::<u32>().unwrap()))
});
let t1_start: &u32 = team.get(0).unwrap();
let t1_end: &u32 = team.get(1).unwrap();
let t2_start: &u32 = team.get(2).unwrap();
let t2_end: &u32 = team.get(3).unwrap();
if (t1_start >= t2_start && t1_end <= t2_end)
|| (t2_start >= t1_start && t2_end <= t1_end)
|| (t1_start == t2_end &&t2_start == t2_end)
|| (t1_end == t2_end && t2_start == t2_end)
{
println!(
"Gruppe full: {:?}-{:?}, {:?}-{:?}",
t1_start, t1_end, t2_start, t2_end
);
//println!("{:?}", team);
full_containt += 1;
} else if (t1_start < t2_end && t1_end < t2_end) || (t2_start >= t1_start) {
println!(
"Gruppe part: {:?}-{:?}, {:?}-{:?}",
t1_start, t1_end, t2_start, t2_end
);
overlapping += 1;
}
}
println!("full {:?}", full_containt);
println!("part {:?}", overlapping);
println!("total {:?}", full_containt + overlapping);
}
pub fn subcmd_day004(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
part1(lines);
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day005(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day006(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,99 @@
use crate::util::read_lines;
use std::cell::{Ref, RefCell};
use std::fs::File;
use std::io::{BufReader, Lines};
use std::path::PathBuf;
use std::rc::{Rc, Weak};
#[derive(Debug)]
enum FsNodeType {
File,
Directory,
}
#[derive(Debug)]
struct FsNode {
vname: String,
vsize: u64,
vtype: FsNodeType,
parent: RefCell<Weak<FsNode>>,
childs: RefCell<Vec<Rc<FsNode>>>,
}
impl FsNode {
fn new() -> Rc<FsNode> {
Rc::new(FsNode {
vname: String::new(),
vsize: (0),
vtype: (FsNodeType::File),
parent: RefCell::new(Weak::new()),
childs: (RefCell::new(Vec::new())),
})
}
fn new_file(fname: &str, size: u64) -> Rc<FsNode> {
Rc::new(FsNode {
vname: (fname.to_string()),
vsize: (size),
vtype: (FsNodeType::File),
parent: RefCell::new(Weak::new()),
childs: (RefCell::new(Vec::new())),
})
}
fn new_dir(fname: &str) -> Rc<FsNode> {
Rc::new(FsNode {
vname: (fname.to_string()),
vsize: (0),
vtype: (FsNodeType::Directory),
parent: RefCell::new(Weak::new()),
childs: (RefCell::new(Vec::new())),
})
}
fn set_parent(&self, new_parent: &Rc<FsNode>) {
*self.parent.borrow_mut() = Rc::downgrade(new_parent);
}
fn add_child_node(&self, cf: Rc<FsNode>) {
match self.vtype {
FsNodeType::File => {}
FsNodeType::Directory => self.childs.borrow_mut().push(cf),
}
}
fn get_size(&self) ->u64{
self.vsize
}
fn get_size_of_tree(&self) -> u64{
let mut csize:u64 = self.vsize;
for c in self.childs.borrow().iter(){
csize += c.get_size_of_tree();
}
csize
}
fn get_parent(&self) -> Option<Rc<FsNode>> {
self.parent.borrow().upgrade()
}
fn get_child(&self) -> Ref<Vec<Rc<FsNode>>> {
self.childs.borrow()
}
}
fn part1(lines: Lines<BufReader<File>>) {
let tnode1: Rc<FsNode> = FsNode::new_dir("test");
let tnode2: Rc<FsNode> = FsNode::new_file("test", 10);
tnode2.set_parent(&tnode1);
tnode1.add_child_node(tnode2);
tnode1.add_child_node(FsNode::new_file("tesd234", 55));
println!("{:?}", tnode1.get_size_of_tree())
}
pub fn subcmd_day007(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
part1(lines);
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day008(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day009(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day010(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day011(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day012(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day013(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day014(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day015(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day016(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day017(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day018(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day019(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day020(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day021(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day022(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day023(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day024(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

View file

@ -0,0 +1,14 @@
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader,Lines};
use crate::util::read_lines;
fn part1(lines: Lines<BufReader<File>>) {
}
pub fn subcmd_day025(file: &Option<PathBuf>, alt: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
}
}

35
aoc/src/year2022/mod.rs Normal file
View file

@ -0,0 +1,35 @@
mod day001;
mod day002;
mod day003;
mod day004;
mod day005;
mod day006;
mod day007;
mod day008;
mod day009;
//mod day010;
//mod day011;
//mod day012;
//mod day013;
//mod day014;
//mod day015;
//mod day016;
//mod day017;
//mod day018;
//mod day019;
//mod day020;
//mod day021;
//mod day022;
//mod day023;
//mod day024;
//mod day025;
pub use day001::*;
pub use day002::*;
pub use day003::*;
pub use day004::*;
pub use day005::*;
pub use day006::*;
pub use day007::*;
pub use day008::*;
pub use day009::*;