Skip to content

Commit

Permalink
Replace unnecessary owned-type to borrowed-type (#525)
Browse files Browse the repository at this point in the history
  • Loading branch information
Watagon authored Sep 24, 2023
1 parent e6be8cc commit fea7725
Show file tree
Hide file tree
Showing 22 changed files with 116 additions and 189 deletions.
2 changes: 1 addition & 1 deletion src/data_structures/lazy_segment_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl<T: Debug + Default + Ord + Copy + Display + AddAssign + Add<Output = T>> La
return;
}

let lazy = self.lazy[idx].unwrap_or(T::default());
let lazy = self.lazy[idx].unwrap_or_default();
self.lazy[idx] = None;

let mid = (element_range.start + element_range.end) / 2;
Expand Down
6 changes: 3 additions & 3 deletions src/data_structures/rb_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ mod tests {
#[test]
fn find() {
let mut tree = RBTree::<usize, char>::new();
for (k, v) in String::from("hello, world!").chars().enumerate() {
for (k, v) in "hello, world!".chars().enumerate() {
tree.insert(k, v);
}
assert_eq!(*tree.find(&3).unwrap_or(&'*'), 'l');
Expand All @@ -628,7 +628,7 @@ mod tests {
#[test]
fn insert() {
let mut tree = RBTree::<usize, char>::new();
for (k, v) in String::from("hello, world!").chars().enumerate() {
for (k, v) in "hello, world!".chars().enumerate() {
tree.insert(k, v);
}
let s: String = tree.iter().map(|x| x.value).collect();
Expand All @@ -638,7 +638,7 @@ mod tests {
#[test]
fn delete() {
let mut tree = RBTree::<usize, char>::new();
for (k, v) in String::from("hello, world!").chars().enumerate() {
for (k, v) in "hello, world!".chars().enumerate() {
tree.insert(k, v);
}
tree.delete(&1);
Expand Down
2 changes: 1 addition & 1 deletion src/data_structures/trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ where
{
let mut node = &mut self.root;
for c in key.into_iter() {
node = node.children.entry(c).or_insert_with(Node::default);
node = node.children.entry(c).or_default();
}
node.value = Some(value);
}
Expand Down
6 changes: 3 additions & 3 deletions src/dynamic_programming/is_subsequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// by deleting some (can be none) of the characters without disturbing the relative
// positions of the remaining characters.
// (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
pub fn is_subsequence(str1: String, str2: String) -> bool {
pub fn is_subsequence(str1: &str, str2: &str) -> bool {
let mut it1 = 0;
let mut it2 = 0;

Expand All @@ -27,7 +27,7 @@ mod tests {

#[test]
fn test() {
assert!(is_subsequence(String::from("abc"), String::from("ahbgdc")));
assert!(!is_subsequence(String::from("axc"), String::from("ahbgdc")));
assert!(is_subsequence("abc", "ahbgdc"));
assert!(!is_subsequence("axc", "ahbgdc"));
}
}
52 changes: 11 additions & 41 deletions src/dynamic_programming/longest_common_substring.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Longest common substring via Dynamic Programming
// longest_common_substring(a, b) returns the length of longest common substring between the strings a and b.
pub fn longest_common_substring(text1: String, text2: String) -> i32 {
pub fn longest_common_substring(text1: &str, text2: &str) -> i32 {
let m = text1.len();
let n = text2.len();

Expand Down Expand Up @@ -32,74 +32,44 @@ mod tests {

#[test]
fn test1() {
assert_eq!(
longest_common_substring(String::from(""), String::from("")),
0
);
assert_eq!(longest_common_substring("", ""), 0);
}
#[test]
fn test2() {
assert_eq!(
longest_common_substring(String::from("a"), String::from("")),
0
);
assert_eq!(longest_common_substring("a", ""), 0);
}
#[test]
fn test3() {
assert_eq!(
longest_common_substring(String::from(""), String::from("a")),
0
);
assert_eq!(longest_common_substring("", "a"), 0);
}
#[test]
fn test4() {
assert_eq!(
longest_common_substring(String::from("a"), String::from("a")),
1
);
assert_eq!(longest_common_substring("a", "a"), 1);
}
#[test]
fn test5() {
assert_eq!(
longest_common_substring(String::from("abcdef"), String::from("bcd")),
3
);
assert_eq!(longest_common_substring("abcdef", "bcd"), 3);
}
#[test]
fn test6() {
assert_eq!(
longest_common_substring(String::from("abcdef"), String::from("xabded")),
2
);
assert_eq!(longest_common_substring("abcdef", "xabded"), 2);
}
#[test]
fn test7() {
assert_eq!(
longest_common_substring(String::from("GeeksforGeeks"), String::from("GeeksQuiz")),
5
);
assert_eq!(longest_common_substring("GeeksforGeeks", "GeeksQuiz"), 5);
}
#[test]
fn test8() {
assert_eq!(
longest_common_substring(String::from("abcdxyz"), String::from("xyzabcd")),
4
);
assert_eq!(longest_common_substring("abcdxyz", "xyzabcd"), 4);
}
#[test]
fn test9() {
assert_eq!(
longest_common_substring(String::from("zxabcdezy"), String::from("yzabcdezx")),
6
);
assert_eq!(longest_common_substring("zxabcdezy", "yzabcdezx"), 6);
}
#[test]
fn test10() {
assert_eq!(
longest_common_substring(
String::from("OldSite:GeeksforGeeks.org"),
String::from("NewSite:GeeksQuiz.com")
),
longest_common_substring("OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com"),
10
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/general/huffman_encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl<T> PartialEq for HuffmanNode<T> {

impl<T> PartialOrd for HuffmanNode<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.frequency.cmp(&other.frequency).reverse())
Some(self.cmp(other))
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/graph/astar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl<V: Ord + Copy, E: Ord + Copy> PartialOrd for Candidate<V, E> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
// Note the inverted order; we want nodes with lesser weight to have
// higher priority
other.estimated_weight.partial_cmp(&self.estimated_weight)
Some(self.cmp(other))
}
}

Expand Down Expand Up @@ -111,8 +111,8 @@ mod tests {
}

fn add_edge<V: Ord + Copy, E: Ord>(graph: &mut Graph<V, E>, v1: V, v2: V, c: E) {
graph.entry(v1).or_insert_with(BTreeMap::new).insert(v2, c);
graph.entry(v2).or_insert_with(BTreeMap::new);
graph.entry(v1).or_default().insert(v2, c);
graph.entry(v2).or_default();
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions src/graph/bellman_ford.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ mod tests {
use std::collections::BTreeMap;

fn add_edge<V: Ord + Copy, E: Ord>(graph: &mut Graph<V, E>, v1: V, v2: V, c: E) {
graph.entry(v1).or_insert_with(BTreeMap::new).insert(v2, c);
graph.entry(v2).or_insert_with(BTreeMap::new);
graph.entry(v1).or_default().insert(v2, c);
graph.entry(v2).or_default();
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions src/graph/dijkstra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ mod tests {
use std::collections::BTreeMap;

fn add_edge<V: Ord + Copy, E: Ord>(graph: &mut Graph<V, E>, v1: V, v2: V, c: E) {
graph.entry(v1).or_insert_with(BTreeMap::new).insert(v2, c);
graph.entry(v2).or_insert_with(BTreeMap::new);
graph.entry(v1).or_default().insert(v2, c);
graph.entry(v2).or_default();
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions src/graph/dinic_maxflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,8 @@ mod tests {
let max_flow = flow.find_maxflow(i32::MAX);
assert_eq!(max_flow, 23);

let mut sm_out = vec![0; 7];
let mut sm_in = vec![0; 7];
let mut sm_out = [0; 7];
let mut sm_in = [0; 7];

let flow_edges = flow.get_flow_edges(i32::MAX);
for e in flow_edges {
Expand Down
2 changes: 1 addition & 1 deletion src/graph/floyd_warshall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ mod tests {
use std::collections::BTreeMap;

fn add_edge<V: Ord + Copy, E: Ord + Copy>(graph: &mut Graph<V, E>, v1: V, v2: V, c: E) {
graph.entry(v1).or_insert_with(BTreeMap::new).insert(v2, c);
graph.entry(v1).or_default().insert(v2, c);
}

fn bi_add_edge<V: Ord + Copy, E: Ord + Copy>(graph: &mut Graph<V, E>, v1: V, v2: V, c: E) {
Expand Down
7 changes: 2 additions & 5 deletions src/graph/graph_enumeration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,8 @@ pub fn enumerate_graph<V: Ord + Clone>(adj: &Graph<V>) -> Vec<Vec<usize>> {
mod tests {
use super::*;
fn add_edge<V: Ord + Clone>(graph: &mut Graph<V>, a: V, b: V) {
graph
.entry(a.clone())
.or_insert_with(Vec::new)
.push(b.clone());
graph.entry(b).or_insert_with(Vec::new).push(a);
graph.entry(a.clone()).or_default().push(b.clone());
graph.entry(b).or_default().push(a);
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions src/graph/prim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use std::ops::Add;
type Graph<V, E> = BTreeMap<V, BTreeMap<V, E>>;

fn add_edge<V: Ord + Copy, E: Ord + Add + Copy>(graph: &mut Graph<V, E>, v1: V, v2: V, c: E) {
graph.entry(v1).or_insert_with(BTreeMap::new).insert(v2, c);
graph.entry(v2).or_insert_with(BTreeMap::new).insert(v1, c);
graph.entry(v1).or_default().insert(v2, c);
graph.entry(v2).or_default().insert(v1, c);
}

// selects a start and run the algorithm from it
Expand Down
3 changes: 1 addition & 2 deletions src/graph/prufer_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ pub fn prufer_encode<V: Ord + Copy>(tree: &Graph<V>) -> Vec<V> {
if tree.len() <= 2 {
return vec![];
}
let mut result: Vec<V> = Vec::new();
result.reserve(tree.len() - 2);
let mut result: Vec<V> = Vec::with_capacity(tree.len() - 2);
let mut queue = BinaryHeap::new();
let mut in_tree = BTreeSet::new();
let mut degree = BTreeMap::new();
Expand Down
2 changes: 1 addition & 1 deletion src/graph/topological_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub fn topological_sort<Node: Hash + Eq + Copy>(
incoming_edges_count.entry(*source).or_insert(0); // if we haven't seen this node yet, mark it as having 0 incoming nodes
edges_by_source // add destination to the list of outgoing edges from source
.entry(*source)
.or_insert_with(Vec::default)
.or_default()
.push(*destination);
// then make destination have one more incoming edge
*incoming_edges_count.entry(*destination).or_insert(0) += 1;
Expand Down
2 changes: 1 addition & 1 deletion src/math/fast_fourier_transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ mod tests {
let mut fft = fast_fourier_transform(&polynomial, &permutation);
fft.iter_mut().for_each(|num| *num *= *num);
let ifft = inverse_fast_fourier_transform(&fft, &permutation);
let expected = vec![1.0, 2.0, 1.0, 4.0, 4.0, 0.0, 4.0, 0.0, 0.0];
let expected = [1.0, 2.0, 1.0, 4.0, 4.0, 0.0, 4.0, 0.0, 0.0];
for (x, y) in ifft.iter().zip(expected.iter()) {
assert!(almost_equal(*x, *y, EPSILON));
}
Expand Down
28 changes: 12 additions & 16 deletions src/string/autocomplete_using_trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl Trie {
Trie(HashMap::new())
}

fn insert(&mut self, text: String) {
fn insert(&mut self, text: &str) {
let mut trie = self;

for c in text.chars().collect::<Vec<char>>() {
Expand All @@ -28,7 +28,7 @@ impl Trie {
trie.0.insert(END, Box::new(Trie::new()));
}

fn find(&self, prefix: String) -> Vec<String> {
fn find(&self, prefix: &str) -> Vec<String> {
let mut trie = self;

for c in prefix.chars().collect::<Vec<char>>() {
Expand All @@ -42,7 +42,7 @@ impl Trie {

Self::_elements(trie)
.iter()
.map(|s| prefix.clone() + s)
.map(|s| prefix.to_owned() + s)
.collect()
}

Expand Down Expand Up @@ -76,13 +76,13 @@ impl Autocomplete {
Self { trie: Trie::new() }
}

pub fn insert_words(&mut self, words: Vec<String>) {
pub fn insert_words<T: AsRef<str>>(&mut self, words: &[T]) {
for word in words {
self.trie.insert(word);
self.trie.insert(word.as_ref());
}
}

pub fn find_words(&self, prefix: String) -> Vec<String> {
pub fn find_words(&self, prefix: &str) -> Vec<String> {
self.trie.find(prefix)
}
}
Expand All @@ -99,28 +99,24 @@ mod tests {

#[test]
fn test_autocomplete() {
let words = vec![
"apple".to_owned(),
"orange".to_owned(),
"oregano".to_owned(),
];
let words = vec!["apple", "orange", "oregano"];

let mut auto_complete = Autocomplete::new();
auto_complete.insert_words(words);
auto_complete.insert_words(&words);

let prefix = "app".to_owned();
let prefix = "app";
let mut auto_completed_words = auto_complete.find_words(prefix);

let mut apple = vec!["apple".to_owned()];
let mut apple = vec!["apple"];
apple.sort();

auto_completed_words.sort();
assert_eq!(auto_completed_words, apple);

let prefix = "or".to_owned();
let prefix = "or";
let mut auto_completed_words = auto_complete.find_words(prefix);

let mut prefix_or = vec!["orange".to_owned(), "oregano".to_owned()];
let mut prefix_or = vec!["orange", "oregano"];
prefix_or.sort();

auto_completed_words.sort();
Expand Down
Loading

0 comments on commit fea7725

Please sign in to comment.