Enhance this code massively. Rules: ( one main.rs file nothing else, no TCH )
use std::collections::HashMap;
use std::env;
use std::fs;
use rand::seq::SliceRandom;
fn main() {
// Get input arguments
let args: Vec = env::args().collect();
if args.len() != 4 {
println!(
"Usage: {} <input_file> <prefix_length> <output_length>",
args[0]
);
return;
}
let filename = &args[1];
let prefix_length: usize = args[2].parse().expect("Prefix length must be a number");
let output_length: usize = args[3].parse().expect("Output length must be a number");
code
// Read the input file
let contents = fs::read_to_string(filename).expect("Something went wrong reading the file");
// Split the contents into words
let words: Vec<&str> = contents.split_whitespace().collect();
// Build the Markov chain
let chain = build_markov_chain(&words, prefix_length);
// Generate text
let generated_text = generate_text(&chain, prefix_length, output_length);
// Print the generated text
println!("{}", generated_text);
let mut rng = rand::thread_rng();
// Randomly pick a starting prefix
let mut prefix = chain
.keys()
.choose(&mut rng)
.expect("Cannot find a starting prefix")
.to_owned();
let mut result = prefix.clone();
for _ in 0..output_length {
if let Some(suffixes) = chain.get(&prefix) {
let next_word = suffixes
.choose(&mut rng)
.expect("No suffixes found")
.to_string();
result.push(next_word.clone());
// Move the prefix window
prefix.remove(0);
prefix.push(next_word);
} else {
// Cannot find the next word, randomly pick a new prefix
prefix = chain
.keys()
.choose(&mut rng)
.expect("Cannot find a new prefix")
.to_owned();
}
}
result.join(" ")
}
Here is an enhanced version of your Rust program that generates text using a Markov chain. The enhancements include:
Removed dependency on external crates: The program no longer relies on the rand crate. Instead, it uses a simple Linear Congruential Generator (LCG) for randomness.
Improved text processing: Punctuation is preserved, and words are tokenized more effectively.
Enhanced error handling: The program includes more detailed error messages and checks for potential issues.
Additional features:
Option to specify a starting prefix.
Handling cases where the prefix length is larger than the number of words.
Preserves capitalization and punctuation in the generated text.
Note: This code adheres to your rules—everything is contained within one main.rs file, and no third-party crates are used.
rust
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io;
use std::time::{SystemTime, UNIX_EPOCH};
fn main() -> io::Result<()> {
// Get input arguments
let args: Vec<String> = env::args().collect();
if args.len() < 4 || args.len() > 5 {
eprintln!(
"Usage: {} <input_file> <prefix_length> <output_length> [start_prefix]",
args[0]
);
eprintln!("Example: {} input.txt 2 100 \"Once upon\"", args[0]);
return Ok(());
}
let filename = &args[1];
let prefix_length: usize = args[2]
.parse()
.expect("Prefix length must be a positive integer");
let output_length: usize = args[3]
.parse()
.expect("Output length must be a positive integer");
// Read the input file
let contents = fs::read_to_string(filename)?;
if contents.is_empty() {
eprintln!("The input file is empty.");
return Ok(());
}
// Split the contents into tokens (preserving punctuation)
let tokens = tokenize(&contents);
if tokens.len() < prefix_length {
eprintln!("The text is too short for the given prefix length.");
return Ok(());
}
// Build the Markov chain
let chain = build_markov_chain(&tokens, prefix_length);
// Determine the starting prefix
let start_prefix = if args.len() == 5 {
let start_words = tokenize(&args[4]);
if start_words.len() != prefix_length {
eprintln!(
"Start prefix must contain exactly {} token(s).",
prefix_length
);
return Ok(());
}
start_words
} else {
// Randomly pick a starting prefix
get_random_prefix(&chain)?
};
// Generate text
let generated_text = generate_text(&chain, prefix_length, output_length, start_prefix)?;
// Print the generated text
println!("{}", generated_text);
Ok(())
}
fn tokenize(text: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current_token = String::new();
for c in text.chars() {
if c.is_alphanumeric() || c == '\'' {
current_token.push(c);
} else {
if !current_token.is_empty() {
tokens.push(current_token.clone());
current_token.clear();
}
if !c.is_whitespace() {
tokens.push(c.to_string());
}
}
}
if !current_token.is_empty() {
tokens.push(current_token);
}
tokens
}
fn build_markov_chain(
tokens: &[String],
prefix_length: usize,
) -> HashMap<Vec<String>, Vec<String>> {
let mut chain: HashMap<Vec<String>, Vec<String>> = HashMap::new();
for i in 0..=(tokens.len() - prefix_length - 1) {
let prefix = tokens[i..i + prefix_length].to_vec();
let suffix = tokens[i + prefix_length].clone();
chain
.entry(prefix)
.or_insert_with(Vec::new)
.push(suffix);
}
chain
}
fn generate_text(
chain: &HashMap<Vec<String>, Vec<String>>,
prefix_length: usize,
output_length: usize,
mut prefix: Vec<String>,
) -> Result<String, &'static str> {
let mut result = prefix.clone();
let mut seed = seed_from_time();
for _ in 0..output_length {
if let Some(suffixes) = chain.get(&prefix) {
let next_word = {
let idx = lcg(&mut seed) as usize % suffixes.len();
suffixes[idx].clone()
};
result.push(next_word.clone());
// Move the prefix window
prefix.remove(0);
prefix.push(next_word);
} else {
// Cannot find the next word, stop generating
break;
}
}
Ok(reconstruct_text(&result))
}
fn reconstruct_text(tokens: &[String]) -> String {
let mut text = String::new();
let mut prev_was_word = false;
for token in tokens {
if token.chars().all(char::is_alphanumeric) || token == "'" {
if prev_was_word {
text.push(' ');
}
text.push_str(token);
prev_was_word = true;
} else {
text.push_str(token);
prev_was_word = false;
}
}
text
}
fn get_random_prefix(
chain: &HashMap<Vec<String>, Vec<String>>,
) -> Result<Vec<String>, &'static str> {
let keys: Vec<&Vec<String>> = chain.keys().collect();
if keys.is_empty() {
return Err("No prefixes found in the Markov chain.");
}
let mut seed = seed_from_time();
let idx = lcg(&mut seed) as usize % keys.len();
Ok(keys[idx].clone())
}
// Simple Linear Congruential Generator for pseudo-random numbers
fn lcg(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1);
*seed
}
fn seed_from_time() -> u64 {
let duration_since_epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_else(|_| Default::default());
duration_since_epoch.as_nanos() as u64
}
Explanation of Enhancements:
Removed Dependency on rand Crate:
Implemented a simple Linear Congruential Generator (LCG) for randomness.
Used the current system time as the seed for the random number generator.
Improved Text Processing:
Created a custom tokenize function to split the text into tokens, preserving punctuation and capitalization.
The tokenizer treats punctuation marks as separate tokens.
Improved the reconstruction of text by appropriately adding spaces and handling punctuation in the reconstruct_text function.
Enhanced Error Handling:
Added detailed error messages for various failure scenarios (e.g., empty input file, insufficient words for the given prefix length).
Checked for potential panics and handled them gracefully.
Additional Features:
Starting Prefix: Users can optionally specify a starting prefix when running the program. This allows for more control over the generated text.
Capitalization and Punctuation Preservation: The generated text maintains the capitalization and punctuation of the source text.
Improved Command-Line Interface: Provided usage examples and clearer instructions when incorrect arguments are supplied.
Code Organization and Readability:
Broke down functions into smaller units for better readability and maintainability (tokenize, reconstruct_text, lcg, etc.).