Skip to content

Instantly share code, notes, and snippets.

@tallpeak
Last active March 9, 2023 21:51
Show Gist options
  • Save tallpeak/2cd8432d3251ff3f8fe394acd49fcade to your computer and use it in GitHub Desktop.
Save tallpeak/2cd8432d3251ff3f8fe394acd49fcade to your computer and use it in GitHub Desktop.
8-bit character frequency, converted from C to Rust by ChatGPT, with minor corrections at msot.
// The result of using ChatGPT to convert my C character-frequency program to Rust
// Surprisingly, this program was correctly converted by ChatGPT!
// My only change was to the "=======" header, which it printed double-length;
// a strange mistake, but very minor.
use std::io::{self, Read};
fn main() {
let mut buffer = [0; 256];
let mut freq = [0; 256];
println!("Top hex digits are the second digit of the character value\nLeft-side hex numbers are the first digit of the character value\nnumbers in the table are the frequence of each character found in stdin.");
while let Ok(size) = io::stdin().read(&mut buffer) {
if size == 0 {
break;
}
for i in 0..size {
freq[buffer[i] as usize] += 1;
}
}
// header: upper hex digits of the character value
print!(" ");
for h in 0..16 {
print!("{:6x} ", h);
}
// header-separator lines
let l = "=======";
print!("\n ");
for _ in 0..16 {
print!("{}", l); // chatGPT said print!("{}{}, l, l);
}
for c in 0..=255 {
if c % 16 == 0 {
print!("\n{:02x}: ", c);
}
print!("{:7}", freq[c]);
}
println!();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment