Skip to content

Instantly share code, notes, and snippets.

@tallpeak
Last active September 1, 2023 07:32
Show Gist options
  • Save tallpeak/7d1af948a02489e0889baeaa6879b0d6 to your computer and use it in GitHub Desktop.
Save tallpeak/7d1af948a02489e0889baeaa6879b0d6 to your computer and use it in GitHub Desktop.
morse code decoder in Rust, converted from morse.py by ChatGPT 3.5, no errors!
use std::collections::HashMap;
fn main() {
let morse: Vec<&str> = vec![
" ", "-.-.--", ".-..-.", "", "...-..-", "", ".-...", ".----.", "-.--.", "-.--.-", "",
".-.-.", "--..--", "-....-", ".-.-.-", "-..-.", "-----", ".----", "..---", "...--",
"....-", ".....", "-....", "--...", "---..", "----.", "---...", "-.-.-.", "", "-...-",
"", "..--..", ".--.-.", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--..", "", "", "", "", "..--.-"
];
let mut ascii_value = 32;
let mut morse_ascii: HashMap<String, char> = HashMap::new();
for m in morse.iter() {
let ch = std::char::from_u32(ascii_value).unwrap();
if !m.is_empty() {
morse_ascii.insert(m.to_string(), ch);
}
ascii_value += 1;
}
// alternative to hashmap; use a bit encoding with a leading 1 bit:
fn encode_morse(m: &str) -> u8 {
let mut x = 1; // leading 1 bit
for c in m.chars() {
x <<= 1;
x += (c == '-') as i8;
}
// debugging:
// println!("{:8} => {:3} => {:9b}", m, x as u8, x);
return x as u8;
}
//equivalent: array or vec
//let mut morse_ascii_vec: Vec<u8> = vec![0; 256];
let mut morse_ascii_vec: [u8; 256] = [0;256];
ascii_value = 32;
for m in morse.iter() {
let x = encode_morse(m);
morse_ascii_vec[x as usize] = ascii_value as u8;
ascii_value += 1;
}
let message = "... --- ..."; // SOS
let mut decoded_message = String::new();
for w in message.split_whitespace() {
if let Some(ch) = morse_ascii.get(w) {
decoded_message.push(*ch);
}
}
println!("{}", decoded_message);
// alternate implementation uses a direct array
let mut decoded_message = String::new();
for w in message.split_whitespace() {
let ch = morse_ascii_vec[encode_morse(w) as usize];
decoded_message.push(ch as char);
}
println!("{}", decoded_message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment