Skip to content

Instantly share code, notes, and snippets.

@ssiegler
Created October 16, 2024 22:45
Show Gist options
  • Select an option

  • Save ssiegler/9833d2d7b14b3d8920c64b59d3530b42 to your computer and use it in GitHub Desktop.

Select an option

Save ssiegler/9833d2d7b14b3d8920c64b59d3530b42 to your computer and use it in GitHub Desktop.
Diamon Kata in Rust
pub fn diamond(c: char) -> String {
('A'..=c)
.chain(('A'..c).rev())
.map(|row| line(c, row))
.collect::<Vec<_>>()
.join("\n")
}
fn line(c: char, row: char) -> String {
('A'..=c)
.rev()
.chain('B'..=c)
.map(move |col| if row == col { row } else { ' ' })
.collect::<String>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn diamond_a() {
assert_eq!("A", diamond('A'));
}
#[test]
fn diamond_b() {
assert_eq!(
" A \
\nB B\
\n A ",
diamond('B')
);
}
#[test]
fn diamond_c() {
assert_eq!(
" A \
\n B B \
\nC C\
\n B B \
\n A ",
diamond('C')
);
}
#[test]
fn diamond_z() {
assert_eq!(
diamond('Z'),
" A \
\n B B \
\n C C \
\n D D \
\n E E \
\n F F \
\n G G \
\n H H \
\n I I \
\n J J \
\n K K \
\n L L \
\n M M \
\n N N \
\n O O \
\n P P \
\n Q Q \
\n R R \
\n S S \
\n T T \
\n U U \
\n V V \
\n W W \
\n X X \
\n Y Y \
\nZ Z\
\n Y Y \
\n X X \
\n W W \
\n V V \
\n U U \
\n T T \
\n S S \
\n R R \
\n Q Q \
\n P P \
\n O O \
\n N N \
\n M M \
\n L L \
\n K K \
\n J J \
\n I I \
\n H H \
\n G G \
\n F F \
\n E E \
\n D D \
\n C C \
\n B B \
\n A "
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment