add 85 and 86

This commit is contained in:
Dr. Matthias Ratajczak
2023-06-20 14:25:54 +02:00
parent 8756fa7dcc
commit 1a34dfda82
4 changed files with 145 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "euler85"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+66
View File
@@ -0,0 +1,66 @@
const TARGET: usize = 2_000_000;
fn main() {
let mut x = 1_000;
let mut y = 2;
let mut grid = Grid::new(x, y);
let mut number;
let mut best_grid = grid.clone();
let mut best_diff = 5_000_000;
loop {
number = grid.number_rectangles();
let diff = number.abs_diff(TARGET);
if diff < best_diff {
best_diff = diff;
best_grid = grid.clone();
}
if number < TARGET {
y += 1;
} else {
x -= 1;
}
if x == 1 {
break;
}
grid = Grid::new(x, y);
}
let area = best_grid.area();
println!("{area}");
}
#[derive(Debug, Clone)]
struct Grid {
x: usize,
y: usize,
}
impl Grid {
fn new(x: usize, y: usize) -> Self {
Self { x, y }
}
fn number_rectangles(&self) -> usize {
let mut result = 0;
for x in 1..=self.x {
for y in 1..=self.y {
result += self.fits(x, y);
}
}
result
}
fn fits(&self, x: usize, y: usize) -> usize {
let fits_in_x = self.x - (x - 1);
let fits_in_y = self.y - (y - 1);
fits_in_x * fits_in_y
}
fn area(&self) -> usize {
self.x * self.y
}
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "euler86"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.release]
lto = "fat"
debug = true
+60
View File
@@ -0,0 +1,60 @@
use std::f64::EPSILON;
const TARGET: u32 = 1_000_000;
fn main() {
let mut m = 1;
let mut distinct = 0;
loop {
println!("trying: {m}");
for x in 1..m + 1 {
for y in x..m + 1 {
let z = m;
let c = Cuboid::new(x, y, z);
if c.shortest_path_is_integer() {
distinct += 1;
};
}
}
if distinct > TARGET {
break;
}
m += 1;
}
println!("\n{m}");
}
struct Cuboid {
x: u32,
y: u32,
z: u32,
}
impl Cuboid {
fn new(x: u32, y: u32, z: u32) -> Self {
Self { x, y, z }
}
fn shortest_path_is_integer(&self) -> bool {
// because of the way we iterator over x, y and z, these are guaranteed to be in order
// and therefore produces the shortest path
let shortest_path = pythagorean(self.x + self.y, self.z);
is_integer(shortest_path)
}
}
fn pythagorean(x: u32, y: u32) -> f64 {
((x.pow(2) + y.pow(2)) as f64).sqrt()
}
fn is_integer(result: f64) -> bool {
let rounded = result.round();
(result - rounded).abs() <= EPSILON
}