Problem overview
Version 2 of the head project takes a second argument: head(lines: Vec<String>, n: i32) -> String returns the first n lines joined by newlines. For this version it may be assumed that 0 <= n <= lines.len(), so n is never more than the number of lines. When n is 0 the result is the empty string.
For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3 the result is "alpha\nbeta\ngamma".
Approach: build the string line by line
The first version fixed the count at 10. Now the count is a parameter, and this version builds the string in a loop that runs n times. The usual rule applies: a newline goes between two lines, so every line except the first gets a newline in front of it. That puts a separator between neighbours and none after the last line.
The statement promises that n fits inside the vector, so the loop doesn't have to check the length. That promise is why this version is simple, and it also marks where it breaks, as the edge cases below show.
Step by step
- Accumulator.
let mut result = String::new();starts empty, andmutallows appending. - Loop.
for i in 0..ncounts0, 1, ..., n - 1. The range excludesn, giving exactlynpasses. Forn = 0the loop never runs. - Separator test.
if i > 0is true on every pass but the first. - Newline. Inside it,
result += "\n";. - The line.
result += &lines[i as usize];. The loop variable has the type ofn, which isi32, but a vector is indexed with ausize, soi as usizeconverts it. The&borrows the text, so it is copied ontoresultand not moved out of the vector. - Return.
return result;after the loop.
The solution in Rust
impl Solution {
fn head(lines: Vec<String>, n: i32) -> String {
let mut result = String::new();
for i in 0..n {
if i > 0 {
result += "\n";
}
result += &lines[i as usize];
}
return result;
}
}
Rust details:
- Rust has no automatic conversion between integer types.
lines[i]with ani32index doesn't compile, so the explicitas usizeis required. For the non-negative values this version assumes, the conversion is exact. lines[i as usize]is aString, and&lines[i as usize]a&Stringthat Rust turns into the&strthat+=wants.- Indexing a vector out of bounds panics; it does not return a default value.
Complexity
The loop runs n times and each pass copies one line, so time is proportional to the combined length of the first n lines. The result is the only extra storage.
Edge cases and common mistakes
n = 0. The loop doesn't run and the result is"".nequal to the number of lines. All lines come back: for the five-word list andn = 5, the result is"alpha\nbeta\ngamma\ndelta\nepsilon".nlarger than the number of lines. This is outside the promise made here. With two lines andn = 3, the third pass indexes position 2 and the program panics with "index out of bounds: the len is 2 but the index is 2". In this version the caller is responsible for keepingnin range.- Trailing newline. Adding
"\n"after every line leaves one at the end. Thei > 0test avoids it. - Forgetting the cast. Indexing with
idirectly is a compile error, becauseiis ani32.
Testing
alpha..epsilon, n = 3 -> "alpha\nbeta\ngamma"
alpha..epsilon, n = 0 -> ""
alpha..epsilon, n = 5 -> "alpha\nbeta\ngamma\ndelta\nepsilon"
