1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/rs/the-number-of-weak-characters-in-the-game.rs
Matej Focko 2351dfd0ee
chore: unwrap one layer
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-12 14:36:00 +01:00

125 lines
2.6 KiB
Rust

#[derive(Debug, PartialEq, Eq)]
struct Property {
attack: i32,
defense: i32,
}
impl Property {
fn is_weak(&self, rhs: &Property) -> bool {
self.attack < rhs.attack && self.defense < rhs.defense
}
}
impl From<&Vec<i32>> for Property {
fn from(v: &Vec<i32>) -> Self {
Self {
attack: v[0],
defense: v[1],
}
}
}
impl PartialOrd for Property {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
match self.attack.partial_cmp(&other.attack) {
Some(core::cmp::Ordering::Equal) => other.defense.partial_cmp(&self.defense),
ord => ord,
}
}
}
impl Ord for Property {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
if self.attack != other.attack {
self.attack.cmp(&other.attack)
} else {
other.defense.cmp(&self.defense)
}
}
}
struct Acc {
max: i32,
count: i32,
}
impl Acc {
fn new(m: i32) -> Acc {
Acc { max: m, count: 0 }
}
fn update(self, p: &Property) -> Acc {
if p.defense < self.max {
Acc {
max: self.max,
count: self.count + 1,
}
} else {
Acc {
max: p.defense,
count: self.count,
}
}
}
}
impl Solution {
pub fn number_of_weak_characters(properties: Vec<Vec<i32>>) -> i32 {
let mut properties: Vec<Property> = properties.iter().map(From::from).collect();
properties.sort();
properties
.iter()
.rfold(Acc::new(properties.last().unwrap().defense), Acc::update)
.count
}
}
struct Solution {}
fn main() {
println!("Hello World!");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_example() {
assert_eq!(
Solution::number_of_weak_characters(vec![vec![5, 5], vec![6, 3], vec![3, 6]]),
0
);
}
#[test]
fn test_another_example() {
assert_eq!(
Solution::number_of_weak_characters(vec![vec![2, 2], vec![3, 3]]),
1
);
}
#[test]
fn test_another_another_example() {
assert_eq!(
Solution::number_of_weak_characters(vec![vec![1, 5], vec![10, 4], vec![4, 3]]),
1
);
}
#[test]
fn test_bigger_example() {
assert_eq!(
Solution::number_of_weak_characters(vec![
vec![1, 5],
vec![10, 4],
vec![4, 3],
vec![2, 6],
vec![1, 1],
vec![10, 6]
]),
3
);
}
}