#can I refactor this piece of code into [something](_iterators_)?

8 messages · Page 1 of 1 (latest)

deep gazelle
#

so i have this chunk of code (spoilers: solution to day 9 AoC)

||```rust
let mut tails: Vec<> = (0..9).into_iter().map(|| (0, 0)).collect();
// ...

for line in input.lines() {
    let mut line_iter = line.split_whitespace();
    let direction = //..
    let distance = //..

    for i in 0..distance {
        head = match direction {
            "R" => // ...
            _ => panic!("unknown direction {direction} in line {line}"),
        };
        let mut prev_head = head;
        // This one here
        for j in 0..tails.len() {
            tails[j] = move_tail(prev_head, tails[j]);
            prev_head = tails[j];
        }
        //..
    }
}

I think there should be a way to change the code starting with `let mut prev_head=head; for j in 0..tails...` to remove the for-loop, but I cant figure out how exactly.
umbral mason
#

for tail in tails.iter_mut()

#

you'd get a mutable reference then

deep gazelle
#

you have a point.

oak root
#

For the Vec, you could also just do vec![(0, 0); 9],

#

(Also, most ranges implement Iterator already, meaning using IntoIterator::into_iter on them, is a no-op... 👀)

deep gazelle