I have setup the docker container to run the model evaluation.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Here's a self-contained Rust program that processes a text file in parallel and outputs word counts as JSON for each chunk:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_size } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let mut reader = BufReader::new(file.try_clone().unwrap()); let mut buffer = String::new(); // If not first chunk, read and discard partial word if i > 0 { reader.read_line(&mut buffer).unwrap(); buffer.clear(); } let mut total_read = 0; while total_read < (end_pos - start_pos) { let bytes_read = reader.read_line(&mut buffer).unwrap(); if bytes_read == 0 { break; } for word in buffer.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } total_read += bytes_read as u64; buffer.clear(); } // Convert HashMap to JSON-like string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Print results from each thread for handle in handles { println!("{}", handle.join().unwrap()); } } |
1 2 | rustc wordcount.rs
./wordcount
|
1 2 3 4 | {"word1": 5, "word2": 3} {"word2": 2, "word3": 4} {"word4": 1, "word2": 2} {"word5": 3, "word1": 1} |
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_size } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let mut reader = BufReader::new(file.try_clone().unwrap()); let mut buffer = String::new(); // If not first chunk, read and discard partial word if i > 0 { reader.read_line(&mut buffer).unwrap(); buffer.clear(); } let mut total_read = 0; while total_read < (end_pos - start_pos) { let bytes_read = reader.read_line(&mut buffer).unwrap(); if bytes_read == 0 { break; } for word in buffer.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } total_read += bytes_read as u64; buffer.clear(); } // Convert HashMap to JSON-like string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Print results from each thread for handle in handles { println!("{}", handle.join().unwrap()); } } |
Below is some student's code. I asked them to parallelize some code. Do not judge if it is correct, I have test cases for that. Logic errors are okay. So are synatx errors. Just tell me if they tried to parallelize it. use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_size } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let mut reader = BufReader::new(file.try_clone().unwrap()); let mut buffer = String::new(); // If not first chunk, read and discard partial word if i > 0 { reader.read_line(&mut buffer).unwrap(); buffer.clear(); } let mut total_read = 0; while total_read < (end_pos - start_pos) { let bytes_read = reader.read_line(&mut buffer).unwrap(); if bytes_read == 0 { break; } for word in buffer.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } total_read += bytes_read as u64; buffer.clear(); } // Convert HashMap to JSON-like string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Print results from each thread for handle in handles { println!("{}", handle.join().unwrap()); } } Answer either 'The student passes' or 'The student fails'.
The student passes.
Testing if the previous output contains the string student passes
: True
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_size } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let mut reader = BufReader::new(file.try_clone().unwrap()); let mut buffer = String::new(); // If not first chunk, read and discard partial word if i > 0 { reader.read_line(&mut buffer).unwrap(); buffer.clear(); } let mut total_read = 0; while total_read < (end_pos - start_pos) { let bytes_read = reader.read_line(&mut buffer).unwrap(); if bytes_read == 0 { break; } for word in buffer.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } total_read += bytes_read as u64; buffer.clear(); } // Convert HashMap to JSON-like string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Print results from each thread for handle in handles { println!("{}", handle.join().unwrap()); } } |
{"foolishness,": 1, "hope,": 1, "it": 10, "were": 2, "spring": 1, "Darkness,": 1, "had": 2, "us,": 2, "times,": 2, "was": 10, "everything": 1, "the": 11, "to": 1, "other": 1, "worst": 1, "nothing": 1, "before": 2, "of": 10, "incredulity,": 1, "best": 1, "epoch": 2, "going": 2, "way": 1, "direct": 2, "Heaven,": 1, "belief,": 1, "all": 2, "despair,": 1, "we": 4, "wisdom,": 1, "season": 2, "winter": 1, "age": 2, "Light,": 1}
{}
{}
{}
warning: unused import: `Read`
--> main.rs:4:35
|
4 | use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
| ^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: 1 warning emitted
Resulting in output: [('Darkness,', 1), ('Heaven,', 1), ('Light,', 1), ('age', 2), ('all', 2), ('before', 2), ('belief,', 1), ('best', 1), ('despair,', 1), ('direct', 2), ('epoch', 2), ('everything', 1), ('foolishness,', 1), ('going', 2), ('had', 2), ('hope,', 1), ('incredulity,', 1), ('it', 10), ('nothing', 1), ('of', 10), ('other', 1), ('season', 2), ('spring', 1), ('the', 11), ('times,', 2), ('to', 1), ('us,', 2), ('was', 10), ('way', 1), ('we', 4), ('were', 2), ('winter', 1), ('wisdom,', 1), ('worst', 1)]
Testing if the previous output equals the string [('Darkness,', 1), ('Heaven,', 1), ('Light,', 1), ('age', 2), ('all', 2), ('before', 2), ('belief,', 1), ('best', 1), ('despair,', 1), ('direct', 2), ('epoch', 2), ('everything', 1), ('foolishness,', 1), ('going', 2), ('had', 2), ('hope,', 1), ('incredulity,', 1), ('it', 10), ('nothing', 1), ('of', 10), ('other', 1), ('season', 2), ('spring', 1), ('the', 11), ('times,', 2), ('to', 1), ('us,', 2), ('was', 10), ('way', 1), ('we', 4), ('were', 2), ('winter', 1), ('wisdom,', 1), ('worst', 1)]
: True
I have setup the docker container to run the model evaluation.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Here's a Rust program that splits the file into 4 parts and processes them in parallel, outputting separate JSON dictionaries for each part:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::thread; fn count_words_in_range(start: u64, end: u64, filename: &str) -> HashMap<String, i32> { let mut word_counts = HashMap::new(); let file = File::open(filename).unwrap(); let mut reader = BufReader::new(file); // Seek to start position reader.seek(SeekFrom::Start(start)).unwrap(); let mut bytes_read = 0u64; for line in reader.lines() { let line = line.unwrap(); bytes_read += line.len() as u64 + 1; // +1 for newline // Split line into words for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } if start + bytes_read >= end { break; } } word_counts } fn format_json(map: &HashMap<String, i32>) -> String { let mut parts: Vec<String> = map .iter() .map(|(k, v)| format!("\"{}\": {}", k, v)) .collect(); parts.sort(); // Sort for consistent output format!("{{{}}}", parts.join(", ")) } fn main() { let filename = "/tmp/file.txt"; let file = File::open(filename).unwrap(); let file_size = file.metadata().unwrap().len(); let chunk_size = file_size / 4; let mut handles = vec![]; // Create 4 threads for i in 0..4 { let start = i * chunk_size; let end = if i == 3 { file_size } else { (i + 1) * chunk_size }; let filename = filename.to_string(); let handle = thread::spawn(move || { let counts = count_words_in_range(start, end, &filename); format_json(&counts) }); handles.push(handle); } // Wait for all threads and print results for handle in handles { let result = handle.join().unwrap(); println!("{}", result); } } |
1 2 | rustc word_count.rs
./word_count
|
1 2 3 4 | {"word1": 5, "word2": 3, "word3": 1} {"word2": 2, "word4": 4, "word5": 1} {"word1": 3, "word6": 2, "word7": 1} {"word3": 4, "word8": 2, "word9": 1} |
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::thread; fn count_words_in_range(start: u64, end: u64, filename: &str) -> HashMap<String, i32> { let mut word_counts = HashMap::new(); let file = File::open(filename).unwrap(); let mut reader = BufReader::new(file); // Seek to start position reader.seek(SeekFrom::Start(start)).unwrap(); let mut bytes_read = 0u64; for line in reader.lines() { let line = line.unwrap(); bytes_read += line.len() as u64 + 1; // +1 for newline // Split line into words for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } if start + bytes_read >= end { break; } } word_counts } fn format_json(map: &HashMap<String, i32>) -> String { let mut parts: Vec<String> = map .iter() .map(|(k, v)| format!("\"{}\": {}", k, v)) .collect(); parts.sort(); // Sort for consistent output format!("{{{}}}", parts.join(", ")) } fn main() { let filename = "/tmp/file.txt"; let file = File::open(filename).unwrap(); let file_size = file.metadata().unwrap().len(); let chunk_size = file_size / 4; let mut handles = vec![]; // Create 4 threads for i in 0..4 { let start = i * chunk_size; let end = if i == 3 { file_size } else { (i + 1) * chunk_size }; let filename = filename.to_string(); let handle = thread::spawn(move || { let counts = count_words_in_range(start, end, &filename); format_json(&counts) }); handles.push(handle); } // Wait for all threads and print results for handle in handles { let result = handle.join().unwrap(); println!("{}", result); } } |
Below is some student's code. I asked them to parallelize some code. Do not judge if it is correct, I have test cases for that. Logic errors are okay. So are synatx errors. Just tell me if they tried to parallelize it. use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::thread; fn count_words_in_range(start: u64, end: u64, filename: &str) -> HashMap<String, i32> { let mut word_counts = HashMap::new(); let file = File::open(filename).unwrap(); let mut reader = BufReader::new(file); // Seek to start position reader.seek(SeekFrom::Start(start)).unwrap(); let mut bytes_read = 0u64; for line in reader.lines() { let line = line.unwrap(); bytes_read += line.len() as u64 + 1; // +1 for newline // Split line into words for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } if start + bytes_read >= end { break; } } word_counts } fn format_json(map: &HashMap<String, i32>) -> String { let mut parts: Vec<String> = map .iter() .map(|(k, v)| format!("\"{}\": {}", k, v)) .collect(); parts.sort(); // Sort for consistent output format!("{{{}}}", parts.join(", ")) } fn main() { let filename = "/tmp/file.txt"; let file = File::open(filename).unwrap(); let file_size = file.metadata().unwrap().len(); let chunk_size = file_size / 4; let mut handles = vec![]; // Create 4 threads for i in 0..4 { let start = i * chunk_size; let end = if i == 3 { file_size } else { (i + 1) * chunk_size }; let filename = filename.to_string(); let handle = thread::spawn(move || { let counts = count_words_in_range(start, end, &filename); format_json(&counts) }); handles.push(handle); } // Wait for all threads and print results for handle in handles { let result = handle.join().unwrap(); println!("{}", result); } } Answer either 'The student passes' or 'The student fails'.
The student passes.
Testing if the previous output contains the string student passes
: True
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::thread; fn count_words_in_range(start: u64, end: u64, filename: &str) -> HashMap<String, i32> { let mut word_counts = HashMap::new(); let file = File::open(filename).unwrap(); let mut reader = BufReader::new(file); // Seek to start position reader.seek(SeekFrom::Start(start)).unwrap(); let mut bytes_read = 0u64; for line in reader.lines() { let line = line.unwrap(); bytes_read += line.len() as u64 + 1; // +1 for newline // Split line into words for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } if start + bytes_read >= end { break; } } word_counts } fn format_json(map: &HashMap<String, i32>) -> String { let mut parts: Vec<String> = map .iter() .map(|(k, v)| format!("\"{}\": {}", k, v)) .collect(); parts.sort(); // Sort for consistent output format!("{{{}}}", parts.join(", ")) } fn main() { let filename = "/tmp/file.txt"; let file = File::open(filename).unwrap(); let file_size = file.metadata().unwrap().len(); let chunk_size = file_size / 4; let mut handles = vec![]; // Create 4 threads for i in 0..4 { let start = i * chunk_size; let end = if i == 3 { file_size } else { (i + 1) * chunk_size }; let filename = filename.to_string(); let handle = thread::spawn(move || { let counts = count_words_in_range(start, end, &filename); format_json(&counts) }); handles.push(handle); } // Wait for all threads and print results for handle in handles { let result = handle.join().unwrap(); println!("{}", result); } } |
{"Darkness,": 1, "Heaven,": 1, "Light,": 1, "age": 2, "all": 2, "before": 2, "belief,": 1, "best": 1, "despair,": 1, "direct": 2, "epoch": 2, "everything": 1, "foolishness,": 1, "going": 2, "had": 2, "hope,": 1, "incredulity,": 1, "it": 10, "nothing": 1, "of": 10, "other": 1, "season": 2, "spring": 1, "the": 11, "times,": 2, "to": 1, "us,": 2, "was": 10, "way": 1, "we": 4, "were": 2, "winter": 1, "wisdom,": 1, "worst": 1}
{"Darkness,": 1, "Heaven,": 1, "Light,": 1, "all": 2, "before": 2, "belief,": 1, "despair,": 1, "direct": 2, "epoch": 2, "everything": 1, "going": 2, "had": 2, "hope,": 1, "incredulity,": 1, "it": 6, "ness,": 1, "nothing": 1, "of": 6, "other": 1, "season": 2, "spring": 1, "the": 7, "to": 1, "us,": 2, "was": 6, "way": 1, "we": 4, "were": 2, "winter": 1}
{"Darkness,": 1, "Heaven,": 1, "all": 2, "before": 2, "despair,": 1, "direct": 2, "e": 1, "everything": 1, "going": 2, "had": 2, "hope,": 1, "it": 2, "nothing": 1, "of": 3, "other": 1, "season": 1, "spring": 1, "the": 3, "to": 1, "us,": 2, "was": 2, "way": 1, "we": 4, "were": 2, "winter": 1}
{"Heaven,": 1, "all": 2, "before": 1, "direct": 2, "going": 2, "had": 1, "nothing": 1, "other": 1, "the": 1, "to": 1, "us,": 2, "way": 1, "we": 3, "were": 2}
Resulting in output: [('Darkness,', 3), ('Heaven,', 4), ('Light,', 2), ('age', 2), ('all', 8), ('before', 7), ('belief,', 2), ('best', 1), ('despair,', 3), ('direct', 8), ('e', 1), ('epoch', 4), ('everything', 3), ('foolishness,', 1), ('going', 8), ('had', 7), ('hope,', 3), ('incredulity,', 2), ('it', 18), ('ness,', 1), ('nothing', 4), ('of', 19), ('other', 4), ('season', 5), ('spring', 3), ('the', 22), ('times,', 2), ('to', 4), ('us,', 8), ('was', 18), ('way', 4), ('we', 15), ('were', 8), ('winter', 3), ('wisdom,', 1), ('worst', 1)]
Testing if the previous output equals the string [('Darkness,', 1), ('Heaven,', 1), ('Light,', 1), ('age', 2), ('all', 2), ('before', 2), ('belief,', 1), ('best', 1), ('despair,', 1), ('direct', 2), ('epoch', 2), ('everything', 1), ('foolishness,', 1), ('going', 2), ('had', 2), ('hope,', 1), ('incredulity,', 1), ('it', 10), ('nothing', 1), ('of', 10), ('other', 1), ('season', 2), ('spring', 1), ('the', 11), ('times,', 2), ('to', 1), ('us,', 2), ('was', 10), ('way', 1), ('we', 4), ('were', 2), ('winter', 1), ('wisdom,', 1), ('worst', 1)]
: False
I have setup the docker container to run the model evaluation.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Here's a self-contained Rust program that processes a text file in parallel and outputs word frequencies as JSON for each chunk:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts: HashMap<String, usize> = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_size } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let reader = BufReader::new(&*file); let mut is_first_line = true; for line in reader.lines() { let line = line.unwrap(); // Skip first line for chunks 1-3 as it might be partial if i > 0 && is_first_line { is_first_line = false; continue; } // Process until we reach end_pos if file.seek(SeekFrom::Current(0)).unwrap() > end_pos { break; } for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } // Convert HashMap to JSON string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Print results from each thread for handle in handles { println!("{}", handle.join().unwrap()); } } |
1 2 | rustc word_count.rs
./word_count
|
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts: HashMap<String, usize> = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_size } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let reader = BufReader::new(&*file); let mut is_first_line = true; for line in reader.lines() { let line = line.unwrap(); // Skip first line for chunks 1-3 as it might be partial if i > 0 && is_first_line { is_first_line = false; continue; } // Process until we reach end_pos if file.seek(SeekFrom::Current(0)).unwrap() > end_pos { break; } for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } // Convert HashMap to JSON string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Print results from each thread for handle in handles { println!("{}", handle.join().unwrap()); } } |
Below is some student's code. I asked them to parallelize some code. Do not judge if it is correct, I have test cases for that. Logic errors are okay. So are synatx errors. Just tell me if they tried to parallelize it. use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts: HashMap<String, usize> = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_size } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let reader = BufReader::new(&*file); let mut is_first_line = true; for line in reader.lines() { let line = line.unwrap(); // Skip first line for chunks 1-3 as it might be partial if i > 0 && is_first_line { is_first_line = false; continue; } // Process until we reach end_pos if file.seek(SeekFrom::Current(0)).unwrap() > end_pos { break; } for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } // Convert HashMap to JSON string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Print results from each thread for handle in handles { println!("{}", handle.join().unwrap()); } } Answer either 'The student passes' or 'The student fails'.
The student passes.
Testing if the previous output contains the string student passes
: True
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts: HashMap<String, usize> = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_size } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let reader = BufReader::new(&*file); let mut is_first_line = true; for line in reader.lines() { let line = line.unwrap(); // Skip first line for chunks 1-3 as it might be partial if i > 0 && is_first_line { is_first_line = false; continue; } // Process until we reach end_pos if file.seek(SeekFrom::Current(0)).unwrap() > end_pos { break; } for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } // Convert HashMap to JSON string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Print results from each thread for handle in handles { println!("{}", handle.join().unwrap()); } } |
error[E0502]: cannot borrow `file` as mutable because it is also borrowed as immutable
--> main.rs:39:20
|
26 | let reader = BufReader::new(&*file);
| ---- immutable borrow occurs here
...
29 | for line in reader.lines() {
| -------------- immutable borrow later used here
...
39 | if file.seek(SeekFrom::Current(0)).unwrap() > end_pos {
| ^^^^ mutable borrow occurs here
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0502`.
main.sh: line 2: ./a.out: No such file or directory
Resulting in output: []
Testing if the previous output equals the string [('Darkness,', 1), ('Heaven,', 1), ('Light,', 1), ('age', 2), ('all', 2), ('before', 2), ('belief,', 1), ('best', 1), ('despair,', 1), ('direct', 2), ('epoch', 2), ('everything', 1), ('foolishness,', 1), ('going', 2), ('had', 2), ('hope,', 1), ('incredulity,', 1), ('it', 10), ('nothing', 1), ('of', 10), ('other', 1), ('season', 2), ('spring', 1), ('the', 11), ('times,', 2), ('to', 1), ('us,', 2), ('was', 10), ('way', 1), ('we', 4), ('were', 2), ('winter', 1), ('wisdom,', 1), ('worst', 1)]
: False
I have setup the docker container to run the model evaluation.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Here's a Rust program that counts words in parallel across 4 cores, printing separate JSON outputs for each chunk:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; use std::thread; fn count_words(text: &str) -> HashMap<String, usize> { let mut word_counts = HashMap::new(); for word in text.split_whitespace() { let word = word.trim(); if !word.is_empty() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } word_counts } fn format_json(map: &HashMap<String, usize>) -> String { let mut pairs: Vec<String> = map .iter() .map(|(k, v)| format!("\"{}\": {}", k, v)) .collect(); pairs.sort(); // For consistent output format!("{{{}}}", pairs.join(", ")) } fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let mut handles = vec![]; for i in 0..4 { let mut file = File::open("/tmp/file.txt").expect("Failed to open file"); let start = i * chunk_size; let end = if i == 3 { file_size } else { (i + 1) * chunk_size }; let handle = thread::spawn(move || { // Seek to start position file.seek(SeekFrom::Start(start)).expect("Failed to seek"); let mut reader = BufReader::new(file); let mut buffer = String::new(); // If not first chunk, read and discard partial word if i > 0 { let mut partial = String::new(); reader.read_line(&mut partial).expect("Failed to read line"); } // Read chunk let mut bytes_read = 0; while bytes_read < (end - start) { let mut line = String::new(); let n = reader.read_line(&mut line).expect("Failed to read line"); if n == 0 { break; } buffer.push_str(&line); bytes_read += n as u64; } let counts = count_words(&buffer); format_json(&counts) }); handles.push(handle); } for handle in handles { match handle.join() { Ok(json) => println!("{}", json), Err(_) => eprintln!("Thread panicked"), } } } |
1 2 | rustc wordcount.rs
./wordcount
|
1 2 3 4 | {"word1": 5, "word2": 3, "word3": 1} {"another": 2, "set": 4, "words": 1} {"from": 3, "third": 2, "chunk": 1} {"last": 4, "chunk": 2, "words": 3} |
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; use std::thread; fn count_words(text: &str) -> HashMap<String, usize> { let mut word_counts = HashMap::new(); for word in text.split_whitespace() { let word = word.trim(); if !word.is_empty() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } word_counts } fn format_json(map: &HashMap<String, usize>) -> String { let mut pairs: Vec<String> = map .iter() .map(|(k, v)| format!("\"{}\": {}", k, v)) .collect(); pairs.sort(); // For consistent output format!("{{{}}}", pairs.join(", ")) } fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let mut handles = vec![]; for i in 0..4 { let mut file = File::open("/tmp/file.txt").expect("Failed to open file"); let start = i * chunk_size; let end = if i == 3 { file_size } else { (i + 1) * chunk_size }; let handle = thread::spawn(move || { // Seek to start position file.seek(SeekFrom::Start(start)).expect("Failed to seek"); let mut reader = BufReader::new(file); let mut buffer = String::new(); // If not first chunk, read and discard partial word if i > 0 { let mut partial = String::new(); reader.read_line(&mut partial).expect("Failed to read line"); } // Read chunk let mut bytes_read = 0; while bytes_read < (end - start) { let mut line = String::new(); let n = reader.read_line(&mut line).expect("Failed to read line"); if n == 0 { break; } buffer.push_str(&line); bytes_read += n as u64; } let counts = count_words(&buffer); format_json(&counts) }); handles.push(handle); } for handle in handles { match handle.join() { Ok(json) => println!("{}", json), Err(_) => eprintln!("Thread panicked"), } } } |
Below is some student's code. I asked them to parallelize some code. Do not judge if it is correct, I have test cases for that. Logic errors are okay. So are synatx errors. Just tell me if they tried to parallelize it. use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; use std::thread; fn count_words(text: &str) -> HashMap<String, usize> { let mut word_counts = HashMap::new(); for word in text.split_whitespace() { let word = word.trim(); if !word.is_empty() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } word_counts } fn format_json(map: &HashMap<String, usize>) -> String { let mut pairs: Vec<String> = map .iter() .map(|(k, v)| format!("\"{}\": {}", k, v)) .collect(); pairs.sort(); // For consistent output format!("{{{}}}", pairs.join(", ")) } fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let mut handles = vec![]; for i in 0..4 { let mut file = File::open("/tmp/file.txt").expect("Failed to open file"); let start = i * chunk_size; let end = if i == 3 { file_size } else { (i + 1) * chunk_size }; let handle = thread::spawn(move || { // Seek to start position file.seek(SeekFrom::Start(start)).expect("Failed to seek"); let mut reader = BufReader::new(file); let mut buffer = String::new(); // If not first chunk, read and discard partial word if i > 0 { let mut partial = String::new(); reader.read_line(&mut partial).expect("Failed to read line"); } // Read chunk let mut bytes_read = 0; while bytes_read < (end - start) { let mut line = String::new(); let n = reader.read_line(&mut line).expect("Failed to read line"); if n == 0 { break; } buffer.push_str(&line); bytes_read += n as u64; } let counts = count_words(&buffer); format_json(&counts) }); handles.push(handle); } for handle in handles { match handle.join() { Ok(json) => println!("{}", json), Err(_) => eprintln!("Thread panicked"), } } } Answer either 'The student passes' or 'The student fails'.
The student passes.
Testing if the previous output contains the string student passes
: True
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; use std::thread; fn count_words(text: &str) -> HashMap<String, usize> { let mut word_counts = HashMap::new(); for word in text.split_whitespace() { let word = word.trim(); if !word.is_empty() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } word_counts } fn format_json(map: &HashMap<String, usize>) -> String { let mut pairs: Vec<String> = map .iter() .map(|(k, v)| format!("\"{}\": {}", k, v)) .collect(); pairs.sort(); // For consistent output format!("{{{}}}", pairs.join(", ")) } fn main() { let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_size = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_size / 4; let mut handles = vec![]; for i in 0..4 { let mut file = File::open("/tmp/file.txt").expect("Failed to open file"); let start = i * chunk_size; let end = if i == 3 { file_size } else { (i + 1) * chunk_size }; let handle = thread::spawn(move || { // Seek to start position file.seek(SeekFrom::Start(start)).expect("Failed to seek"); let mut reader = BufReader::new(file); let mut buffer = String::new(); // If not first chunk, read and discard partial word if i > 0 { let mut partial = String::new(); reader.read_line(&mut partial).expect("Failed to read line"); } // Read chunk let mut bytes_read = 0; while bytes_read < (end - start) { let mut line = String::new(); let n = reader.read_line(&mut line).expect("Failed to read line"); if n == 0 { break; } buffer.push_str(&line); bytes_read += n as u64; } let counts = count_words(&buffer); format_json(&counts) }); handles.push(handle); } for handle in handles { match handle.join() { Ok(json) => println!("{}", json), Err(_) => eprintln!("Thread panicked"), } } } |
{"Darkness,": 1, "Heaven,": 1, "Light,": 1, "age": 2, "all": 2, "before": 2, "belief,": 1, "best": 1, "despair,": 1, "direct": 2, "epoch": 2, "everything": 1, "foolishness,": 1, "going": 2, "had": 2, "hope,": 1, "incredulity,": 1, "it": 10, "nothing": 1, "of": 10, "other": 1, "season": 2, "spring": 1, "the": 11, "times,": 2, "to": 1, "us,": 2, "was": 10, "way": 1, "we": 4, "were": 2, "winter": 1, "wisdom,": 1, "worst": 1}
{}
{}
{}
warning: unused import: `Read`
--> main.rs:4:35
|
4 | use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
| ^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: 1 warning emitted
Resulting in output: [('Darkness,', 1), ('Heaven,', 1), ('Light,', 1), ('age', 2), ('all', 2), ('before', 2), ('belief,', 1), ('best', 1), ('despair,', 1), ('direct', 2), ('epoch', 2), ('everything', 1), ('foolishness,', 1), ('going', 2), ('had', 2), ('hope,', 1), ('incredulity,', 1), ('it', 10), ('nothing', 1), ('of', 10), ('other', 1), ('season', 2), ('spring', 1), ('the', 11), ('times,', 2), ('to', 1), ('us,', 2), ('was', 10), ('way', 1), ('we', 4), ('were', 2), ('winter', 1), ('wisdom,', 1), ('worst', 1)]
Testing if the previous output equals the string [('Darkness,', 1), ('Heaven,', 1), ('Light,', 1), ('age', 2), ('all', 2), ('before', 2), ('belief,', 1), ('best', 1), ('despair,', 1), ('direct', 2), ('epoch', 2), ('everything', 1), ('foolishness,', 1), ('going', 2), ('had', 2), ('hope,', 1), ('incredulity,', 1), ('it', 10), ('nothing', 1), ('of', 10), ('other', 1), ('season', 2), ('spring', 1), ('the', 11), ('times,', 2), ('to', 1), ('us,', 2), ('was', 10), ('way', 1), ('we', 4), ('were', 2), ('winter', 1), ('wisdom,', 1), ('worst', 1)]
: True
I have setup the docker container to run the model evaluation.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Write a self-contained Rust program that prints a JSON output of how often each word appears in a text file located in /tmp/file.txt. So if the file contains "This is is is, an example" then the program should print to stdout. {"This": 1, "is": 2, "is,": 1, "an": 1, "example": 1} Don't import any crates that would require a Cargo.toml file. I'll just compile it with `rustc yourfile.rs` and it should work. The program should be run by calling /path/to/rust_word_count with no arguments. Make it run in parallel on 4 cores at the same time, each job taking ~1/4 of the file. Print out 4 differnt json dicts, one per line. I'll do the merging.
Here's a self-contained Rust program that processes a text file in parallel and outputs word counts as JSON for each chunk:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { // Open the file let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_len = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_len / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; // Spawn 4 threads for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts: HashMap<String, usize> = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_len } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let reader = BufReader::new(&*file); // Read and process lines for line in reader.lines() { if let Ok(line) = line { for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } // Check if we've reached our chunk's end if file.stream_position().unwrap() >= end_pos { break; } } // Convert HashMap to JSON-like string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Collect and print results for handle in handles { if let Ok(json) = handle.join() { println!("{}", json); } } } |
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { // Open the file let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_len = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_len / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; // Spawn 4 threads for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts: HashMap<String, usize> = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_len } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let reader = BufReader::new(&*file); // Read and process lines for line in reader.lines() { if let Ok(line) = line { for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } // Check if we've reached our chunk's end if file.stream_position().unwrap() >= end_pos { break; } } // Convert HashMap to JSON-like string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Collect and print results for handle in handles { if let Ok(json) = handle.join() { println!("{}", json); } } } |
Below is some student's code. I asked them to parallelize some code. Do not judge if it is correct, I have test cases for that. Logic errors are okay. So are synatx errors. Just tell me if they tried to parallelize it. use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { // Open the file let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_len = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_len / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; // Spawn 4 threads for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts: HashMap<String, usize> = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_len } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let reader = BufReader::new(&*file); // Read and process lines for line in reader.lines() { if let Ok(line) = line { for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } // Check if we've reached our chunk's end if file.stream_position().unwrap() >= end_pos { break; } } // Convert HashMap to JSON-like string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Collect and print results for handle in handles { if let Ok(json) = handle.join() { println!("{}", json); } } } Answer either 'The student passes' or 'The student fails'.
The student passes.
Testing if the previous output contains the string student passes
: True
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::thread; fn main() { // Open the file let file = File::open("/tmp/file.txt").expect("Failed to open file"); let file_len = file.metadata().expect("Failed to get metadata").len(); let chunk_size = file_len / 4; let file = Arc::new(Mutex::new(file)); let mut handles = vec![]; // Spawn 4 threads for i in 0..4 { let file = Arc::clone(&file); let handle = thread::spawn(move || { let mut word_counts: HashMap<String, usize> = HashMap::new(); let start_pos = i * chunk_size; let end_pos = if i == 3 { file_len } else { (i + 1) * chunk_size }; let mut file = file.lock().unwrap(); file.seek(SeekFrom::Start(start_pos)).unwrap(); let reader = BufReader::new(&*file); // Read and process lines for line in reader.lines() { if let Ok(line) = line { for word in line.split_whitespace() { *word_counts.entry(word.to_string()).or_insert(0) += 1; } } // Check if we've reached our chunk's end if file.stream_position().unwrap() >= end_pos { break; } } // Convert HashMap to JSON-like string let mut json = String::from("{"); for (i, (word, count)) in word_counts.iter().enumerate() { if i > 0 { json.push_str(", "); } json.push_str(&format!("\"{}\": {}", word, count)); } json.push('}'); json }); handles.push(handle); } // Collect and print results for handle in handles { if let Ok(json) = handle.join() { println!("{}", json); } } } |
error[E0502]: cannot borrow `file` as mutable because it is also borrowed as immutable
--> main.rs:39:20
|
28 | let reader = BufReader::new(&*file);
| ---- immutable borrow occurs here
...
31 | for line in reader.lines() {
| -------------- immutable borrow later used here
...
39 | if file.stream_position().unwrap() >= end_pos {
| ^^^^ mutable borrow occurs here
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0502`.
main.sh: line 2: ./a.out: No such file or directory
Resulting in output: []
Testing if the previous output equals the string [('Darkness,', 1), ('Heaven,', 1), ('Light,', 1), ('age', 2), ('all', 2), ('before', 2), ('belief,', 1), ('best', 1), ('despair,', 1), ('direct', 2), ('epoch', 2), ('everything', 1), ('foolishness,', 1), ('going', 2), ('had', 2), ('hope,', 1), ('incredulity,', 1), ('it', 10), ('nothing', 1), ('of', 10), ('other', 1), ('season', 2), ('spring', 1), ('the', 11), ('times,', 2), ('to', 1), ('us,', 2), ('was', 10), ('way', 1), ('we', 4), ('were', 2), ('winter', 1), ('wisdom,', 1), ('worst', 1)]
: False