Skip to content

Instantly share code, notes, and snippets.

@BlueZeeKing
Last active March 13, 2023 18:39
Show Gist options
  • Select an option

  • Save BlueZeeKing/c2bc8feaaf80da9f187026b427f98489 to your computer and use it in GitHub Desktop.

Select an option

Save BlueZeeKing/c2bc8feaaf80da9f187026b427f98489 to your computer and use it in GitHub Desktop.
Comp sci club challenge
fn main() {
println!("{}", how_many_in_common("january february march"));
}
fn how_many_in_common(input: &str) -> u32 {
let words = input.split(" ");
let mut combined = 0x3ffffff;
for word in words {
combined &= word_to_letters(word);
}
combined.count_ones()
}
fn word_to_letters(word: &str) -> u32 {
let mut response = 0u32;
for letter in word.chars().map(|letter| letter_to_index(letter)) {
response |= 1 << letter;
}
response
}
fn letter_to_index(char: char) -> u32 {
let letter = char as u32;
if letter <= 90 && letter >= 65 {
// capital letters
letter - 65
} else if letter <= 122 && letter >= 97 {
// lowercase letters
letter - 97
} else {
26
}
}
#[cfg(test)]
mod test {
use crate::{ how_many_in_common, letter_to_index, word_to_letters };
#[test]
fn main() {
assert_eq!(how_many_in_common("january february march"), 2);
assert_eq!(how_many_in_common("last"), 4);
assert_eq!(how_many_in_common("funny punny runny"), 3)
}
#[test]
fn letter() {
assert_eq!(letter_to_index('A'), 0);
assert_eq!(letter_to_index('a'), 0);
assert_eq!(letter_to_index('Z'), 25);
assert_eq!(letter_to_index('z'), 25);
assert_eq!(letter_to_index('-'), 26);
}
#[test]
fn word() {
assert_eq!(word_to_letters("abc"), 7);
assert_eq!(word_to_letters("za"), 0x2000001);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment