Skip to content
Snippets Groups Projects
Commit 4cdcf1da authored by iliya.saroukha's avatar iliya.saroukha
Browse files

added exercises

parents
No related branches found
No related tags found
No related merge requests found
Showing with 442 additions and 0 deletions
rust-101/
Cargo.lock
/target
[package]
name = "frac_rs"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
num = "0.4.1"
use num::integer::{gcd, lcm};
use std::ops::{Add, Div, Mul, Sub};
#[derive(Debug, Clone, Copy)]
pub struct Frac {
num: i128,
denom: i128,
}
#[derive(Debug)]
pub enum FractionError {
DenomZero,
Underflow,
Overflow,
}
impl Frac {
pub fn new(num: i128, denom: i128) -> Result<Self, FractionError> {
let valid_num = match num {
_n if num > std::i128::MAX => return Err(FractionError::Overflow),
_n if num < std::i128::MIN => return Err(FractionError::Underflow),
_ => num,
};
let valid_denom = match denom {
_d if denom > std::i128::MAX => return Err(FractionError::Overflow),
_d if denom < std::i128::MIN => return Err(FractionError::Underflow),
_d if denom == 0 => return Err(FractionError::DenomZero),
_ => denom,
};
Ok(Frac {
num: valid_num,
denom: valid_denom,
})
}
fn simplify(&mut self, factor: i128) {
self.num /= factor;
self.denom /= factor;
}
// pub fn print<T: std::fmt::Display>(&self) {
// println!("{}", self.num);
// println!("--");
// println!("{}", self.denom);
// }
}
impl Add for Frac {
type Output = Result<Frac, FractionError>;
fn add(self, rhs: Self) -> Result<Frac, FractionError> {
let lcm = lcm(self.denom, rhs.denom);
let lhs_factor = lcm / self.denom;
let rhs_factor = lcm / rhs.denom;
let num = self.num * lhs_factor + rhs.num * rhs_factor;
let valid_num = match num {
_n if num > std::i128::MAX => return Err(FractionError::Overflow),
_n if num < std::i128::MIN => return Err(FractionError::Underflow),
_ => num,
};
let mut res = Frac {
num: valid_num,
denom: lcm,
};
let gcd = gcd(res.num, res.denom);
res.simplify(gcd);
Ok(res)
}
}
impl Sub for Frac {
type Output = Result<Frac, FractionError>;
fn sub(self, rhs: Self) -> Result<Frac, FractionError> {
let lcm = lcm(self.denom, rhs.denom);
let lhs_factor = lcm / self.denom;
let rhs_factor = lcm / rhs.denom;
let num = self.num * lhs_factor + rhs.num * rhs_factor;
let valid_num = match num {
_n if num > std::i128::MAX => return Err(FractionError::Overflow),
_n if num < std::i128::MIN => return Err(FractionError::Underflow),
_ => num,
};
let mut res = Frac {
num: valid_num,
denom: lcm,
};
let gcd = gcd(res.num, res.denom);
res.simplify(gcd);
Ok(res)
}
}
impl Mul for Frac {
type Output = Frac;
fn mul(self, rhs: Self) -> Frac {
let mut res = Frac {
num: self.num * rhs.num,
denom: self.denom * rhs.denom,
};
let gcd = gcd(res.num, res.denom);
res.simplify(gcd);
res
}
}
impl Div for Frac {
type Output = Frac;
fn div(self, rhs: Self) -> Frac {
let mut res = Frac {
num: self.num * rhs.denom,
denom: self.denom * rhs.num,
};
let gcd = gcd(res.num, res.denom);
res.simplify(gcd);
res
}
}
use crate::frac::{Frac, FractionError};
mod frac;
fn main() -> Result<(), FractionError> {
let lhs = Frac::new(1, 4)?;
let rhs = Frac::new(2, 5)?;
println!("lhs + rhs = {:?}", lhs + rhs);
println!("lhs - rhs = {:?}", lhs - rhs);
println!("lhs * rhs = {:?}", lhs * rhs);
println!("lhs / rhs = {:?}", lhs / rhs);
Ok(())
}
/target
[package]
name = "pi_rs"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
use rand::Rng;
use crate::square::Square;
mod square;
fn main() {
let mut rng = rand::thread_rng();
let new_square = Square::new(9);
let bounded_range = new_square.compute_range();
let iter = 69420;
let mut count = 0;
for _ in 0..iter {
let x = rng.gen_range(bounded_range.clone());
let y = rng.gen_range(bounded_range.clone());
match new_square.valid_point((x, y)) {
true => count += 1,
false => continue,
}
}
println!("The area of the given circle is {}", new_square.circle_area());
println!("For n = {iter}, the estimated value of π is = {}", (count * 4) as f64 / (iter as f64));
}
use std::ops::Range;
pub struct Square {
side: u32,
}
impl Square {
pub fn new(side: u32) -> Self {
Square { side }
}
pub fn circle_area(&self) -> f64 {
std::f64::consts::PI * (self.side as f64 / 2.0).powf(2.0)
}
pub fn valid_point(&self, point: (f64, f64)) -> bool {
point.0.powi(2) + point.1.powi(2) < self.side.pow(2) as f64
}
pub fn compute_range(&self) -> Range<f64> {
-(self.side as f64)..(self.side as f64)
}
}
/target
[package]
name = "queen_rs"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8"
use rand::Rng;
use std::collections::HashSet;
const BOARD_DIM: usize = 8;
fn compute_possible_solutions(board: &[[bool; BOARD_DIM]; BOARD_DIM]) -> HashSet<(usize, usize)> {
let mut solutions: HashSet<(usize, usize)> = HashSet::new();
let mut current_pos: (usize, usize) = (0, 0);
for (i, _row) in board.iter().enumerate() {
for (j, _col) in board.iter().enumerate() {
match board[i][j] {
true => {
current_pos.0 = i;
current_pos.1 = j;
}
false => continue,
};
}
}
//Whole column of a given X value
//Whole row of a given Y value
for i in 0..BOARD_DIM {
solutions.insert((current_pos.0, i));
solutions.insert((i, current_pos.1));
}
solutions
}
fn print_solutions(positions: &HashSet<(usize, usize)>) {
for i in 0..BOARD_DIM {
print!("{} | ", i);
for j in 0..BOARD_DIM {
if positions.contains(&(i, j)) {
print!("* ");
continue;
}
print!("_ ");
}
println!();
}
}
fn main() {
let mut rng = rand::thread_rng();
let (x, y) = (rng.gen_range(0..BOARD_DIM), rng.gen_range(0..BOARD_DIM));
println!("Selected location for queen: X = {x}, Y = {y}");
let mut board: [[bool; BOARD_DIM]; BOARD_DIM] = [[false; BOARD_DIM]; BOARD_DIM];
board[x][y] = true;
let res = compute_possible_solutions(&board);
println!("Current length of vector: {}", res.len());
println!();
print_solutions(&res);
// res.iter().for_each(|x| println!("{:?}", x));
}
/target
[package]
name = "sorting_algos_rs"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
fn bubble_sort(arr: &mut [i32]) {
for i in 0..arr.len() - 1 {
for j in 0..arr.len() - 1 - i {
if arr[j] > arr[j + 1] {
arr.swap(j, j + 1);
}
}
}
}
fn main() {
let mut needs_sorting = [6, -9, 4, -2, 0];
println!("Before sorting: {:?}", needs_sorting);
bubble_sort(&mut needs_sorting);
println!("After sorting: {:?}", needs_sorting);
}
/target
Cargo.lock
[package]
name = "stack_rs"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
use crate::stack::Stack;
use rand::Rng;
mod stack;
const SIZE: usize = 10;
fn two_stacks_sort<T: Copy + PartialOrd>(data_to_sort: &mut Vec<T>) {
let mut lhs: Stack<T> = Stack::new();
let mut rhs: Stack<T> = Stack::new();
for i in 0..data_to_sort.len() {
if lhs.is_empty() {
lhs.push(data_to_sort[i]);
continue;
}
while !lhs.is_empty() && data_to_sort[i] > *lhs.peek().unwrap() {
match lhs.pop() {
Some(v) => rhs.push(v),
None => (),
};
}
while !rhs.is_empty() && data_to_sort[i] < *rhs.peek().unwrap() {
match rhs.pop() {
Some(v) => lhs.push(v),
None => (),
};
}
lhs.push(data_to_sort[i]);
}
while !rhs.is_empty() {
match rhs.pop() {
Some(v) => lhs.push(v),
None => (),
};
}
for i in 0..data_to_sort.len() {
if let Some(v) = lhs.pop() {
data_to_sort[i] = v;
}
}
}
fn main() {
let mut rng = rand::thread_rng();
let mut data: Vec<f64> = Vec::new();
// data.push(17);
// data.push(34);
// data.push(20);
// data.push(40);
// data.push(25);
for _ in 0..SIZE {
data.push(rng.gen_range(-1e-1..1e-1));
}
println!("Before sorting: {:.3?}", data);
two_stacks_sort(&mut data);
println!("After sorting: {:.3?}", data);
}
pub struct Stack<T> {
data: Vec<T>,
}
impl<T: std::fmt::Display> std::fmt::Display for Stack<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for item in &self.data {
write!(f, "{} ", item)?;
}
Ok(())
}
}
#[allow(dead_code)]
impl<T> Stack<T> {
pub fn new() -> Stack<T> {
Stack { data: Vec::new() }
}
pub fn is_empty(&self) -> bool {
self.data.len() == 0
}
pub fn push(&mut self, value: T) {
self.data.insert(0, value)
}
pub fn pop(&mut self) -> Option<T> {
match self.data.len() {
0 => None,
_ => Some(self.data.remove(0)),
}
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn peek(&self) -> Option<&T> {
self.data.get(0)
}
}
/target
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment