Skip to content

Commit

Permalink
Add problem 2306: Naming a Company
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 18, 2024
1 parent cb7d84d commit 4e3899e
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1717,6 +1717,7 @@ pub mod problem_2302_count_subarrays_with_score_less_than_k;
pub mod problem_2303_calculate_amount_paid_in_taxes;
pub mod problem_2304_minimum_path_cost_in_a_grid;
pub mod problem_2305_fair_distribution_of_cookies;
pub mod problem_2306_naming_a_company;
pub mod problem_2309_greatest_english_letter_in_upper_and_lower_case;
pub mod problem_2310_sum_of_numbers_with_units_digit_k;
pub mod problem_2315_count_asterisks;
Expand Down
50 changes: 50 additions & 0 deletions src/problem_2306_naming_a_company/group_by_prefix.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::collections::HashSet;

impl Solution {
pub fn distinct_names(ideas: Vec<String>) -> i64 {
let mut groups = [(); 26].map(|()| HashSet::<u64>::new());

for idea in ideas {
let mut iter = idea.bytes();
let prefix = usize::from(iter.next().unwrap());
let suffix = iter.fold(0, |result, c| (result << 7) | u64::from(c));

groups[prefix - usize::from(b'a')].insert(suffix);
}

let mut result = 0;
let mut iter = groups.iter();

while let Some(left) = iter.next() {
if !left.is_empty() {
iter.clone().for_each(|right| {
let intersections = left.intersection(right).count();

result += (left.len() - intersections) * (right.len() - intersections);
});
}
}

(result * 2) as _
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn distinct_names(ideas: Vec<String>) -> i64 {
Self::distinct_names(ideas)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
24 changes: 24 additions & 0 deletions src/problem_2306_naming_a_company/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
pub mod group_by_prefix;

pub trait Solution {
fn distinct_names(ideas: Vec<String>) -> i64;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
(&["coffee", "donuts", "time", "toffee"] as &[_], 6),
(&["lack", "back"], 0),
];

for (ideas, expected) in test_cases {
assert_eq!(
S::distinct_names(ideas.iter().copied().map(str::to_string).collect()),
expected,
);
}
}
}

0 comments on commit 4e3899e

Please sign in to comment.