2021: day14: fix stack overflow in part 1
This commit is contained in:
parent
218d9d5298
commit
9d81739f2b
|
@ -119,27 +119,41 @@ impl std::str::FromStr for Polymer {
|
|||
}
|
||||
|
||||
fn insert_pairs(
|
||||
mut molecules: LinkedList<char>,
|
||||
molecules: LinkedList<char>,
|
||||
rules: &HashMap<(char, char), char>,
|
||||
) -> Result<LinkedList<char>> {
|
||||
if molecules.len() <= 1 {
|
||||
return Ok(molecules);
|
||||
}
|
||||
|
||||
let mut head = molecules;
|
||||
let mut tail = head.split_off(0);
|
||||
|
||||
while tail.len() > 1 {
|
||||
// List length is at least 2
|
||||
let mut iter = molecules.iter();
|
||||
let mut iter = tail.iter();
|
||||
let (left, right) = (*iter.next().unwrap(), *iter.next().unwrap());
|
||||
|
||||
let to_insert = *rules
|
||||
.get(&(left, right))
|
||||
.with_context(|| format!("couldn't find rule for pair ({}, {})", left, right))?;
|
||||
|
||||
let mut tail = insert_pairs(molecules.split_off(1), rules)?;
|
||||
// tail = left
|
||||
// new_tail = right -> rest
|
||||
let new_tail = tail.split_off(1);
|
||||
|
||||
molecules.push_back(to_insert);
|
||||
molecules.append(&mut tail);
|
||||
// head = head -> left
|
||||
head.append(&mut tail);
|
||||
// head = head -> left -> to_insert
|
||||
head.push_back(to_insert);
|
||||
|
||||
Ok(molecules)
|
||||
// tail = right -> rest
|
||||
tail = new_tail;
|
||||
}
|
||||
|
||||
head.append(&mut tail);
|
||||
|
||||
Ok(head)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
Loading…
Reference in a new issue