Compare commits

..

2 Commits

Author SHA1 Message Date
8e30ece8b9 day09: rust 2023-12-09 11:53:39 +01:00
a1eccb5f34 add loc 2023-12-09 11:53:29 +01:00
13 changed files with 172 additions and 17 deletions

View File

@ -3,6 +3,8 @@
Today's language: **Python** Today's language: **Python**
Lines of code: **3**
Execution time: **0,021 s** Execution time: **0,021 s**
Both tasks are solved in one hell of a oneliner each: Both tasks are solved in one hell of a oneliner each:

View File

@ -3,6 +3,7 @@
Today's language: **Rust** Today's language: **Rust**
Lines of code: **49**
Execution time: **0,002 s** Execution time: **0,002 s**

View File

@ -3,6 +3,8 @@
Today's language: **Rust** Today's language: **Rust**
Lines of code: **85**
Execution time: **0,006 s** Execution time: **0,006 s**
```shell ```shell

View File

@ -3,6 +3,8 @@
Today's language: **Rust** Today's language: **Rust**
Lines of code: **40**
Execution time: **0,004 s** Execution time: **0,004 s**
```shell ```shell

View File

@ -3,6 +3,8 @@
Today's language: **Rust** Today's language: **Rust**
Lines of code: **138**
Execution time: **0,009 s** Execution time: **0,009 s**
Super fast! Super fast!

View File

@ -3,6 +3,8 @@
Today's language: **Rust** Today's language: **Rust**
Lines of code: **60**
Execution time: **0,001 s** Execution time: **0,001 s**
*Midnight formula go brrrrr* *Midnight formula go brrrrr*

View File

@ -3,6 +3,8 @@
Today's language: **Rust** Today's language: **Rust**
Lines of code: **210**
Execution time: **0,007 s** Execution time: **0,007 s**
Not pretty, but pretty fast. Not pretty, but pretty fast.

View File

@ -3,6 +3,8 @@
Today's language: **Rust** Today's language: **Rust**
Lines of code: **101**
Execution time: **0,039 s** Execution time: **0,039 s**
Next time, I should just use 64 bit right from the start... Next time, I should just use 64 bit right from the start...

17
09/README.md Normal file
View File

@ -0,0 +1,17 @@
# [Day 9](https://adventofcode.com/2023/day/9)
:gift::gift::gift::gift::gift::gift::gift::gift::gift:
Today's language: **Rust**
Lines of code: **88**
Execution time: **0,003 s**
This solution uses a custom triangle datatype.
It is a bit overkill code-wise, but efficient with memory and re-allocations.
```shell
rustc day09.rs
./day09
```
<!-- implemented triangle datatype -->

114
09/day09.rs Normal file
View File

@ -0,0 +1,114 @@
use std::io::{self, BufRead};
use std::fmt::Debug;
use std::fmt;
// 0 1 3 6 10 ...
fn triangular_numbers(n: usize) -> usize { (n * (n + 1)) / 2 }
struct Triangle {
data: Vec::<i32>,
width: usize,
}
impl Triangle {
fn new(firstrow: &mut Vec<i32>) -> Triangle {
let mut triangle = Triangle{data: Vec::new(), width: firstrow.len()};
triangle.data = std::mem::take(firstrow);
triangle.data.resize(triangular_numbers(triangle.width), 0);
return triangle
}
fn at_mut(&mut self, row: usize, col: usize) -> &mut i32 {
let i = self._index(row, col);
&mut self.data[i]
}
fn at(&self, row: usize, col: usize) -> i32 {
self.data[self._index(row, col)]
}
// 1 2 3 4
// 1 2 3
// 1 2
// 1
fn _index(&self, row: usize, col: usize) -> usize {
assert!(col < self.row_len(row), "Invalid indices for Triangle with width {}: row={}, col={}", self.width, row, col);
return col + self.data.len() - triangular_numbers(self.width - row); // subtract the triangle with width (self.width - row) from total length
}
// fn row(&mut self, row: usize) -> impl Iterator<Item = &mut i32> {
// assert!(row < self.width, "Invalid row");
// let skip: usize = self.width * row - triangular_numbers(self.width - row); // skip <row> rows - the triangle with width (self.width - row)
// self.data.iter_mut().skip(skip).take(self.row_len(row));
// }
// #rows or #colums of first row
fn len(&self) -> usize { self.width }
fn row_len(&self, row: usize) -> usize { self.width - row }
}
impl fmt::Display for Triangle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for r in 0..self.len() {
for c in 0..self.row_len(r) {
let res = write!(f, "{} ", self.at(r, c));
if res.is_err() { return res };
}
if r != self.len() - 1 { println!() }
}
return Result::Ok(());
}
}
fn predict(numbers: &mut Vec<i32>) -> (i32, i32) {
numbers.insert(0, 0);
numbers.push(0);
let mut triangle = Triangle::new(numbers);
// fill until maxrow is all zero
let mut maxrow: usize = triangle.len() - 1; // skip last row
for r in 1..maxrow {
maxrow = r;
let mut allzero = true;
for j in 1..triangle.row_len(r) - 1 {
// print!("{} -> ", triangle.at(r, j));
let diff = triangle.at(r-1, j+1) - triangle.at(r-1, j); //).abs();
allzero &= diff == 0;
*triangle.at_mut(r, j) = diff;
}
if allzero { break }
// println!();
}
assert!(maxrow < triangle.len()- 3, "maxrow={} ", maxrow);
for r in (0..maxrow).rev() {
// forward prediction
let newval = triangle.at(r, triangle.row_len(r) - 2) + triangle.at(r + 1, triangle.row_len(r + 1) - 1);
*triangle.at_mut(r, triangle.row_len(r) - 1) = newval;
let newval = triangle.at(r, 1) - triangle.at(r + 1, 0);
*triangle.at_mut(r, 0) = newval;
}
// println!("{}", triangle);
return (triangle.at(0, 0), triangle.at(0, triangle.row_len(0) - 1));
}
fn main() {
let input = "input.txt";
// let input = "example.txt";
let lines = read_lines(&input);
let mut sum_forward_predictions = 0;
let mut sum_backward_predictions = 0;
for line in lines.map(|r| r.ok().unwrap()) {
let preds = predict(&mut split_into_numbers::<i32>(&line).collect());
sum_backward_predictions += preds.0;
sum_forward_predictions += preds.1;
}
println!("OASIS: sum of forward predictions (1): {}", sum_forward_predictions);
println!("OASIS: sum of backward predictions (2): {}", sum_backward_predictions);
}
fn split_into_numbers<T: std::str::FromStr>(x: &str) -> impl Iterator<Item = T> + '_ where <T as std::str::FromStr>::Err: Debug {
return x.split(' ').filter(|&n| {n != "" && n != " "}).map(|n| n.parse::<T>().unwrap());
}
fn read_lines<P>(filename: P) -> io::Lines<io::BufReader<std::fs::File>>
where P: AsRef<std::path::Path>, {
return match std::fs::File::open(filename) {
Err(why) => panic!("Could not open file. {}", why),
Ok(file) => std::io::BufReader::new(file).lines()
};
}

View File

@ -2,13 +2,16 @@
This is a repository for my solutions for the [advent of code 2023](https://adventofcode.com/2023). This is a repository for my solutions for the [advent of code 2023](https://adventofcode.com/2023).
<!-- table begin --> <!-- table begin -->
| Day | Language | Execuction time | Comment | | Day | Language | Lines of code | Execuction time | Comment |
|:---: |:---: | ---: | --- | |:---: |:---: | ---: | --- | |
| [01](01) | Python | 0,021 s | one-liners | | [01](01) | Python | 3 | 0,021 s | one-liners |
| [02](02) | Rust | 0,002 s | my very first rust program | | [02](02) | Rust | 49 | 0,002 s | my very first rust program |
| [03](03) | Rust | 0,006 s | | | [03](03) | Rust | 85 | 0,006 s | |
| [04](04) | Rust | 0,004 s | | | [04](04) | Rust | 40 | 0,004 s | |
| [05](05) | Rust | 0,009 s | very efficient | | [05](05) | Rust | 138 | 0,009 s | very efficient |
| [06](06) | Rust | 0,001 s | quadratic formula go *brrr* | | [06](06) | Rust | 60 | 0,001 s | quadratic formula go *brrr* |
| [07](07) | Rust | 0,007 s | not pretty, but pretty fast | | [07](07) | Rust | 210 | 0,007 s | not pretty, but pretty fast |
| [08](08) | Rust | 0,039 s | | | [08](08) | Rust | 101 | 0,039 s | |
| [09](09) | Rust | 88 | 0,003 s | implemented triangle datatype |
Lines of code are without blank lines and comments

View File

@ -15,11 +15,14 @@ function find_lang {
# 1: fileext, 2: lang, 3: howto # 1: fileext, 2: lang, 3: howto
sourcefile=$(ls $day_dir/*.$1 2> /dev/null) sourcefile=$(ls $day_dir/*.$1 2> /dev/null)
[[ $? != 0 ]] && return [[ $? != 0 ]] && return
sourcefile=$(basename $sourcefile) lang=$2
printf "$FMT_VAR" "Determined Langugae" "$2 ($sourcefile)" sourcefilebase=$(basename $sourcefile)
printf "$FMT_VAR" "Determined Langugae" "$2 ($sourcefilebase)"
sed -i "s/LANG/$2/" $readme sed -i "s/LANG/$2/" $readme
howto=$(echo "$3" | sed "s|SOURCE|$sourcefile|") howto=$(echo "$3" | sed "s|SOURCE|$sourcefilebase|")
sed -i "s(HOWTORUN($howto(" $readme sed -i "s(HOWTORUN($howto(" $readme
loc=$(sed -r '/^\s*(#|\/\/|\/\*|;)/d;/^\s*$/d' $sourcefile | wc -l)
sed -i "s(LOC($loc(" $readme
} }
function get_time { function get_time {
@ -28,6 +31,7 @@ function get_time {
exe=$(basename $exe) exe=$(basename $exe)
if [[ $(echo $exe | wc -w) != 1 ]]; then if [[ $(echo $exe | wc -w) != 1 ]]; then
printf "$FMT_ERR" "Found multiple or no executables for day $day: '$exe'" printf "$FMT_ERR" "Found multiple or no executables for day $day: '$exe'"
cd ..
return 1 return 1
time=Error time=Error
else else
@ -37,6 +41,7 @@ function get_time {
printf "\e[34m" printf "\e[34m"
echo -e "$time" echo -e "$time"
printf "\e[0m" printf "\e[0m"
cd ..
return 1 return 1
fi fi
time=$(echo -e "$time" | tail -3 | head -1 | awk '{print $2}') time=$(echo -e "$time" | tail -3 | head -1 | awk '{print $2}')
@ -50,6 +55,7 @@ function get_time {
else else
time="$sec,$msec s" time="$sec,$msec s"
fi fi
cd ..
# elif [[ $sec != 0 ]]; then # elif [[ $sec != 0 ]]; then
# time="$sec,$msec s" # time="$sec,$msec s"
# else # else
@ -74,8 +80,6 @@ else
sed -i '/.*EXECTIME.*/d' $readme sed -i '/.*EXECTIME.*/d' $readme
fi fi
if [[ -z $1 ]]; then if [[ -z $1 ]]; then
printf "$FMT_WARN" "No comment provided" printf "$FMT_WARN" "No comment provided"
sed -i "/<!-- COMMENT -->/d" $readme sed -i "/<!-- COMMENT -->/d" $readme

View File

@ -1,15 +1,17 @@
#!/bin/bash #!/bin/bash
table="| Day | Language | Execuction time | Comment |\n" table="| Day | Language | Lines of code | Execuction time | Comment |\n"
table+="|:---:|:---:| ---:| --- |\n" table+="|:---:|:---:| ---:| --- |\n"
for day in $(seq -f "%02g" 1 25); do for day in $(seq -f "%02g" 1 25); do
[[ ! -d "$day" ]] && continue [[ ! -d "$day" ]] && continue
# echo $day # echo $day
lang=$(grep -E "Today's language:" $day/README.md | sed -r 's/.*\*\*(.+)\*\*.*/\1/') lang=$(grep -E "Today's language:" $day/README.md | sed -r 's/.*\*\*(.+)\*\*.*/\1/')
exectime=$(grep -E "Execution time:" $day/README.md | sed -r 's/.*\*\*(.+)\*\*.*/\1/') exectime=$(grep -E "Execution time:" $day/README.md | sed -r 's/.*\*\*(.+)\*\*.*/\1/')
loc=$(grep -E "Lines of code:" $day/README.md | sed -r 's/.*\*\*(.+)\*\*.*/\1/')
comment=$(grep -E "<!-- .* -->" $day/README.md | head -1 | sed -r 's/.*<!-- *(.*) *-->.*/\1/') comment=$(grep -E "<!-- .* -->" $day/README.md | head -1 | sed -r 's/.*<!-- *(.*) *-->.*/\1/')
table+="| [$day]($day) | $lang | $exectime | $comment |\n" table+="| [$day]($day) | $lang | $loc | $exectime | $comment |\n"
done done
# remove table from readme # remove table from readme
sed -i '/<!-- table begin -->/q' README.md sed -i '/<!-- table begin -->/q' README.md
echo -e $table | column -t -s '|' -o '|' >> README.md echo -e $table | column -t -s '|' -o '|' >> README.md
echo -e "\n Lines of code are without blank lines and comments" >> README.md