Created
April 15, 2015 07:33
-
-
Save hjr3/14a23e3f1872633ed5fb to your computer and use it in GitHub Desktop.
Example of a solution to the telegram problem using channels in Rust
This file contains 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
use std::sync::mpsc::channel; | |
use std::thread; | |
fn main() { | |
let line_length = 40; | |
let input = vec!("The task is", | |
"to write a program which", | |
"accepts", | |
"lines of text and generates output", | |
"lines of", | |
"a different length, without splitting any of the", | |
"words in the text. We assume no word is longer than the size of", | |
"the output lines."); | |
let (tx, rx) = channel(); | |
for i in input { | |
let words = i.split(' '); | |
for word in words { | |
let tx = tx.clone(); | |
thread::spawn(move || { | |
tx.send(word).unwrap(); | |
}); | |
} | |
} | |
drop(tx); | |
let mut lines: Vec<String> = Vec::new(); | |
let mut buf = String::new(); | |
for word in rx.iter() { | |
if buf.len() + word.len() > line_length { | |
buf.pop(); // remove space char at end of line | |
lines.push(buf.clone()); | |
buf.clear(); | |
} | |
buf.push_str(word); | |
buf.push(' '); | |
} | |
lines.push(buf); | |
for line in lines { | |
println!("{}", line); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment