Move History

Fork Selected
  • Description

    Correction pour agir comme la question originale decrit.

    Code
    fn closest_to_zero(ints: &[i32]) -> i32 {
        *ints.iter().min_by_key(|x| (x.abs(), x.is_negative())).unwrap_or(&0)
    }
    
    Test Cases
    #[cfg(test)]
    mod tests {
        use super::*;
        
        #[test]
        fn test_simple() {
            assert_eq!(closest_to_zero(&[7, 5, 9, 1, 4]), 1);
        }
        
        #[test]
        fn test_negative() {
            assert_eq!(closest_to_zero(&[7, -4, -3, -12, 5, 9, -2, 4]), -2);
        }
        
        #[test]
        fn test_same() {
            assert_eq!(closest_to_zero(&[-5, -5]), -5);
        }
        
        #[test]
        fn test_empty() {
            assert_eq!(closest_to_zero(&[]), 0);
        }
        
        #[test]
        fn test_with_zero() {
            assert_eq!(closest_to_zero(&[-5, 0, 1, 5]), 0);
        }
        
        #[test]
        fn test_same_distance() {
            assert_eq!(closest_to_zero(&[-5, -1, 1, 5]), 1);
        }
    }
    
  • Code
    • fn closest_to_zero(ints: &[i32]) -> i32 {
    • *ints.iter().min_by_key(|x| x.abs()).unwrap_or(&0)
    • *ints.iter().min_by_key(|x| (x.abs(), x.is_negative())).unwrap_or(&0)
    • }
    Test Cases
    • #[cfg(test)]
    • mod tests {
    • use super::*;
    • #[test]
    • fn test_simple() {
    • assert_eq!(closest_to_zero(&[7, 5, 9, 1, 4]), 1);
    • }
    • #[test]
    • fn test_negative() {
    • assert_eq!(closest_to_zero(&[7, -4, -3, -12, 5, 9, -2, 4]), -2);
    • }
    • #[test]
    • fn test_same() {
    • assert_eq!(closest_to_zero(&[-5, -5]), -5);
    • }
    • #[test]
    • fn test_empty() {
    • assert_eq!(closest_to_zero(&[]), 0);
    • }
    • #[test]
    • fn test_with_zero() {
    • assert_eq!(closest_to_zero(&[-5, 0, 1, 5]), 0);
    • }
    • #[test]
    • fn test_same_distance() {
    • assert_eq!(closest_to_zero(&[-5, -1, 1, 5]), -1);
    • assert_eq!(closest_to_zero(&[-5, -1, 1, 5]), 1);
    • }
    • }