Compare commits

...

10 Commits

Author SHA1 Message Date
b3f9c09f44 Wrote program for Day 10
https://en.wikipedia.org/wiki/Catalan_number
2024-08-04 16:37:26 +02:00
7c5fdc5242 Wrote program for Day 9 2024-08-03 14:57:17 +02:00
6ee3c88c30 Wrote program for Day 8 2024-08-02 21:50:37 +02:00
1fb8530cbc Wrote program for Day 7 2024-08-01 13:17:53 +02:00
2027871010 Wrote program for Day 6 2024-07-31 21:14:40 +02:00
9b06185114 Wrote program for Day 5 2024-07-30 11:17:39 +02:00
539eddce01 Wrote program for Day 4 2024-07-29 15:57:03 +02:00
0dc867ecb5 Wrote program for Day 3 2024-07-28 13:57:52 +02:00
042f3bf7fa Wrote program for Day 2 2024-07-27 14:59:53 +02:00
4f0b2678c2 Wrote program for Day 1 2024-07-26 16:03:54 +02:00
33 changed files with 535 additions and 23 deletions

View File

@ -3,6 +3,4 @@ name = "convert_ages_to_days"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]

View File

@ -1,27 +1,22 @@
use std::io; use std::io::{self, Write};
fn calc_age(age: u16) -> u16 {
const DAYS_IN_YEAR: u16 = 365;
return age * DAYS_IN_YEAR;
}
fn main() { fn main() {
print!("Write your age: ");
io::stdout().flush().expect("Failed to flush stdout.");
loop { let mut buffer = String::new();
println!("Please input your age in years!");
let mut guess = String::new();
io::stdin() io::stdin()
.read_line(&mut guess) .read_line(&mut buffer)
.expect("Could not read age. Make you an integer is used."); .expect("Error while trying to read from stdin.");
let guess: u32 = match guess.trim().parse() { let age: u16 = buffer.trim().parse()
Ok(num) => num, .expect("The input is not an integer between 0 and 65535");
Err(_) => continue,
};
let age: u32 = guess * 365;
println!("You are roughly {age} days old!")
}
let days = calc_age(age);
println!("Your age is about {} days", days);
} }

View File

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

View File

@ -0,0 +1,29 @@
use std::io::{self, Write};
fn find_nemo(word: &str) -> Option<usize> {
for (i, word) in word.split(" ").enumerate() {
if word == "Nemo" {
return Some(i + 1);
}
}
None
}
fn main() {
let mut buffer = String::new();
print!("Insert your words: ");
io::stdout().flush().expect("Failed to flush stdout.");
io::stdin()
.read_line(&mut buffer)
.expect("Error while trying to read from stdin.");
let nemo = find_nemo(&buffer);
match nemo {
Some(x) => println!("I found Nemo at {}!", x),
None => println!("I can't find Nemo :("),
}
}

View File

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

View File

@ -0,0 +1,57 @@
fn bbq_skewers(skewers: &'static [&str]) -> (usize, usize) {
let mut vegetarian = 0;
for skewer in skewers {
if ! skewer.contains('x') {
vegetarian += 1;
}
}
return (vegetarian, skewers.len() - vegetarian);
}
#[test]
fn test1() {
assert_eq!(
bbq_skewers(&[
"--xo--x--ox--",
"--xx--x--xx--",
"--oo--o--oo--",
"--xx--x--ox--",
"--xx--x--ox--"
]),
(1, 4)
);
}
#[test]
fn test2() {
assert_eq!(
bbq_skewers(&[
"--oooo-ooo---",
"--xx--x--xx--",
"--o---o--oo--",
"--xx--x--ox--",
"--xx--x--ox--"
]),
(2, 3)
);
}
#[test]
fn test3() {
assert_eq!(
bbq_skewers(&[
"--oooo-ooo--",
"--xxxxxxxx--",
"--o---",
"-o-----o---x--",
"--o---o-----"
]),
(3, 2)
);
}
fn main() {
println!("Run `cargo test`.");
}

View File

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

View File

@ -0,0 +1,11 @@
pub fn progress_days(days: &'static [usize]) -> usize {
let mut progress_days = 0;
for i in 1..days.len() {
if days[i] > days[i-1] {
progress_days += 1;
}
}
progress_days
}

View File

@ -0,0 +1,3 @@
fn main() {
println!("Run `cargo test`.");
}

View File

@ -0,0 +1,21 @@
use is_johnny_making_progress::progress_days;
#[test]
fn no_progress_days() {
assert_eq!(progress_days(&[9, 9]), 0);
}
#[test]
fn one_progress_day() {
assert_eq!(progress_days(&[6, 5, 4, 3, 2, 9]), 1);
}
#[test]
fn two_progress_days() {
assert_eq!(progress_days(&[3, 4, 1, 2]), 2);
}
#[test]
fn three_progress_days() {
assert_eq!(progress_days(&[10, 11, 12, 9, 10]), 3);
}

View File

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

View File

@ -0,0 +1,12 @@
pub fn sock_pairs(socks: &str) -> usize {
let mut sock_pairs = 0;
let mut socks = String::from(socks);
while !socks.is_empty() {
let full_length = socks.len();
socks = socks.replace(socks.chars().next().unwrap(), "");
sock_pairs += (full_length - socks.len()) / 2;
}
sock_pairs
}

View File

@ -0,0 +1,16 @@
use pair_of_socks::sock_pairs;
#[test]
fn one_sock_pair() {
assert_eq!(sock_pairs("AA"), 1);
}
#[test]
fn two_sock_pair() {
assert_eq!(sock_pairs("ABABC"), 2);
}
#[test]
fn four_sock_pair() {
assert_eq!(sock_pairs("CABBACCC"), 4);
}

View File

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

View File

@ -0,0 +1,16 @@
pub fn next_prime(num: usize) -> Option<usize> {
let max_next_prime = num * 2;
let mut is_prime: Vec<bool> = vec![true; max_next_prime];
for i in 2..max_next_prime {
for j in (i * 2..max_next_prime).step_by(i) {
is_prime[j] = false;
}
if i >= num && is_prime[i] {
return Some(i);
}
}
None
}

View File

@ -0,0 +1,23 @@
use next_prime::next_prime;
use std::io::{self, Write};
fn main() {
let mut buffer = String::new();
print!("Give me an integer, and I will return the first prime found from that: ");
io::stdout().flush().expect("Failed to flush stdout.");
io::stdin()
.read_line(&mut buffer)
.expect("Error while trying to read the number.");
let num: usize = buffer
.trim()
.parse()
.expect("The input inserted is not a valid integer");
match next_prime(num) {
Some(x) => println!("Here's the first prime found from {}: {}", num, x),
None => println!("None found"),
}
}

View File

@ -0,0 +1,16 @@
use next_prime::next_prime;
#[test]
fn first_example() {
assert_eq!(next_prime(12), Some(13));
}
#[test]
fn second_example() {
assert_eq!(next_prime(24), Some(29));
}
#[test]
fn third_example() {
assert_eq!(next_prime(11), Some(11));
}

View File

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

View File

@ -0,0 +1,21 @@
pub fn merge(arr1: &mut [usize], arr2: &[usize]) {
let arr2_len = arr2.len();
let arr1_len = arr1.len() - arr2_len;
let mut arr2_iterator = 0;
let mut arr1_iterator = 0;
let temp_arr1 = arr1.to_vec();
for _ in 0..arr1_len + arr2_len {
if arr1_iterator == arr1_len {
arr1[arr1_iterator + arr2_iterator] = arr2[arr2_iterator];
arr2_iterator += 1;
} else if arr2_iterator == arr2_len || temp_arr1[arr1_iterator] <= arr2[arr2_iterator] {
arr1[arr1_iterator + arr2_iterator] = temp_arr1[arr1_iterator];
arr1_iterator += 1;
} else if arr2[arr2_iterator] < temp_arr1[arr1_iterator] {
arr1[arr1_iterator + arr2_iterator] = arr2[arr2_iterator];
arr2_iterator += 1;
}
}
}

View File

@ -0,0 +1,46 @@
use std::io::{self, Write};
use merge_sorted_array::merge;
fn main() {
let mut buffer = String::new();
print!("Insert the first set of numbers separated by a space: ");
io::stdout().flush().expect("Failed to flush stdout.");
io::stdin()
.read_line(&mut buffer)
.expect("Failed to read from stdin.");
let mut nums1: Vec<usize> = buffer
.split(' ')
.map(|x| x.trim())
.filter(|x| !x.is_empty())
.map(|x| x.parse().expect("A non-integer has been inserted."))
.collect();
nums1.sort();
print!("Insert the second set of numbers separated by a space: ");
io::stdout().flush().expect("Failed to flush stdout.");
buffer = String::new();
io::stdin()
.read_line(&mut buffer)
.expect("Failed to read from stdin.");
let mut nums2: Vec<usize> = buffer
.split(' ')
.map(|x| x.trim())
.filter(|x| !x.is_empty())
.map(|x| x.parse().expect("A non-integer has been inserted."))
.collect();
nums2.sort();
nums1.resize(nums1.len() + nums2.len(), 0);
merge(&mut nums1, &nums2);
let merged: String = nums1.into_iter().map(|x| x.to_string() + " ").collect();
println!("Your ordered and merged sets: {}", merged);
}

View File

@ -0,0 +1,9 @@
use merge_sorted_array::merge;
#[test]
fn example() {
let mut nums1 = [1, 2, 3, 0, 0, 0];
let nums2 = [2, 5, 6];
merge(&mut nums1, &nums2);
assert_eq!(nums1, [1, 2, 2, 3, 5, 6]);
}

View File

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

View File

@ -0,0 +1,37 @@
fn digit_to_chars(digit: char) -> Vec<char> {
match digit {
'2' => vec!['a', 'b', 'c'],
'3' => vec!['d', 'e', 'f'],
'4' => vec!['g', 'h', 'i'],
'5' => vec!['j', 'k', 'l'],
'6' => vec!['m', 'n', 'o'],
'7' => vec!['p', 'q', 'r', 's'],
'8' => vec!['t', 'u', 'v'],
'9' => vec!['w', 'x', 'y', 'z'],
_ => panic!(
"Character out of range: '{}' is not between '2' and '9'.",
digit
),
}
}
pub fn combination(digits: &str) -> Vec<String> {
let mut combinations: Vec<String> = vec![String::new()];
for d in digits.chars() {
let mut temp = Vec::new();
for c in combinations {
let chars = digit_to_chars(d);
for ch in chars {
temp.push(format!("{}{}", c, ch));
}
}
combinations = temp;
}
if combinations.len() == 1 {
vec![] as Vec<String>
} else {
combinations
}
}

View File

@ -0,0 +1,21 @@
use std::io::{self, Write};
use day8::combination;
fn main() {
let mut buffer = String::new();
print!("Insert the digits: ");
io::stdout().flush().expect("Failed to flush stdout.");
io::stdin()
.read_line(&mut buffer)
.expect("Failed to read the digits.");
let combinations = combination(buffer.trim());
println!(
"Those are all the possible combinations: {:?}",
combinations
);
}

View File

@ -0,0 +1,19 @@
use day8::combination;
#[test]
fn example1() {
assert_eq!(
combination("23"),
vec!["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
);
}
#[test]
fn example2() {
assert_eq!(combination(""), vec![] as Vec<String>);
}
#[test]
fn example3() {
assert_eq!(combination("2"), vec!["a", "b", "c"]);
}

View File

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

View File

@ -0,0 +1,26 @@
pub fn trap(heights: Vec<u8>) -> u16 {
let maxh = heights.iter().max().cloned().unwrap_or(0);
let mut water: u16 =
maxh as u16 * heights.len() as u16 - heights.iter().map(|x| *x as u16).sum::<u16>();
let mut maxt;
maxt = 0;
for h in heights.iter() {
maxt = std::cmp::max(maxt, *h);
if maxt == maxh {
break;
}
water -= maxh as u16 - maxt as u16;
}
maxt = 0;
for h in heights.iter().rev() {
maxt = std::cmp::max(maxt, *h);
if maxt == maxh {
break;
}
water -= maxh as u16 - maxt as u16;
}
water
}

View File

@ -0,0 +1,24 @@
use std::io::{self, Write};
use day9::trap;
fn main() {
let mut buffer = String::new();
print!("Insert space separated heights: ");
io::stdout().flush().expect("Failed to flush stdout.");
io::stdin()
.read_line(&mut buffer)
.expect("Failed to read from input.");
let heights = buffer
.trim()
.split(' ')
.filter(|x| !x.is_empty())
.map(|x| x.parse().expect("A not number has been found"))
.collect();
let water = trap(heights);
println!("{}", water);
}

View File

@ -0,0 +1,11 @@
use day9::trap;
#[test]
fn exaple1() {
assert_eq!(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1].to_vec()), 6);
}
#[test]
fn exaple2() {
assert_eq!(trap([4, 2, 0, 3, 2, 5].to_vec()), 9);
}

View File

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

View File

@ -0,0 +1,9 @@
pub fn catalan_number(n: u8) -> usize {
let mut result = 1f64;
for k in 2..=n {
result *= (n as f64 + k as f64) / k as f64;
}
result.round() as usize
}

View File

@ -0,0 +1,24 @@
use std::io::{self, Write};
use day10::catalan_number;
fn main() {
let mut buffer = String::new();
print!("Insert n: ");
io::stdout().flush().expect("Failed to flush stdout.");
io::stdin()
.read_line(&mut buffer)
.expect("Failed to read from stdin.");
let n: u8 = buffer
.trim()
.parse()
.expect("The input is not a positive integer");
println!(
"The number of structurally unique BST's that store values from 1 to n is {}",
catalan_number(n)
);
}

View File

@ -0,0 +1,14 @@
use day10::catalan_number;
#[test]
fn example() {
assert_eq!(catalan_number(3), 5);
}
#[test]
fn examplu() {
let array = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786];
for (i, a) in array.into_iter().enumerate() {
assert_eq!(catalan_number(i as u8), a);
}
}