Created
January 20, 2023 15:36
-
-
Save unfo/0bd0e30ee740dbb303d0782c41aeb2a1 to your computer and use it in GitHub Desktop.
Elias Gamma Encoding in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Wikipedia: https://en.wikipedia.org/wiki/Elias_gamma_coding | |
use std::vec; | |
use std::env; | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
if args.len() < 2 { | |
panic!("Please provide gamma-encoded binary string as input"); | |
} | |
let input = &args[1]; | |
let chars = input.chars(); | |
let mut selector = 0; | |
let mut nums: Vec<usize> = vec![]; | |
let mut it = chars.into_iter().peekable(); | |
while it.peek().is_some() { | |
if let Some(mut chr) = it.next() { | |
if chr == '0' { | |
selector += 1; | |
} else { | |
let mut num: usize = 0; | |
while selector >= 0 { | |
if chr == '1' { | |
num += 1 << selector; | |
} | |
selector -= 1; | |
if selector >= 0 { | |
chr = it.next().expect("Unexpected end of string"); | |
} | |
} | |
selector = 0; | |
nums.push(num); | |
} | |
} | |
} | |
println!("Input `{}`:", input); | |
for num in nums { | |
println!("- {}", num); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment