Count as you go
A counter goes up by one for each thing seen and is read at the end, and a yes or no is handed back the moment one element settles it.
- Reach for it when
- The problem says how many, is there any, or are all.
- The move
- A counter you add to, or a yes or no you can return the moment it is settled.
- Cost
- O(n) time, O(1) extra space.
The idea
Every sheep I own has won a prize.
How many sheep do you own?
Don't rush me. We'll come back to them. Here are six numbers: 4, -2, 0, 7, 0, -5. How many are negative?
Two.
One at a time, please, as in "Best so far". There you carried the best one. What do you carry this time?
A count. It starts at zero, and each time a number is below zero I add one to it.
Zero? In that lesson zero was the villain.
There it sat in the chair, passing itself off as one of the numbers. Here it's the truth: before the first number, I have counted none.
Picture a gate in a field wall. The flock goes through it one at a time, and you stand beside it with a clicker. You're counting the black sheep, so each time one goes through, you click. When can you read the clicker out?
When the last sheep is through. Until then, any sheep still in the field could be one more click.
People count sheep to get to sleep, you know.
It has never worked for me. A count can't finish early, so I have to stay awake for the whole flock.
New question, same gate. Is there a wolf in the flock?
I watch. The moment a wolf comes through, I shout yes.
And then you watch the rest, to be thorough.
I do not. One wolf settles it. Nothing still in the field can turn that yes into a no.
So when do you get to say no?
Only when the last one is through and I haven't shouted. Yes can come at any moment. No has to wait for the end.
Turn it round. Are they all sheep?
The same wolf answers it. The moment something comes through that isn't a sheep, the answer is no. This time yes is the one that waits.
So "how many" needs the whole flock, and "is there any" and "are all" can be over at the first wolf.
One of their two answers can. The other still needs the whole flock.
Last one. The field is empty, and nothing comes through the gate at all. How many black sheep? Is there a wolf? Are they all sheep?
None. No. And yes.
Yes? They were all sheep, all none of them?
Nothing came through that wasn't one. I had no reason to say no.
Keep that answer. It has prizes to explain.
That is the whole tool: a clicker for "how many", read only when the whole flock is through, and a shout for "is there any" and "are all", which can come at the first wolf. Everything else in this lesson is one of those two with one thing changed at a time.
The shape
This is what you know by heart: two small loops. The numbers are the flock, and the loop is the gate that each of them comes through. The first loop is the clicker. Its black sheep are the negative numbers.
/// How many of the numbers are below zero.
func countOfNegatives(_ numbers: [Int]) -> Int {
var count = 0 // the clicker starts at zero
for number in numbers {
if number < 0 { // is this one of the ones being counted?
count += 1 // one click
}
}
return count // read it when the last one is through
}It has four parts, and each is there for a reason.
- The start.
countbegins at 0, because before the first number nothing has been counted. In "Best so far" zero was a made-up start. Here it is the true count so far. - The test. The
ifsays which numbers are counted. It is the only line that changes from one counting problem to the next. - The click.
count += 1adds 1, whatever the number is. You are counting the sheep, not weighing them. - The answer.
return countcomes after the loop, never inside it. Until the last number is through, the count can still go up.
The second loop is the shout.
/// Whether any of the numbers is zero.
func containsZero(_ numbers: [Int]) -> Bool {
for number in numbers {
if number == 0 { // the wolf
return true // settled: nothing still to come can change it
}
}
return false // the last one is through, and none was zero
}It has three parts.
- Nothing to carry. There is no variable. This answer is not built up a little at a time. It is not known, and then all at once it is.
- The answer inside the loop. One zero settles the question, so
return truehands the answer back on the spot.returnends the whole function, and the loop with it, so the numbers after that zero are never looked at. - The answer after the loop.
return falseis reached only when the loop has run out without returning: every number has come through, and none was zero. No one number can say that. Only the end of the array can.
The two answers are opposites, and they are never in the same place. The answer that one number can settle goes inside the loop. The other goes after it.
"Are all" is this second loop with its two answers changed over, and step 3 has it.
Swift has words of its own for these loops, and you may have typed them in an app. They are at the end of "Step by step". First comes each loop, written by you.
Watch it run
The six numbers are 4, -2, 0, 7, 0 and -5. First the clicker, counting the negative numbers. Here is count after each number.
| number | below zero? | count after |
|---|---|---|
| 4 | no | 0 |
| -2 | yes | 1 |
| 0 | no | 1 |
| 7 | no | 1 |
| 0 | no | 1 |
| -5 | yes | 2 |
The answer is 2. Look at the last row. The count went up on the very last number, so there was no earlier moment at which it could have been read. Look at the third row too: zero is not below zero, so it gets no click.
Now the shout, "is there any zero?", on the same six numbers.
| number | zero? | then |
|---|---|---|
| 4 | no | on to the next number |
| -2 | no | on to the next number |
| 0 | yes | return true |
The answer is true, and the table stops there: 3 rows for 6 numbers. The 7, the second 0 and the -5 never came through the gate. That last row is the whole difference between the two loops. The clicker has a row for every number, always. The shout stops at the row that settles it.
Step by step
How many numbers are negative?
This step is the first shape, written from an empty function. What is new is the counter: a variable that starts at zero and goes up by one each time the thing is seen.
Say the sentence that stays true as the loop runs: count is how many of the numbers met so far are negative. It is true before the loop, when no number has been met and count is 0. Each pass keeps it true. So it is true at the end, when every number has been met.
The sentence covers the empty array as well. With no numbers the loop does not run even once, and the answer is the 0 that count started with: of no numbers, none are negative. Nothing had to be written for it.
Negative means below zero, so the test is number < 0. Zero is not negative. For 4, -2, 0, 7, 0 and -5 the answer is 2, and neither zero is counted. This step's second problem hands you a version that counts them, to mend.
Is there any zero?
You could answer this with the clicker: count the zeros, and at the end ask whether count > 0. That is right, and it does too much. A count needs the whole flock, so for 4, -2, 0, 7, 0 and -5 it looks at all 6 numbers. The question was settled at the third number.
This step is the second shape, written from an empty function. What is new: return inside the loop. One zero settles the question whatever comes after it, so the function hands back true there and then, and the loop is over.
To see where it stops, here is the same loop keeping a list of the numbers it looks at.
/// The numbers that "is there any zero?" looks at before it can answer, in order.
func lookedAt(_ numbers: [Int]) -> [Int] {
var looked: [Int] = []
for number in numbers {
looked.append(number) // this one has come through the gate
if number == 0 {
return looked // the wolf: nothing after it is looked at
}
}
return looked // no zero: every number had to be looked at
}For the six numbers it gives [4, -2, 0]: 3 numbers looked at, not 6. For a million numbers with a zero at the front it looks at 1, where the clicker would look at all 1,000,000. For 4 and 7 it gives [4, 7]. With no zero there is nothing to stop it, and only the end of the array can say no.
So the line after the loop is return false. The loop gets that far only when no number was zero. It is also what an empty array gets: no numbers, so no zero.
return does more than the break of "Loops and indexes". break ends the loop, and the function carries on below it. return ends the function, with the answer.
This step's second problem asks for that list of the numbers looked at. Its third hands you a version that answers too soon, to mend. "What goes wrong" shows it.
Are all the numbers positive?
/// Whether every one of the numbers is above zero.
func allPositive(_ numbers: [Int]) -> Bool {
for number in numbers {
if number <= 0 { // the wolf: one that is not positive
return false // settled: the rest cannot make it true again
}
}
return true // the last one is through, and none said no
}What is new: "are all" is "is there any" asked about the opposite, with the two answers changed over.
You do not watch for positive numbers. A positive number settles nothing, because the next one may still spoil it. You watch for the wolf: one number that is not positive. That number settles it at once, and the answer it settles is no. So return false is inside the loop, and return true waits after it, for when every number has come through and none said no.
Turn the test round with care. Positive means above zero. Not positive means zero or below, so the wolf is number <= 0.
For 4, -2, 0, 7, 0 and -5 the answer is false, settled at the second number. For 4, 7 and 3 it is true, and only the end of the array could say so. For 4, 0 and 7 it is false: zero is not positive.
For an empty array it is true. That can look wrong, and it is what the question means: the answer is no only when some number is not positive, and here there is none.
Here are the three questions so far, side by side.
| The question | What one number can settle | What only the end can say |
|---|---|---|
| How many are negative? | nothing | the count |
| Is there any zero? | yes | no |
| Are all positive? | no | yes |
Before you write the loop, ask what one number can settle. That answer is returned inside the loop, and the other waits for the end.
This step's second problem hands you a version that never says yes, to mend.
How many characters are vowels?
/// How many of the characters of `s` are vowels. A capital vowel counts too.
func countOfVowels(_ s: String) -> Int {
let vowels: Set<Character> = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
var count = 0
for character in s {
if vowels.contains(character) { // the only line that knows what is counted
count += 1
}
}
return count
}You wrote most of this loop in "A string as an array of characters". Here it is again as the clicker.
What is new: the test can be any question about one element that has a yes or no for an answer. In step 1 it was a comparison. Here it is a question put to a set: is this character one of the vowels? The start, the click and the answer are where they were. Only the test knows what is being counted.
This problem counts a capital vowel as well as a small one, so the set holds ten characters. That is where a problem's small print goes: into the test, and nowhere else.
For Orithms the answer is 2, the O and the i. For queue it is 4, because a vowel is counted every time it comes. For rhythm it is 0.
How many numbers are larger than the one before them?
Call a number a rise when it is larger than the one before it. This step counts the rises.
/// How many of the numbers are larger than the one before them.
/// `numbers` is never empty.
func countOfRises(_ numbers: [Int]) -> Int {
var count = 0
for i in 1..<numbers.count { // from 1: position 0 has no one before it
if numbers[i] > numbers[i - 1] { // this one against the one before it
count += 1
}
}
return count
}What is new: the test looks at two numbers, this one and the one before it. One number on its own cannot say whether it is larger than the one before. So the loop walks the positions, and the test reads numbers[i] and numbers[i - 1].
That is why the loop starts at position 1. The number at position 0 has no number before it, so it is never asked. It is only ever the one before.
Here are the six numbers, a pair at a time.
i | the one before | this one | larger? | count after |
|---|---|---|---|---|
| 1 | 4 | -2 | no | 0 |
| 2 | -2 | 0 | yes | 1 |
| 3 | 0 | 7 | yes | 2 |
| 4 | 7 | 0 | no | 2 |
| 5 | 0 | -5 | no | 2 |
The answer is 2. Six numbers make 5 rows, because the first number has no row of its own. An array of one number makes no rows at all: the loop does not run, and the answer is 0.
Larger means >. A number equal to the one before it is not larger, so 5, 5 and 5 give 0.
The problems for this step promise at least one number, and "What goes wrong" says what an empty array does to this loop. This step's second problem hands you the loop started one place too early, to mend.
The position of the first negative number, or nil
/// Where the first negative number is, or `nil` when no number is negative.
func positionOfFirstNegative(_ numbers: [Int]) -> Int? {
for i in numbers.indices {
if numbers[i] < 0 {
return i // found: the first one, and the walk is over
}
}
return nil // the last one is through, and none was negative
}This is step 2's loop, asked where and not whether. return true has become return i, and return false has become return nil.
What is new: the answer is a position, and there may be none to give. So the function hands back an Int?, an optional, the kind of value that a dictionary lookup hands back. When a negative number turns up, its position goes back on the spot. When the loop runs out, no number was negative, there is no position, and nil says exactly that.
The loop walks numbers.indices, because a position is what goes back. And it finds the first negative number with no extra work: it starts from the front, and it returns at the first one it meets.
For 4, -2, 0, 7, 0 and -5 the answer is 1. The -5 is never looked at. For -3 and 8 it is 0, which is a real answer: the first position there is. For 3 and 8 it is nil.
Those last two are why "none" cannot be a number. If no negative number were answered with 0, then -3, 8 and 3, 8 would get the same answer. Other languages often answer -1. That is not a position, but it is still an Int, and nothing stops the caller from using it as one. An optional has to be opened first, with if let, and nil will not open.
This step's second problem hands you a version that answers 0 when no number is negative, to mend.
What Swift calls these loops
Each loop in this lesson has a name in Swift. Here they are, on the same six numbers.
let negatives = numbers.filter { $0 < 0 }.count // the counter
let sameCount = numbers.count(where: { $0 < 0 }) // the counter again
let hasZero = numbers.contains(where: { $0 == 0 }) // is there any?
let allArePositive = numbers.allSatisfy { $0 > 0 } // are all?
let firstNegativeAt = numbers.firstIndex(where: { $0 < 0 }) // the position, or nilThey give 2, 2, true, false and 1: what the loops gave.
None of them is magic. Inside the standard library, contains(where:) is a for loop with an if that returns true, and a return false after the loop: step 2, with the test handed in. allSatisfy is written there by way of contains: all of them pass when there is not one that fails, which is step 3. firstIndex(where:) returns the position from inside its loop and nil after it, which is step 6. For an empty array they answer as your loops do: false, true and nil.
The two ways to count are not the same inside. filter builds a new array of the negative numbers, and .count then asks how long it is: an array made only to be measured. count(where:) keeps one number and builds nothing, as your clicker does.
In an app, write Swift's word, because it says what you mean. In a problem the loop is rarely this bare. The test needs the number before, or a total is carried along beside the count, or the count has to stop at a limit, and then Swift has no word for it. The loop is still there. So the problems in this lesson ask for the loops.
What goes wrong
Answering for the whole flock after one sheep. This is "is there any zero?" with an else.
func containsZeroTooSoon(_ numbers: [Int]) -> Bool {
for number in numbers {
if number == 0 {
return true
} else {
return false // wrong: the first number has answered for them all
}
}
return false
}For 0 and 4 it answers true, and it looks fine. For 4 and 0 it answers false: the 4 was not zero, the else returned, and the zero was never looked at. A number that is not zero settles nothing, because a zero may still be on its way. The no belongs after the loop, where every number has been seen.
The wrong answer after the loop. End "is there any zero?" with return true, and for 4 and 7 it answers true: it cries wolf at a flock with no wolf in it. End "are all positive?" with return false, and for 4 and 7 it answers false: it can never say yes at all. The answer after the loop is the opposite of the one inside it, every time.
The empty array. With nothing to walk, each loop gives its start, or the line after it. The count is 0, "is there any zero?" is false, "are all positive?" is true, and the position of the first negative number is nil. The true is the one that surprises. "All" says no only when it can point at one that fails, and here there is nothing to point at. When a problem wants no for an empty array, it has to say so, and you answer before the loop: if numbers.isEmpty { return false }.
Zero on the wrong side. Negative is < 0 and positive is > 0, and zero is neither. Count the negative numbers with <= 0, and the six numbers give 4 where the answer is 2. Ask "are all positive?" as "is none negative?", and 3, 0 and 5 get true where the answer is false.
Starting one place too early. Step 5's test reads numbers[i - 1]. Walk numbers.indices and i begins at 0, where there is no number before. The program stops on its first pass with "Index out of range". Start at 1.
An empty array, when the loop starts at 1. For an empty array 1..<numbers.count is 1..<0. Swift will not build a range that ends before it starts, and the program stops with "Range requires lowerBound <= upperBound". One number is fine: 1..<1 is a range with nothing in it. When a problem does not promise a number, answer the empty array before the loop: if numbers.isEmpty { return 0 }.
A number for "not there". For -3 and 8 the first negative number is at position 0. Answer "no negative number" with 0 as well, and 3 and 8 cannot be told from it. Hand back nil.
Say it back
What does a counter start at, and when can it be read?
Show the answerHide the answer
At zero, because before the first element nothing has been counted. It can be read only after the loop: until the last element is through, the count can still go up.
"Is there any zero?" Which answer goes inside the loop, and which goes after it?
Show the answerHide the answer
return true goes inside, at the first zero, because one zero settles it. return false goes after the loop, because only the end of the array can say there was none. Swift calls this loop contains(where:).
"Are all the numbers positive?" What do you look for, and what does it settle?
Show the answerHide the answer
One number that is not positive: zero or below. It settles the answer as no, so return false is inside the loop and return true waits after it. Swift calls this loop allSatisfy.
What does each loop answer for an empty array?
Show the answerHide the answer
The count is 0, "is there any" is false, "are all" is true, and the first position is nil. Each is the loop's start, or the line after the loop.
You are counting the numbers that are larger than the one before them. Where does the loop start, and why?
Show the answerHide the answer
At position 1. The number at position 0 has no number before it. A loop that starts at 0 stops the program on its first pass.
The position of the first negative number comes back as an optional. Why not as a plain Int?
Show the answerHide the answer
There may be no negative number, and then there is no position to give. nil says so. Any Int could be taken for a position, and 0 is one.
How has every sheep Harper owns won a prize?
Show the answerHide the answer
She owns no sheep. "Have they all won a prize?" is answered no at the first sheep that has not, from inside the loop. Nothing came through the gate, so nothing said no, and the line after the loop said yes. Ask whether any sheep of hers has won a prize, and the same empty field answers no.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | How many are negative? | Easy |
| 2 | The zeros are counted too | Easy |
| 3 | Is there any zero? | Easy |
| 4 | Which numbers were looked at? | Easy |
| 5 | The first number answers for them all | Easy |
| 6 | Are all the numbers positive? | Easy |
| 7 | It never says yes | Easy |
| 8 | How many characters are vowels? | Easy |
| 9 | Larger than the one before | Easy |
| 10 | The first number has none before it | Easy |
| 11 | Where the first negative number is | Easy |
| 12 | It says 0 when there is none | Easy |
These problems are done in the Orithms Mac app.
Every piece of code and every number in a lesson comes from a file that was compiled and run.