Skip to content

Commit

Permalink
-- practice refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
djnzx committed Oct 20, 2024
1 parent b1c41db commit 8859edb
Show file tree
Hide file tree
Showing 59 changed files with 370 additions and 63 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
itertools = "0.13.0"
colored = "2.1.0"
rand = "^0.8.5" # 0.8.5+, <0.9.0
time = "0.3.36"
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
13 changes: 13 additions & 0 deletions src/lectures/lec04/a4case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,16 @@ fn change_case() {
println!("{}", upper); // ПРИВІТ
println!("{}", lower); // привіт
}

#[test]
fn test1() {
// in some cases when letter becomes lowercase
// it has more than 1 symbol
let s = "ΣΣ";
let c = 'Æ';

let cl = c.to_lowercase();
let c2 = cl.collect::<String>();
println!("{}", s.to_lowercase());
println!("{}", c2);
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
mod homeworks;
mod lectures;
mod practice;
mod usecases;

fn main() {
println!("Hello from \u{211D}u\x73\x74😀!");
Expand Down
18 changes: 18 additions & 0 deletions src/practice/list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
### practical lessons

1. github
2. project structure
3. TODO
4. envelope - console
5. apples_and_oranges
6. chess_board - console
7. rhombus - console
8. brackets_is_valid_simple - string/array
9. brackets_max_level - string/array
10. shoes_groups - string/array
11. counting_valleys - string/array
12. parking_dilemma - array/array
13. brackets_is_valid_full - string/array
14. char_indexes - data manipulation
15. pack-unpack - data manipulation
16. 5317^1000000000
File renamed without changes.
File renamed without changes.
2 changes: 2 additions & 0 deletions src/practice/p04/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
mod envelope1;
mod envelope2;
Binary file added src/practice/p04/slides1.pdf
Binary file not shown.
Binary file added src/practice/p04/slides2.pdf
Binary file not shown.
File renamed without changes.
2 changes: 1 addition & 1 deletion src/practice/p05/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
mod envelope;
mod apple_and_oranges;
Binary file modified src/practice/p05/slides.pdf
Binary file not shown.
File renamed without changes.
2 changes: 1 addition & 1 deletion src/practice/p06/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
mod envelope;
mod chessboard;
Binary file modified src/practice/p06/slides.pdf
Binary file not shown.
2 changes: 1 addition & 1 deletion src/practice/p07/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
mod apple_and_oranges;
mod rhombus;
File renamed without changes.
Binary file modified src/practice/p07/slides.pdf
Binary file not shown.
File renamed without changes.
2 changes: 1 addition & 1 deletion src/practice/p08/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
mod chessboard;
mod brackets_is_valid;
Binary file removed src/practice/p08/slides.pdf
Binary file not shown.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion src/practice/p09/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
mod rhombus;
mod brackets_max_level;
Binary file removed src/practice/p09/slides.pdf
Binary file not shown.
2 changes: 1 addition & 1 deletion src/practice/p10/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
mod brackets_is_valid;
mod shoes_groups;
File renamed without changes.
File renamed without changes.
File renamed without changes.
62 changes: 62 additions & 0 deletions src/practice/p11/counting_valleys.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/// https://www.hackerrank.com/challenges/counting-valleys/problem
fn countingValleys1(steps: i32, path: &str) -> i32 {
struct State {
level: i32,
count: i32,
}

impl State {
fn new(level: i32, count: i32) -> State {
State { level, count }
}
fn fresh() -> Self {
Self::new(0, 0)
}
fn calc_delta(prev_level: i32, curr_level: i32) -> i32 {
match curr_level {
0 if prev_level < 0 => 1,
_ => 0,
}
}
fn up(&self) -> Self {
let curr_level = self.level + 1;
let delta_count = Self::calc_delta(self.level, curr_level);
State::new(curr_level, self.count + delta_count)
}
fn down(&self) -> Self {
let curr_level = self.level - 1;
let delta_count = Self::calc_delta(self.level, curr_level);
State::new(curr_level, self.count + delta_count)
}
fn process(&self, c: char) -> State {
match c {
'U' => self.up(),
'D' => self.down(),
_ => panic!("wrong char"),
}
}
}

path.chars()
.fold(State::fresh(), |st, c| st.process(c))
.count
}

fn countingValleys2(steps: i32, path: &str) -> i32 {
let mut prev_level = 0;
let mut count = 0;
for c in path.chars() {
let curr_level = match c {
'U' => prev_level + 1,
'D' => prev_level - 1,
_ => prev_level,
};
let delta = match curr_level {
0 if prev_level < 0 => 1,
_ => 0,
};
prev_level = curr_level;
count += delta;
}
count
}
3 changes: 1 addition & 2 deletions src/practice/p11/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
mod brackets_max_level;
mod shoes_groups;
mod counting_valleys;
50 changes: 0 additions & 50 deletions src/practice/p12/counting_valleys.rs

This file was deleted.

1 change: 0 additions & 1 deletion src/practice/p12/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
mod counting_valleys;
mod parking_dilemma;
46 changes: 46 additions & 0 deletions src/practice/p13/brackets_full.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use std::collections::{HashMap, HashSet};

fn brackets_is_valid_full(s: String) -> bool {
let pairs = HashMap::from([('}', '{'), (')', '('), (']', '['), ('>', '<')]);
let open = HashSet::<char>::from_iter("{[(<".chars());
let close = HashSet::<char>::from_iter("}])>".chars());

let mut stack = Vec::new();
for c in s.chars() {
match c {
c if open.contains(&c) => stack.push(c),
c if close.contains(&c) => match stack.pop() {
None => return false,
Some(top) => match pairs.get(&c) {
Some(&op) if op == top => (),
Some(_) | None => return false,
},
},
_ => continue,
}
}

stack.is_empty()
}

#[test]
fn is_valid_test2() {
let test_data = [
//input expected
("{}", true),
("[{(<>()[])}<>]", true),
("{}{}", true),
("{{}}", true),
("{{}{}}", true),
("{{}", false),
("{}}", false),
("}{", false),
("{", false),
("}", false),
("<}", false),
];

for (s, r) in test_data {
assert_eq!(brackets_is_valid_full(s.to_string()), r);
}
}
Empty file.
41 changes: 41 additions & 0 deletions src/practice/p14/char_indexes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use itertools::Itertools;
use std::collections::HashMap;

fn char_indexes(text: &String) -> HashMap<char, Vec<usize>> {
let mut outcome: HashMap<char, Vec<usize>> = HashMap::new();
text.chars()
.into_iter()
.zip(1..)
.filter(|&(c, _)| c.is_alphabetic())
.for_each(|(c, idx)| {
outcome
.entry(c.to_ascii_lowercase())
.or_insert_with(Vec::new)
.push(idx);
});

outcome
}

// with help of https://docs.rs/itertools/latest/itertools/
fn char_indexes2(text: &String) -> HashMap<char, Vec<usize>> {
text.chars()
.into_iter()
.zip(1..)
.filter(|&(c, _)| c.is_alphabetic())
.map(|(c, idx)| (c.to_ascii_lowercase(), idx))
.into_group_map()
}

#[test]
fn char_indexes_test() {
let s = String::from("Hello, world!");

let indexes1 = char_indexes(&s);
println!("{:?}", indexes1);

let indexes2 = char_indexes2(&s);
println!("{:?}", indexes2);

assert_eq!(indexes1, indexes2);
}
2 changes: 1 addition & 1 deletion src/practice/p14/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
mod char_coordinates;
mod char_indexes;
2 changes: 1 addition & 1 deletion src/practice/p15/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
mod permutations;
mod pack_unpack;
95 changes: 95 additions & 0 deletions src/practice/p15/pack_unpack.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// fold-left implementation
fn pack2<A: Clone + PartialEq>(xs: &Vec<A>) -> Vec<(A, usize)> {
let one = |a: &A| (a.clone(), 1);

xs.iter()
.fold(Vec::<(A, usize)>::with_capacity(xs.len()), |mut acc, a| {
match acc.last() {
// start
None => vec![one(a)],
// continue with the same element
Some((aa, c)) if a == aa => {
acc.last_mut()
.unwrap()
.1 = c + 1;
acc
}
// continue with the different element
Some(_) => {
acc.push(one(a));
acc
}
}
})
}

// iterator-based implementation
fn pack1<A: Clone + PartialEq>(xs: &Vec<A>) -> Vec<(A, usize)> {
let mut iter = xs.iter();
let mut cur: Option<(A, usize)> = None;
let mut acc = Vec::<(A, usize)>::new();

loop {
match (iter.next(), &cur) {
// finish with empty current
(None, None) => break acc,
// finish with non-empty current
(None, Some((v, count))) => {
acc.push((v.clone(), *count));
break acc;
}
// start
(Some(a), None) => cur = Some((a.clone(), 1)),
// continue with the same element
(Some(a), Some((v, count))) if a == v => cur = Some((a.clone(), count + 1)),
// continue with the different element
(Some(a), Some((v, count))) => {
acc.push((v.clone(), *count));
cur = Some((a.clone(), 1));
}
}
}
}

fn unpack<A: Clone + PartialEq>(xs: &Vec<(A, usize)>) -> Vec<A> {
xs.iter()
.flat_map(|&(ref a, ref count)| vec![a.clone(); *count])
.collect()
}

#[test]
fn pack_test() {
let test_cases: Vec<(&str, Vec<(char, usize)>)> = vec![
("", vec![]),
("a", vec![('a', 1)]),
("aa", vec![('a', 2)]),
("ab", vec![('a', 1), ('b', 1)]),
("aab", vec![('a', 2), ('b', 1)]),
("abb", vec![('a', 1), ('b', 2)]),
("abba", vec![('a', 1), ('b', 2), ('a', 1)]),
(
"abbcccaabc",
vec![('a', 1), ('b', 2), ('c', 3), ('a', 2), ('b', 1), ('c', 1)],
),
];

test_cases
.iter()
.for_each(|(s_unpacked, packed)| {
let unpacked = s_unpacked
.chars()
.collect::<Vec<_>>();

// pack V1
let packed2 = pack1(&unpacked);
assert_eq!(packed2, *packed);

// pack V2
let packed2 = pack2(&unpacked);
assert_eq!(packed2, *packed);

// unpack
let unpacked2 = unpack(&packed);
assert_eq!(unpacked2, unpacked);
});
}
Empty file removed src/practice/p15/permutations.rs
Empty file.
Loading

0 comments on commit 8859edb

Please sign in to comment.