-
Notifications
You must be signed in to change notification settings - Fork 0
/
tricks
65 lines (54 loc) · 2.07 KB
/
tricks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
- using split() with multiple characters => split(&['-', "-"])
- Convert IP address str: ip.split(".").map(|x| x.parse::<u8>().unwrap()).fold(0, |acc, byte| (acc << 8) + byte as u32)
- Ranges in rust:
1..2; // std::ops::Range
3..; // std::ops::RangeFrom
..4; // std::ops::RangeTo
..; // std::ops::RangeFull
5..=6; // std::ops::RangeInclusive
..=7; // std::ops::RangeToInclusive
- (1..=gcd)
.find(|x| l.iter().all(|(number, denom)| (number * x) % denom == 0))
.unwrap();
- s.chars().filter(|c| if "aeiou".contains(c.to_ascii_lowercase()) {false} else {true})
.collect();
- for i in 3..n {
let sum = &res[i - 3..i].iter().sum(); -> taking a certain slice of a vec
res.push(*sum);
}
- ref keyword
fn main() {
let maybe_name = Some(String::from("Alice"));
// Using `ref`, the value is borrowed, not moved ...
match maybe_name {
Some(ref n) => println!("Hello, {n}"),
_ => println!("Hello, world"),
}
// ... so it's available here!
// Without ref this wouldn't be possible!
println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
}
- nice solution:
fn order_weight(s: &str) -> String {
let mut numbers = s.split_whitespace().collect::<Vec<_>>();
numbers.sort();
numbers.sort_by_key(|s| s.chars().flat_map(|c| c.to_digit(10)).sum::<u32>());
numbers.join(" ")
}
* difference between map and flat_map is flat_map flattens nested structure:
let words = ["alpha", "beta", "gamma"];
// chars() returns an iterator
let merged: String = words.iter()
.flat_map(|s| s.chars())
.collect();
assert_eq!(merged, "alphabetagamma");
- when printing with zero's (e.g. 23:01:04):
res = 1;
format!("{res:02}");
- Using enumerate without for loop and repeat() and join():
fn accum(s:&str)->String {
s.chars().enumerate()
.map(|(i,c)|c.to_string().to_uppercase() + c.to_string().to_lowercase().repeat(i).as_str())
.collect::<Vec<String>>()
.join("-")
}