Skip to content

Commit

Permalink
fix subrepo
Browse files Browse the repository at this point in the history
  • Loading branch information
MellKam committed Dec 2, 2022
1 parent 70808ed commit a745940
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 1 deletion.
1 change: 0 additions & 1 deletion day_1/rust
Submodule rust deleted from a22d23
8 changes: 8 additions & 0 deletions day_1/rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "day_1_rust"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
54 changes: 54 additions & 0 deletions day_1/rust/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
mod quick_sort;

use quick_sort::quick_sort;
use std::fs;

// Part one
fn find_largest_calorie_size(calorie_list: &String) -> i32 {
let mut max: i32 = 0;
let mut temp_sum: i32 = 0;
for line in calorie_list.lines() {
if line == "" {
if temp_sum > max {
max = temp_sum
};
temp_sum = 0;
continue;
}
temp_sum += line.parse::<i32>().unwrap();
}

return max;
}

// Part two
fn find_three_largest_calorie_size(calorie_list: &String) -> i32 {
let mut total_calories = Vec::<i32>::new();
let mut temp_sum: i32 = 0;

for line in calorie_list.lines() {
if line == "" {
total_calories.push(temp_sum);
temp_sum = 0;
continue;
}

temp_sum += line.parse::<i32>().unwrap();
}

quick_sort(&mut total_calories);

let length = total_calories.len();

return total_calories[length - 3] + total_calories[length - 2] + total_calories[length - 1];
}

fn main() {
let data = fs::read_to_string("../input.txt").expect("Error while trying to read input file");

let max_total = find_largest_calorie_size(&data);
let three_max_total = find_three_largest_calorie_size(&data);

println!("max total: {max_total}");
println!("three max total: {three_max_total}");
}
36 changes: 36 additions & 0 deletions day_1/rust/src/quick_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
pub fn quick_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
_quick_sort(arr, 0, (len - 1) as isize);
}

fn _quick_sort<T: Ord>(arr: &mut [T], low: isize, high: isize) {
if low < high {
let p = partition(arr, low, high);
_quick_sort(arr, low, p - 1);
_quick_sort(arr, p + 1, high);
}
}

fn partition<T: Ord>(arr: &mut [T], low: isize, high: isize) -> isize {
let pivot = high as usize;
let mut store_index = low - 1;
let mut last_index = high;

loop {
store_index += 1;
while arr[store_index as usize] < arr[pivot] {
store_index += 1;
}
last_index -= 1;
while last_index >= 0 && arr[last_index as usize] > arr[pivot] {
last_index -= 1;
}
if store_index >= last_index {
break;
} else {
arr.swap(store_index as usize, last_index as usize);
}
}
arr.swap(store_index as usize, pivot as usize);
store_index
}

0 comments on commit a745940

Please sign in to comment.