Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to find the most common pair of characters in a string with Rust

2 Answers

0 votes
use std::collections::HashMap;
 
fn main() {
    let s = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";
    
    let result = find_most_common_pair(s);
     
    println!("The most common pair: {:?}", result);
    println!("The most common pair: {:?}", result.as_ref().unwrap());
    println!("The most common pair: {:?}", result.unwrap());
}
 
fn find_most_common_pair(s: &str) -> Option<String> {
    let mut pair_count = HashMap::new();
     
    for i in 0..s.len() - 1 {
        let pair = &s[i..i + 2];
        *pair_count.entry(pair).or_insert(0) += 1;
    }
 
    let mut most_common_pair = None;
    let mut max_count = 0;
    for (pair, &count) in &pair_count {
        if count > max_count {
            most_common_pair = Some(pair.to_string());
            max_count = count;
        }
    }
     
    println!("Max count: {}", max_count);
 
    most_common_pair
}
 
 
  
  
/*
run:
 
Max count: 7
The most common pair: Some("xz")
The most common pair: "xz"
The most common pair: "xz"
 
*/
 

 



answered Nov 28, 2024 by avibootz
edited Nov 29, 2024 by avibootz
0 votes
use std::collections::HashMap;
 
fn main() {
    let s = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";
    
    let result = find_most_common_pair(s);
 
    println!("The most common pair: {:?}", result);
    println!("The most common pair: {:?}", result.as_ref().unwrap());
    println!("The most common pair: {:?}", result.unwrap());
}
 
fn find_most_common_pair(s: &str) -> Option<String> {
    let mut pair_counts = HashMap::new();
 
    for chars in s.chars().zip(s.chars().skip(1)) {
        let pair = format!("{}{}", chars.0, chars.1);
        *pair_counts.entry(pair).or_insert(0) += 1;
    }
 
    pair_counts
        .into_iter()
        .max_by_key(|(_, count)| *count)
        .map(|(pair, _)| pair)
}
 
  
  
/*
run:
 
The most common pair: Some("xz")
The most common pair: "xz"
The most common pair: "xz"
 
*/
 

 



answered Nov 28, 2024 by avibootz
edited Nov 29, 2024 by avibootz
...