Rust learning: lessons, notes, and exercise crates
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/target
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "learn-challenges"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "learn-challenges"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::{collections::HashMap, vec};
|
||||
|
||||
fn main() {
|
||||
let list = vec![3, 1, 4, 1, 5];
|
||||
|
||||
let med: usize = list.len() / 2;
|
||||
|
||||
println!("this is the median {}", list.get(med).unwrap_or(&0));
|
||||
|
||||
let mut count = HashMap::new();
|
||||
|
||||
for &v in &list {
|
||||
let x = count.entry(v).or_insert(0);
|
||||
*x += 1;
|
||||
}
|
||||
|
||||
let mut mode = 0;
|
||||
let mut max_count = 0;
|
||||
|
||||
for (k, v) in &count {
|
||||
if *v > max_count {
|
||||
max_count = *v;
|
||||
mode = *k;
|
||||
}
|
||||
}
|
||||
|
||||
println!("this is the mode {}", mode);
|
||||
|
||||
let latin = "apple banana".to_string();
|
||||
|
||||
println!("{latin} = this is the pig latin: {}", pig_latin(&latin));
|
||||
|
||||
let latin = "kdlkjlkdsgjh gkjldgjd".to_string();
|
||||
|
||||
println!("{latin} = this is the pig latin: {}", pig_latin(&latin));
|
||||
}
|
||||
|
||||
fn pig_latin(s: &String) -> String {
|
||||
let mut results_words: Vec<String> = Vec::new();
|
||||
|
||||
for word in s.split_whitespace() {
|
||||
let mut vowel_idx = None;
|
||||
for (i, v) in word.char_indices() {
|
||||
match v {
|
||||
'a' | 'i' | 'e' | 'u' | 'o' => {
|
||||
vowel_idx = Some(i);
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let transformed = match vowel_idx {
|
||||
Some(0) => format!("{}-hay", word),
|
||||
Some(idx) => {
|
||||
let x = &word[..idx];
|
||||
let rmdr = &word[idx..];
|
||||
format!("{rmdr}-{x}ay")
|
||||
}
|
||||
None => word.to_string(),
|
||||
};
|
||||
results_words.push(transformed);
|
||||
}
|
||||
|
||||
results_words.join(" ")
|
||||
}
|
||||
Reference in New Issue
Block a user