Loop Over Candidates
00:00 Okay, so now what we need to do is find a way that we can loop over our stream. And in this case, there are a couple of different ways we can do this, but we want to keep track of some indices while we’re doing this.
00:13
So I’m thinking that the simplest way of doing this is probably just to loop over a range. So we can do something like for
some index—I’ll call it n
—in a range()
.
00:24
Let’s start at marker_length
,
00:27
and then we can loop to the length of the stream. So that means that, yeah, let’s go back to the simpler example that will start at 4
,
00:38
and then we’ll just loop through the end of the stream that we have. And then we’ll pick out the candidates. Now I can do this as starting at n-marker_length
and looping until n
, or sorry, slicing until n
. I was just about to ask why you start with marker_length
and not with 0
, but the idea is that you start at marker_length
and then look the, now in this case, four characters or four positions that come before the point where you are in the loop right now.
01:14
Yes. And the other natural example, as you said, we could start at 0
. So let’s actually just compare them.
01:23
We could start at 0
, and then in that case we’ll move to the len(stream)
and - marker_length
. I guess that we’ll need to have in there.
01:34
And in that case, our candidate would be stream
01:40
starting from n
and then going to n+marker_length
, something like this.
01:49
These are mostly equivalent. I chose the first one because the number that we’re looking for is the end of the sequence. So if the first four characters had been a marker, the answer would’ve been 4
.
02:02
And by choosing to kind of let n
run over the end of our candidate, it just means that we’ll have the number that we’re looking for immediately.
02:14
Okay. Because otherwise you would need to then add this marker_length
to it again to kind of get the number that you’re having. Yes, exactly. Okay.
02:23
And also to quickly point this out, in the for
loop where you start at 0
, you subtracted the marker_length
from the length of the stream, because once you reach the end of the stream minus the marker_length
, you don’t need to look forward.
02:38 Like, there aren’t enough characters anymore to make this work, and the other thing is that you don’t want to have the index out of bound there. Exactly. Now, typically the Advent of Code puzzles, they’re all well formed in the sense that there will be an answer.
02:54
So if I would kind of just trust that, I wouldn’t really care too much about subtracting the marker_length
, because I know that I will find a marker before then, but it’s still good practice to not willfully run into indexing errors.
03:10
Okay. So yeah, let’s stick with the first variant then by starting with the marker_length
in the range()
function. Yeah.
Become a Member to join the conversation.