From 1945a07426f6f7f6b3052df3a088c273304c5a01 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 30 Aug 2024 11:28:00 +0800 Subject: [PATCH] 20240830 finished. --- src/problem/mod.rs | 3 +- ...3_sum_of_digit_differences_of_all_pairs.rs | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 src/problem/p3153_sum_of_digit_differences_of_all_pairs.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 73837e4..53e765c 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -219,4 +219,5 @@ mod p3146_permutation_difference_between_two_strings; mod p698_partition_to_k_equal_sum_subsets; mod p3134_find_the_median_of_the_uniqueness_array; mod p3144_minimum_substring_partition_of_equal_character_frequency; -mod p3142_check_if_grid_satisfies_conditions; \ No newline at end of file +mod p3142_check_if_grid_satisfies_conditions; +mod p3153_sum_of_digit_differences_of_all_pairs; \ No newline at end of file diff --git a/src/problem/p3153_sum_of_digit_differences_of_all_pairs.rs b/src/problem/p3153_sum_of_digit_differences_of_all_pairs.rs new file mode 100644 index 0000000..c8a8c21 --- /dev/null +++ b/src/problem/p3153_sum_of_digit_differences_of_all_pairs.rs @@ -0,0 +1,50 @@ +/** + * [3153] Sum of Digit Differences of All Pairs + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn sum_digit_differences(nums: Vec) -> i64 { + let n = nums.len() as i64; + let mut result = 0; + + let mut base = 1; + loop { + if nums[0] / base == 0 { + break; + } + + let mut map = vec![0; 10]; + for &num in nums.iter() { + let digit = (num / base % 10) as usize; + map[digit] += 1; + } + + result += map.iter().filter_map(|x| if *x == 0 { + None + } else { + Some(*x * (n - *x)) + }).sum::() / 2; + + base *= 10; + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3153() { + assert_eq!(4, Solution::sum_digit_differences(vec![13, 23, 12])); + assert_eq!(0, Solution::sum_digit_differences(vec![10, 10, 10, 10])); + } +}