Skip to content

Commit a5a0f3b

Browse files
authored
Merge branch 'TheAlgorithms:master' into master
2 parents c1171c9 + b4aecf4 commit a5a0f3b

34 files changed

+94
-93
lines changed

Cargo.toml

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@ authors = ["Anshul Malik <[email protected]>"]
77
[dependencies]
88
num-bigint = { version = "0.4", optional = true }
99
num-traits = { version = "0.2", optional = true }
10-
rand = "0.8"
11-
rand_chacha = "0.3"
10+
rand = "0.9"
1211
nalgebra = "0.33.0"
1312

1413
[dev-dependencies]
@@ -25,14 +24,12 @@ restriction = "warn"
2524
nursery = "warn"
2625
cargo = "warn"
2726
# pedantic-lints:
28-
bool_to_int_with_if = { level = "allow", priority = 1 }
2927
cast_lossless = { level = "allow", priority = 1 }
3028
cast_possible_truncation = { level = "allow", priority = 1 }
3129
cast_possible_wrap = { level = "allow", priority = 1 }
3230
cast_precision_loss = { level = "allow", priority = 1 }
3331
cast_sign_loss = { level = "allow", priority = 1 }
3432
cloned_instead_of_copied = { level = "allow", priority = 1 }
35-
default_trait_access = { level = "allow", priority = 1 }
3633
doc_markdown = { level = "allow", priority = 1 }
3734
enum_glob_use = { level = "allow", priority = 1 }
3835
explicit_deref_methods = { level = "allow", priority = 1 }
@@ -49,15 +46,13 @@ manual_let_else = { level = "allow", priority = 1 }
4946
manual_string_new = { level = "allow", priority = 1 }
5047
many_single_char_names = { level = "allow", priority = 1 }
5148
match_on_vec_items = { level = "allow", priority = 1 }
52-
match_same_arms = { level = "allow", priority = 1 }
5349
match_wildcard_for_single_variants = { level = "allow", priority = 1 }
5450
missing_errors_doc = { level = "allow", priority = 1 }
5551
missing_fields_in_debug = { level = "allow", priority = 1 }
5652
missing_panics_doc = { level = "allow", priority = 1 }
5753
module_name_repetitions = { level = "allow", priority = 1 }
5854
must_use_candidate = { level = "allow", priority = 1 }
5955
needless_pass_by_value = { level = "allow", priority = 1 }
60-
range_plus_one = { level = "allow", priority = 1 }
6156
redundant_closure_for_method_calls = { level = "allow", priority = 1 }
6257
return_self_not_must_use = { level = "allow", priority = 1 }
6358
semicolon_if_nothing_returned = { level = "allow", priority = 1 }
@@ -145,6 +140,8 @@ cfg_not_test = { level = "allow", priority = 1 }
145140
field_scoped_visibility_modifiers = { level = "allow", priority = 1 }
146141
unused_trait_names = { level = "allow", priority = 1 }
147142
used_underscore_items = { level = "allow", priority = 1 }
143+
arbitrary_source_item_ordering = { level = "allow", priority = 1 }
144+
map_with_unused_argument_over_ranges = { level = "allow", priority = 1 }
148145
# nursery-lints:
149146
branches_sharing_code = { level = "allow", priority = 1 }
150147
cognitive_complexity = { level = "allow", priority = 1 }
@@ -167,3 +164,4 @@ doc_lazy_continuation = { level = "allow", priority = 1 }
167164
needless_return = { level = "allow", priority = 1 }
168165
# complexity-lints
169166
needless_lifetimes = { level = "allow", priority = 1 }
167+
precedence = { level = "allow", priority = 1 }

clippy.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
allowed-duplicate-crates = [
2+
"zerocopy",
3+
"zerocopy-derive",
4+
]

src/ciphers/transposition.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
//! original message. The most commonly referred to Transposition Cipher is the
66
//! COLUMNAR TRANSPOSITION cipher, which is demonstrated below.
77
8-
use std::ops::Range;
8+
use std::ops::RangeInclusive;
99

1010
/// Encrypts or decrypts a message, using multiple keys. The
1111
/// encryption is based on the columnar transposition method.
@@ -142,8 +142,8 @@ fn decrypt(mut msg: String, key_order: Vec<usize>) -> String {
142142

143143
split_large.iter_mut().rev().for_each(|key_index| {
144144
counter -= 1;
145-
let range: Range<usize> =
146-
((*key_index * split_size) + counter)..(((*key_index + 1) * split_size) + counter + 1);
145+
let range: RangeInclusive<usize> =
146+
((*key_index * split_size) + counter)..=(((*key_index + 1) * split_size) + counter);
147147

148148
let slice: String = msg[range.clone()].to_string();
149149
indexed_vec.push((*key_index, slice));

src/data_structures/hash_table.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ mod tests {
9393
let mut hash_table = HashTable::new();
9494
let initial_capacity = hash_table.elements.capacity();
9595

96-
for i in 0..initial_capacity * 3 / 4 + 1 {
96+
for i in 0..=initial_capacity * 3 / 4 {
9797
hash_table.insert(TestKey(i), TestKey(i + 10));
9898
}
9999

src/data_structures/lazy_segment_tree.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,10 @@ mod tests {
235235
fn check_single_interval_min(array: Vec<i32>) -> TestResult {
236236
let mut seg_tree = LazySegmentTree::from_vec(&array, min);
237237
for (i, value) in array.into_iter().enumerate() {
238-
let res = seg_tree.query(i..(i + 1));
238+
let res = seg_tree.query(Range {
239+
start: i,
240+
end: i + 1,
241+
});
239242
if res != Some(value) {
240243
return TestResult::error(format!("Expected {:?}, got {:?}", Some(value), res));
241244
}
@@ -247,7 +250,10 @@ mod tests {
247250
fn check_single_interval_max(array: Vec<i32>) -> TestResult {
248251
let mut seg_tree = LazySegmentTree::from_vec(&array, max);
249252
for (i, value) in array.into_iter().enumerate() {
250-
let res = seg_tree.query(i..(i + 1));
253+
let res = seg_tree.query(Range {
254+
start: i,
255+
end: i + 1,
256+
});
251257
if res != Some(value) {
252258
return TestResult::error(format!("Expected {:?}, got {:?}", Some(value), res));
253259
}
@@ -259,7 +265,10 @@ mod tests {
259265
fn check_single_interval_sum(array: Vec<i32>) -> TestResult {
260266
let mut seg_tree = LazySegmentTree::from_vec(&array, max);
261267
for (i, value) in array.into_iter().enumerate() {
262-
let res = seg_tree.query(i..(i + 1));
268+
let res = seg_tree.query(Range {
269+
start: i,
270+
end: i + 1,
271+
});
263272
if res != Some(value) {
264273
return TestResult::error(format!("Expected {:?}, got {:?}", Some(value), res));
265274
}

src/data_structures/probabilistic/bloom_filter.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ pub struct MultiBinaryBloomFilter {
108108

109109
impl MultiBinaryBloomFilter {
110110
pub fn with_dimensions(filter_size: usize, hash_count: usize) -> Self {
111-
let bytes_count = filter_size / 8 + if filter_size % 8 > 0 { 1 } else { 0 }; // we need 8 times less entries in the array, since we are using bytes. Careful that we have at least one element though
111+
let bytes_count = filter_size / 8 + usize::from(filter_size % 8 > 0); // we need 8 times less entries in the array, since we are using bytes. Careful that we have at least one element though
112112
Self {
113113
filter_size,
114114
bytes: vec![0; bytes_count],

src/data_structures/probabilistic/count_min_sketch.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ impl<T: Hash, const WIDTH: usize, const DEPTH: usize> Default
109109
let hashers = std::array::from_fn(|_| RandomState::new());
110110

111111
Self {
112-
phantom: Default::default(),
112+
phantom: std::marker::PhantomData,
113113
counts: [[0; WIDTH]; DEPTH],
114114
hashers,
115115
}

src/data_structures/veb_tree.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -322,21 +322,21 @@ mod test {
322322
#[test]
323323
fn test_10_256() {
324324
let mut rng = StdRng::seed_from_u64(0);
325-
let elements: Vec<u32> = (0..10).map(|_| rng.gen_range(0..255)).collect();
325+
let elements: Vec<u32> = (0..10).map(|_| rng.random_range(0..255)).collect();
326326
test_veb_tree(256, elements, Vec::new());
327327
}
328328

329329
#[test]
330330
fn test_100_256() {
331331
let mut rng = StdRng::seed_from_u64(0);
332-
let elements: Vec<u32> = (0..100).map(|_| rng.gen_range(0..255)).collect();
332+
let elements: Vec<u32> = (0..100).map(|_| rng.random_range(0..255)).collect();
333333
test_veb_tree(256, elements, Vec::new());
334334
}
335335

336336
#[test]
337337
fn test_100_300() {
338338
let mut rng = StdRng::seed_from_u64(0);
339-
let elements: Vec<u32> = (0..100).map(|_| rng.gen_range(0..255)).collect();
339+
let elements: Vec<u32> = (0..100).map(|_| rng.random_range(0..255)).collect();
340340
test_veb_tree(300, elements, Vec::new());
341341
}
342342
}

src/dynamic_programming/fibonacci.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ fn get_pisano_sequence_and_period(m: i64) -> (i128, Vec<i128>) {
226226
let mut pisano_sequence: Vec<i128> = vec![a, b];
227227

228228
// Iterating through all the fib numbers to get the sequence
229-
for _i in 0..(m * m) + 1 {
229+
for _i in 0..=(m * m) {
230230
let c = (a + b) % m as i128;
231231

232232
// adding number into the sequence

src/general/genetic.rs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ impl<Rng: rand::Rng> SelectionStrategy<Rng> for RouletteWheel<Rng> {
6868
return (parents[0], parents[1]);
6969
}
7070
let sum: f64 = fitnesses.iter().sum();
71-
let mut spin = self.rng.gen_range(0.0..=sum);
71+
let mut spin = self.rng.random_range(0.0..=sum);
7272
for individual in population {
7373
let fitness: f64 = individual.fitness().into();
7474
if spin <= fitness {
@@ -104,7 +104,7 @@ impl<const K: usize, Rng: rand::Rng> SelectionStrategy<Rng> for Tournament<K, Rn
104104
// This means we can draw K random (distinct) numbers between (0..population.len()) and return the chromosomes at the 2 lowest indices
105105
let mut picked_indices = BTreeSet::new(); // will keep indices ordered
106106
while picked_indices.len() < K {
107-
picked_indices.insert(self.rng.gen_range(0..population.len()));
107+
picked_indices.insert(self.rng.random_range(0..population.len()));
108108
}
109109
let mut iter = picked_indices.into_iter();
110110
(
@@ -185,15 +185,15 @@ impl<
185185

186186
// 3. Apply random mutations to the whole population
187187
for chromosome in self.population.iter_mut() {
188-
if self.rng.gen::<f64>() <= self.mutation_chance {
188+
if self.rng.random::<f64>() <= self.mutation_chance {
189189
chromosome.mutate(&mut self.rng);
190190
}
191191
}
192192
// 4. Select parents that will be mating to create new chromosomes
193193
let mut new_population = Vec::with_capacity(self.population.len() + 1);
194194
while new_population.len() < self.population.len() {
195195
let (p1, p2) = self.selection.select(&self.population);
196-
if self.rng.gen::<f64>() <= self.crossover_chance {
196+
if self.rng.random::<f64>() <= self.crossover_chance {
197197
let child = p1.crossover(p2, &mut self.rng);
198198
new_population.push(child);
199199
} else {
@@ -220,7 +220,7 @@ mod tests {
220220
Tournament,
221221
};
222222
use rand::rngs::ThreadRng;
223-
use rand::{thread_rng, Rng};
223+
use rand::{rng, Rng};
224224
use std::collections::HashMap;
225225
use std::fmt::{Debug, Formatter};
226226
use std::ops::RangeInclusive;
@@ -240,7 +240,7 @@ mod tests {
240240
impl TestString {
241241
fn new(rng: &mut ThreadRng, secret: String, chars: RangeInclusive<char>) -> Self {
242242
let current = (0..secret.len())
243-
.map(|_| rng.gen_range(chars.clone()))
243+
.map(|_| rng.random_range(chars.clone()))
244244
.collect::<Vec<_>>();
245245

246246
Self {
@@ -258,16 +258,16 @@ mod tests {
258258
impl Chromosome<ThreadRng, i32> for TestString {
259259
fn mutate(&mut self, rng: &mut ThreadRng) {
260260
// let's assume mutations happen completely randomly, one "gene" at a time (i.e. one char at a time)
261-
let gene_idx = rng.gen_range(0..self.secret.len());
262-
let new_char = rng.gen_range(self.chars.clone());
261+
let gene_idx = rng.random_range(0..self.secret.len());
262+
let new_char = rng.random_range(self.chars.clone());
263263
self.genes[gene_idx] = new_char;
264264
}
265265

266266
fn crossover(&self, other: &Self, rng: &mut ThreadRng) -> Self {
267267
// Let's not assume anything here, simply mixing random genes from both parents
268268
let genes = (0..self.secret.len())
269269
.map(|idx| {
270-
if rng.gen_bool(0.5) {
270+
if rng.random_bool(0.5) {
271271
// pick gene from self
272272
self.genes[idx]
273273
} else {
@@ -292,7 +292,7 @@ mod tests {
292292
.count() as i32
293293
}
294294
}
295-
let mut rng = thread_rng();
295+
let mut rng = rng();
296296
let pop_count = 1_000;
297297
let mut population = Vec::with_capacity(pop_count);
298298
for _ in 0..pop_count {
@@ -388,7 +388,7 @@ mod tests {
388388
}
389389
}
390390
fn random_color(rng: &mut ThreadRng) -> ColoredPeg {
391-
match rng.gen_range(0..=5) {
391+
match rng.random_range(0..=5) {
392392
0 => ColoredPeg::Red,
393393
1 => ColoredPeg::Yellow,
394394
2 => ColoredPeg::Green,
@@ -403,15 +403,15 @@ mod tests {
403403
impl Chromosome<ThreadRng, i32> for CodeBreaker {
404404
fn mutate(&mut self, rng: &mut ThreadRng) {
405405
// change one random color
406-
let idx = rng.gen_range(0..4);
406+
let idx = rng.random_range(0..4);
407407
self.guess[idx] = random_color(rng);
408408
}
409409

410410
fn crossover(&self, other: &Self, rng: &mut ThreadRng) -> Self {
411411
Self {
412412
maker: self.maker.clone(),
413413
guess: std::array::from_fn(|i| {
414-
if rng.gen::<f64>() < 0.5 {
414+
if rng.random::<f64>() < 0.5 {
415415
self.guess[i]
416416
} else {
417417
other.guess[i]
@@ -443,7 +443,7 @@ mod tests {
443443
mutation_chance: 0.5,
444444
crossover_chance: 0.3,
445445
};
446-
let mut rng = thread_rng();
446+
let mut rng = rng();
447447
let mut initial_pop = Vec::with_capacity(population_count);
448448
for _ in 0..population_count {
449449
initial_pop.push(CodeBreaker {

0 commit comments

Comments
 (0)