dsa_rust/algorithms/
list_processing.rs1pub mod recursion {
2 pub fn _recursion(n: i32) {
3 if n >= 10 {
5 _recursion(n / 10);
7 }
8 println!("{}", n % 10);
10 }
11}
12
13pub mod binary_search {
14 pub fn _binary_search(a: &[i32], key: i32) -> Option<i32> {
17 use std::cmp::Ordering;
18
19 let mut left = 0;
21 let mut right = a.len() - 1;
22
23 while left <= right {
27 let mid = (left + right) / 2;
28 match a[mid].cmp(&key) {
29 Ordering::Equal => return Some(mid as i32),
30 Ordering::Greater => right = mid - 1,
31 Ordering::Less => left = mid + 1,
32 }
33 println!("Guess index: {}", &mid);
45 }
46 None
47 }
48
49 #[test]
50 pub fn binary_search_test() {
51 let target = 73;
53 let array: [i32; 39] = [
54 1, 4, 5, 6, 10, 12, 16, 21, 23, 24, 25, 27, 31, 32, 33, 35, 37, 39, 40, 41, 42, 43, 45,
55 47, 49, 50, 51, 52, 54, 56, 57, 60, 61, 67, 70, 71, 72, 73, 74,
56 ];
57 let result = _binary_search(&array, target).unwrap_or_default();
58 assert_eq!(result, 37)
59 }
60}
61
62#[allow(dead_code)]
63pub mod substring_search {
64
65 struct Temp<T> {
66 elem: T,
67 }
68 impl<T> Temp<T> {
69 fn own(self) -> Self {
70 self
71 }
72 }
73 use std::collections::HashMap;
74
75 fn longest_unique_substring(s: &str) -> usize {
76 let mut map = HashMap::new(); let mut left = 0;
78 let mut max_len = 0;
79
80 let chars: Vec<char> = s.chars().collect();
81
82 for right in 0..chars.len() {
83 *map.entry(chars[right]).or_insert(0) += 1;
84
85 while map[&chars[right]] > 1 {
86 *map.get_mut(&chars[left]).unwrap() -= 1;
87 left += 1;
88 }
89
90 max_len = max_len.max(right - left + 1);
91 }
92
93 max_len
94 }
95
96 fn longest_unique_substring_print(s: &str) -> usize {
97 let mut map = HashMap::new();
98 let mut left = 0;
99 let mut max_len = 0;
100 let mut best_range = (0, 0); let chars: Vec<char> = s.chars().collect();
103
104 for right in 0..chars.len() {
105 *map.entry(chars[right]).or_insert(0) += 1;
106
107 while map[&chars[right]] > 1 {
108 *map.get_mut(&chars[left]).unwrap() -= 1;
109 left += 1;
110 }
111
112 let current_len = right - left + 1;
113 if current_len > max_len {
114 max_len = current_len;
115 best_range = (left, right);
116 }
117 }
118
119 let result: String = chars[best_range.0..=best_range.1].iter().collect();
121 println!("Longest substring found: \"{result}\" (length {max_len})");
122
123 max_len
124 }
125
126 #[test]
127 fn longest_unique_substring_test() {
128 let s = "this is a llama test.";
129 assert_eq!(longest_unique_substring(s), 6);
130 longest_unique_substring_print(s);
131 }
133}