Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active October 1, 2019 14:40
Show Gist options
  • Save lovasoa/b40679905f90b5fc180b5fbef84d2cb1 to your computer and use it in GitHub Desktop.
Save lovasoa/b40679905f90b5fc180b5fbef84d2cb1 to your computer and use it in GitHub Desktop.
Command-line utility that transcribes a number to the mayan numeral system. Written in rust.

maya.rs

Command-line utility that transcribes a number to the mayan numeral system. Other implementations

Usage

Compile the program with: rustc maya.rs. Then run ./maya 2017

Result

╔════╦════╦════╗
║    ║    ║ ●● ║
║    ║    ║————║
║    ║    ║————║
║————║ Θ  ║————║
╚════╩════╩════╝

(and indeed, 2017 = 5 x 20^2 + 0 x 20^1 + (3*5 + 2) x 20^0)

fn main() {
let arg = std::env::args().nth(1).map(|s| s.parse());
match arg {
Some(Ok(n)) => mayan_print(n),
_ => {
eprintln!("Usage:\n\tmaya NUMBER");
std::process::exit(1);
}
}
}
const ONES: [&str; 5] = ["", "●", "●●", "●●●", "●●●●"];
const FIVE: &str = "————";
const ZERO: &str = "Θ";
fn print_line<I: Iterator<Item = &'static str>>(
start: &str,
separator: &str,
end: &str,
components: I,
) {
print!("{}", start);
for (i, component) in components.enumerate() {
if i != 0 {
print!("{}", separator);
}
print!("{:^4}", component);
}
println!("{}", end);
}
fn mayan_decomposition(mut num: u64) -> Vec<(u8, u8)> {
let size = (64 - num.leading_zeros() as usize) / 4;
let mut parts = Vec::with_capacity(size);
while num > 0 {
let units = num % 5;
num -= units;
let fives = (num % 20) / 5;
num -= fives * 5;
num /= 20;
parts.push((units as u8, fives as u8));
}
parts.reverse();
parts
}
fn mayan_print(num: u64) {
let parts = mayan_decomposition(num);
let horiz_lines = std::iter::repeat("════").take(parts.len());
print_line("╔", "╦", "╗", horiz_lines.clone());
for i in (0..4).rev() {
print_line(
"║",
"║",
"║",
parts.iter().map(|&(units, fives)| {
if units == 0 && fives == 0 && i == 0 {
ZERO
} else if i < fives {
FIVE
} else if i == fives {
ONES[units as usize]
} else {
""
}
}),
);
}
print_line("╚", "╩", "╝", horiz_lines.clone());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment