Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
163 changes: 10 additions & 153 deletions solutions/diamond_creation/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,158 +1,15 @@
/* ## diamond_creation

### Instructions

Complete the function "make_diamond" that takes a letter as input, and outputs it in a diamond shape.

Rules:

- The first and last row contain one 'A'.
- The given letter has to be at the widest point.
- All rows, except the first and last, have exactly two identical letters.
- All rows have as many trailing spaces as leading spaces. (This might be 0).
- The diamond is vertically and horizontally symmetric.
- The diamond width equals the height.
- The top half has the letters in ascending order. (abcd)
- The bottom half has the letters in descending order. (dcba)

### Notions

- https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html

### Expected functions

```rust
fn get_diamond(c: char) -> Vec<String> {}
```

### Usage

Here is a program to test your function.

```rust
fn main() {
println!("{:?}", make_diamond('A'));
println!("{:?}", make_diamond('C'));
}
```

And its output

```console
student@ubuntu:~/[[ROOT]]/test$ cargo run
["A"]
[" A ", " B B ", "C C", " B B ", " A "]
student@ubuntu:~/[[ROOT]]/test$
```
*/
use std::iter;

pub fn get_diamond(c: char) -> Vec<String> {
let size = ((c as u8) - b'A') as usize * 2 + 1;

let half: Vec<_> = iter::once(format!("{0:^1$}", 'A', size))
.chain((1..=size / 2).map(|i| {
format!(
"{0:^1$}",
format!("{0}{1}{0}", (b'A' + i as u8) as char, " ".repeat(i * 2 - 1)),
size
)
}))
.collect();

half.iter()
.chain(half.iter().rev().skip(1))
.cloned()
.collect()
}

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

#[test]
fn test_a() {
assert_eq!(get_diamond('A'), vec!["A"]);
}

#[test]
fn test_b() {
assert_eq!(get_diamond('B'), vec![" A ", "B B", " A "]);
}
let n = ((c as u8 - b'A') * 2 + 1) as _;
let mid = (n + 1) / 2;

#[test]
fn test_c() {
assert_eq!(
get_diamond('C'),
vec![" A ", " B B ", "C C", " B B ", " A "]
);
}
let ladder = (0..mid).map(|i| {
let mut s = vec![' '; n];
let c = (b'A' + i as u8) as _;
s[mid - 1 - i] = c;
s[mid - 1 + i] = c;

#[test]
fn test_d() {
assert_eq!(
get_diamond('D'),
vec![" A ", " B B ", " C C ", "D D", " C C ", " B B ", " A ",]
);
}
String::from_iter(s)
});

#[test]
fn test_z() {
assert_eq!(
get_diamond('Z'),
vec![
" A ",
" B B ",
" C C ",
" D D ",
" E E ",
" F F ",
" G G ",
" H H ",
" I I ",
" J J ",
" K K ",
" L L ",
" M M ",
" N N ",
" O O ",
" P P ",
" Q Q ",
" R R ",
" S S ",
" T T ",
" U U ",
" V V ",
" W W ",
" X X ",
" Y Y ",
"Z Z",
" Y Y ",
" X X ",
" W W ",
" V V ",
" U U ",
" T T ",
" S S ",
" R R ",
" Q Q ",
" P P ",
" O O ",
" N N ",
" M M ",
" L L ",
" K K ",
" J J ",
" I I ",
" H H ",
" G G ",
" F F ",
" E E ",
" D D ",
" C C ",
" B B ",
" A ",
]
);
}
ladder.clone().chain(ladder.rev().skip(1)).collect()
}
41 changes: 20 additions & 21 deletions solutions/luhn_algorithm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
pub fn is_luhn_formula(code: &str) -> bool {
if code.trim().len() <= 1 {
return false;
let it = code.chars().filter(|c| !c.is_ascii_whitespace());
if it.clone().count() <= 1 {
false
} else {
it.rev()
.enumerate()
.try_fold(0, |acc, (i, c)| {
c.to_digit(10).map(|c| {
acc + if i % 2 == 1 {
if c > 4 {
c * 2 - 9
} else {
c * 2
}
} else {
c
}
})
})
.map_or(false, |n| n % 10 == 0)
}
code.as_bytes()
.iter()
.rev()
.filter(|&c| *c != b' ')
.enumerate()
.try_fold(0, |acc, (i, &c)| {
if c.is_ascii_digit() {
Some(
acc + match (i % 2 == 1, c - b'0') {
(true, nb) if nb > 4 => nb * 2 - 9,
(true, nb) => nb * 2,
(false, nb) => nb,
},
)
} else {
None
}
})
.map_or(false, |checksum| checksum % 10 == 0)
}
36 changes: 9 additions & 27 deletions solutions/ordinal/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,16 @@
/*
Complete the function "num_to_ordinal" that receives a cardinal number and returns its ordinal number.

fn main() {
println!("{}", num_to_ordinal(1));
println!("{}", num_to_ordinal(22));
println!("{}", num_to_ordinal(43));
println!("{}", num_to_ordinal(47));
}
*/

pub fn num_to_ordinal(x: u32) -> String {
format!(
"{}{}",
x,
match (x % 10, x % 100) {
(1, 1) | (1, 21..=91) => "st",
(2, 2) | (2, 22..=92) => "nd",
(3, 3) | (3, 23..=93) => "rd",
_ => "th",
if matches!(x % 100, 11..=13) {
"th"
} else {
match x % 10 {
1 => "st",
2 => "nd",
3 => "rd",
_ => "th",
}
}
)
}

#[test]
fn test_num_to_ordinal() {
assert_eq!(num_to_ordinal(0), "0th");
assert_eq!(num_to_ordinal(1), "1st");
assert_eq!(num_to_ordinal(12), "12th");
assert_eq!(num_to_ordinal(22), "22nd");
assert_eq!(num_to_ordinal(43), "43rd");
assert_eq!(num_to_ordinal(67), "67th");
assert_eq!(num_to_ordinal(1901), "1901st");
}
61 changes: 1 addition & 60 deletions solutions/pangram/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,62 +1,3 @@
// Determine if the string is a pangram.
// A pangram is a sentence using every letter of the alphabet at least once.
// The best known English pangram is: "The quick brown fox jumps over the lazy dog."

use std::collections::HashSet;

pub fn is_pangram(s: &str) -> bool {
let mut letters = HashSet::new();

for c in s.chars().map(|c| c.to_ascii_lowercase()) {
match c {
'a'..='z' => letters.insert(c),
_ => false,
};
if letters.len() == 26 {
return true;
}
}

false
}

// fn main() {
// println!(
// "{}",
// is_pangram("the quick brown fox jumps over the lazy dog!")
// );
// println!("{}", is_pangram("this is not a panagram!"));
// }

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

#[test]
fn test_empty_strings() {
assert!(!is_pangram(""));
assert!(!is_pangram(" "));
}

#[test]
fn test_is_panagram() {
assert!(is_pangram("the quick brown fox jumps over the lazy dog"));
assert!(is_pangram("the_quick_brown_fox_jumps_over_the_lazy_dog"));
assert!(is_pangram(
"the 1 quick brown fox jumps over the 2 lazy dogs"
));
}
#[test]
fn test_not_pangrams() {
assert!(!is_pangram(
"a quick movement of the enemy will jeopardize five gunboats"
));
assert!(!is_pangram("the quick brown fish jumps over the lazy dog"));
assert!(!is_pangram("the quick brown fox jumps over the lay dog"));
assert!(!is_pangram("7h3 qu1ck brown fox jumps ov3r 7h3 lazy dog"));
assert!(is_pangram("\"Five quacking Zephyrs jolt my wax bed.\""));
assert!(is_pangram(
"Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich."
));
}
('a'..='z').all(|c| s.to_lowercase().contains(c))
}
72 changes: 13 additions & 59 deletions solutions/pig_latin/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,63 +1,17 @@
pub fn pig_latin(text: &str) -> String {
text.split_whitespace()
.map(|s| {
let mut nb_chars_to_move = 0;
for c in s.chars() {
if !is_vowel(c) {
nb_chars_to_move += 1;
} else {
break;
}
}
if nb_chars_to_move >= 2
&& nb_chars_to_move < s.len()
&& s.chars().nth(nb_chars_to_move - 1) == Some('q')
&& s.chars().nth(nb_chars_to_move) == Some('u')
{
nb_chars_to_move += 1;
}
format!("{}{}ay", &s[nb_chars_to_move..], &s[0..nb_chars_to_move])
})
.collect::<Vec<String>>()
.join(" ")
}

fn is_vowel(mut c: char) -> bool {
c = lowercase(c);
c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
}
const VOWELS: &str = "aeiou";

fn lowercase(c: char) -> char {
c.to_lowercase().to_string().chars().next().unwrap()
}

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

#[test]
fn test_word_beginning_with_vowel() {
assert_eq!(pig_latin(&String::from("apple")), "appleay");
assert_eq!(pig_latin(&String::from("ear")), "earay");
assert_eq!(pig_latin(&String::from("igloo")), "iglooay");
assert_eq!(pig_latin(&String::from("object")), "objectay");
assert_eq!(pig_latin(&String::from("under")), "underay");
}
pub fn pig_latin(text: &str) -> String {
let first_vowel = text
.find(|c: char| VOWELS.contains(c.to_ascii_lowercase()))
.unwrap_or(text.len());

#[test]
let (start, rem) = text.split_at(
if first_vowel != 0 && text.len() >= 3 && &text[1..3] == "qu" {
3
} else {
first_vowel
},
);

fn test_word_beginning_with_consonant() {
assert_eq!(pig_latin(&String::from("queen")), "ueenqay");
assert_eq!(pig_latin(&String::from("square")), "aresquay");
assert_eq!(pig_latin(&String::from("equal")), "equalay");
assert_eq!(pig_latin(&String::from("pig")), "igpay");
assert_eq!(pig_latin(&String::from("koala")), "oalakay");
assert_eq!(pig_latin(&String::from("yellow")), "ellowyay");
assert_eq!(pig_latin(&String::from("xenon")), "enonxay");
assert_eq!(pig_latin(&String::from("qat")), "atqay");
assert_eq!(pig_latin(&String::from("chair")), "airchay");
assert_eq!(pig_latin(&String::from("therapy")), "erapythay");
assert_eq!(pig_latin(&String::from("thrush")), "ushthray");
assert_eq!(pig_latin(&String::from("school")), "oolschay");
}
format!("{rem}{start}ay")
}
Loading
Loading