Characters as numbers
A character is not a number, and three conversions get you from one to the other: a letter to its place in the alphabet, a digit to its value, and a number to its characters.
- Reach for it when
- Letters are counted in 26 slots, or digit characters have to become numbers.
- The move
asciiValuegives a letter's number,wholeNumberValuegives a digit's value, andString(n)turns a number back into characters.- Cost
- Each is one step.
The idea
I turned a seven over last night. On the back it said fifty-five.
Then it wasn't a number. Numbers don't have backs.
We'll come back to it. Here is the character "7". Add 1 to it.
I can't. It doesn't compile. A character is a picture of a seven, not a seven.
But it says seven. I can read it.
A photograph of a cake says cake. You still can't eat it.
Then give me a picture I can use.
A box of tiles, the kind you spell words with. Every character is a tile, and its face is what you read. A digit tile will hand you its face as a real number, one you can add to: that is wholeNumberValue, and for "7" it is 7.
And the tile for c? What's that face worth?
Nothing. It's a letter, so wholeNumberValue is nil. Turn it over, though. Every plain tile has a number printed on its back, and the lowercase letters were numbered in order: 97 on a, 98 on b, on to 122 on z. That number is asciiValue.
Who starts counting at 97?
A committee. The numbers before it were taken.
So I take 97 off the back of a letter, and I'm left with…
Its place in the alphabet. 0 for a, 25 for z.
Twenty-six places, 0 to 25. That's an array waiting to happen.
It's a tray with 26 slots. To count the letters of a word, turn each tile over, take off 97, and drop it in the slot with that number. Nobody searches for anything. The tile says where it goes.
And a number like 120? Can I have that in tiles?
String(120) spells it: three tiles, 1, 2 and 0. To read a row of digit tiles back, go left to right. Each tile makes what you have ten times bigger, then adds its face.
Which leaves my seven.
You read the wrong side.
Hold that thought. I'd already put it in the total.
That is the whole tool: a character is not a number, but it carries one on its back, and a digit carries another on its face. The lesson is three conversions: a letter to its place in the alphabet and back, a digit to its value, and a number to its characters and back.
The shape
This is what you know by heart. It counts the letters of a word, and later lessons lean on it more than on anything else here.
/// How many times each letter is in `word`: slot 0 counts a, and slot 25 counts z.
/// `word` holds only the lowercase letters a to z.
func letterCounts(_ word: String) -> [Int] {
var counts = Array(repeating: 0, count: 26) // the tray: 26 slots, all empty
for letter in word {
let place = Int(letter.asciiValue!) - 97 // the back of the tile, less a's 97
counts[place] += 1 // drop the tile in its slot
}
return counts
}Each of its parts is there for a reason.
- The tray.
Array(repeating: 0, count: 26)is 26 zeros: one empty slot for each letter. Slot 0 will count the a's, and slot 25 the z's. - The back of the tile.
letter.asciiValueis the number on the back: 97 for a, 122 for z. Its type isUInt8?. It is optional because only the plain tiles have a number on the back. Plain means it is on an old list of 128 characters called ASCII: the English letters, the ten digits, the space, the usual marks, and some that do not print. A tile such as é is not on it. The!opens the optional by force, which is safe only because the problem promises lowercase English letters. Int(…)before the subtraction. AUInt8runs from 0 to 255 and cannot go below zero, and an index has to be anIntin any case. So the back becomes anIntfirst, and the arithmetic is done there.- Less 97. That is the back of a. Taking it off turns 97 to 122 into 0 to 25: the letter's place in the alphabet, and the number of its slot.
- The drop.
counts[place] += 1puts one more tile in that slot.
The other conversions are one line each. Step by step takes them in turn, and ends at the tray.
Watch it run
The word is cabbage. Each tile is turned over and dropped.
| letter | on its back | place | its slot after |
|---|---|---|---|
| c | 99 | 2 | 1 |
| a | 97 | 0 | 1 |
| b | 98 | 1 | 1 |
| b | 98 | 1 | 2 |
| a | 97 | 0 | 2 |
| g | 103 | 6 | 1 |
| e | 101 | 4 | 1 |
The first seven slots, a to g, end as [2, 2, 1, 0, 1, 0, 1], and the other nineteen are still 0. Look at the fourth row. The second b has the same number on its back as the first, so it lands in the same slot, and the slot goes from 1 to 2. That is all the counting there is. Nothing was searched for: each tile's own back said where it goes.
Step by step
Is this character a digit? A letter?
/// What kind of character this is: "digit", "letter" or "other".
func kind(of character: Character) -> String {
if character.isNumber {
return "digit"
}
if character.isLetter {
return "letter"
}
return "other"
}What is new: a tile can say what kind of face it has. isNumber is true for a digit, and isLetter for a letter. Both come with Swift's Character, with nothing imported. kind(of: "7") is digit, kind(of: "q") is letter, and kind(of: "?") is other.
In a loop the same two questions pick characters out of a text. Keep each character for which character.isLetter || character.isNumber is true, and Room 42, floor 3! becomes Room42floor3.
One more small step, with a problem of its own. What is new: the two questions are generous. They answer for every alphabet and every kind of number. isLetter is true for é. isNumber is true for ½, and for the raised ² of m², so in 10 m² it finds 3 numbers. When a problem promises ASCII, which is plain tiles and nothing else, this never shows. When it does not, and you mean the ten digits 0 to 9, ask as well whether the tile is plain: character.isASCII && character.isNumber. The ten digits are the only numbers among the plain tiles, so that finds 2 in 10 m².
The value of a digit character
/// What a digit is worth: "7" gives 7. `digit` is one of "0" to "9".
func digitValue(_ digit: Character) -> Int {
return digit.wholeNumberValue!
}What is new: wholeNumberValue reads the face of a digit tile as an Int. For "7" it is 7. The back of the same tile is 55: the back says where a tile sits among all the tiles, not what it is worth.
wholeNumberValue is an Int?, because most tiles are not digits: for q it is nil. The ! is right here because the problem promises a digit. When nothing is promised, if let asks "is it a digit?" and takes the value in one line:
/// The sum of the digits in `text`. Every other character is skipped.
func sumOfDigits(_ text: String) -> Int {
var total = 0
for character in text {
if let value = character.wholeNumberValue { // a digit, and what it is worth
total += value
}
}
return total
}For a1b2c3 this gives 6.
wholeNumberValue is generous in the way isNumber is: for a 4 in a circle, ④, it is 4. Among the plain tiles, the only ones it has a value for are the ten digits.
A letter's place in the alphabet
/// Where a lowercase letter is in the alphabet: a is 0, and z is 25.
func place(of letter: Character) -> Int {
return Int(letter.asciiValue!) - 97
}What is new: asciiValue, the number on the back of a tile. The lowercase letters are numbered in order with no gaps: a is 97, c is 99 and z is 122. So a letter's back, less 97, is how far it is past a: 0 for a, 2 for c and 25 for z.
Its type is UInt8?, and each half of that is a trap.
The ?. Only the plain tiles have a number on the back. For é, asciiValue is nil, and ! on that stops the program. So ! is for a problem that promises lowercase English letters, as this step's first problem does.
The UInt8. It holds 0 to 255 and nothing below zero. The back of a capital A is 65. Take 97 from it as an Int and you get -32, an ordinary number that you can test and turn away. Take 97 from it as a UInt8 and there is no such number, so the program stops. That is why the line says Int(…) first and subtracts second.
One more small step. What is new: when nothing is promised, test the place before you trust it.
/// Where `character` is in the alphabet, or nil when it is not one of a to z.
func carefulPlace(of character: Character) -> Int? {
if let number = character.asciiValue { // nil for a tile such as é
let place = Int(number) - 97 // may be below 0, or above 25
if place >= 0 && place < 26 {
return place
}
}
return nil
}It gives 2 for c, and nil for a capital C and for é. This step's second problem hands you this function with one line that stops the program, to mend.
The digit tiles are numbered in order too, from 48 for "0", which is why the back of "7" is 55. So a digit's back, less 48, is its value. wholeNumberValue gives the same answer with no number to remember.
The letter for a place
/// The lowercase letter at a place in the alphabet: 0 gives a, and 25 gives z.
func letter(at place: Int) -> Character {
return Character(UnicodeScalar(UInt8(97 + place)))
}What is new: the way back, from a number to its tile. Read it from the inside out. 97 + place is the number for the back. UInt8(…) makes it the kind of number a back is. UnicodeScalar(…) finds the character with that number, and Character(…) hands it over as a tile. letter(at: 2) is c, and letter(at: 25) is z.
The UInt8(…) has a job. Every UInt8 is the number of some character, so UnicodeScalar always finds one. Hand it an Int and it gives back an optional, because most large numbers belong to no character, and the line does not compile.
In a loop over the places 0, 1, 2 and so on, appending each letter to a string, it spells the alphabet: five places give abcde.
The characters of a number
/// The characters that spell `number`: 120 gives "1", "2", "0".
func characters(of number: Int) -> [Character] {
return Array(String(number))
}What is new: String(number) spells a number in tiles, and Array(…), from the lesson "A string as an array of characters", sets them out one to a position. For 120 this gives ["1", "2", "0"]: 3 characters, and not one of them is a number yet. Loop over them, read each face with step 2's digit.wholeNumberValue!, and you have the digits as numbers: [1, 2, 0].
The problems for this step promise a number that is 0 or more, because a minus sign is a tile too. -45 spells as ["-", "4", "5"], and the face of "-" is worth nil.
A number from its digit characters, multiplying by ten as you go
/// The number that a string of digits spells: "120" gives 120.
func readNumber(_ digits: String) -> Int {
var number = 0
for digit in digits {
number = number * 10 + digit.wholeNumberValue! // one column left, then add
}
return number
}What is new: the line number = number * 10 + …. The tiles are read from the left. Each one pushes what you have one column to the left, which is times ten, and then adds its own face. Here it is for 120:
| digit | number before | times ten | plus the digit |
|---|---|---|---|
| 1 | 0 | 0 | 1 |
| 2 | 1 | 10 | 12 |
| 0 | 12 | 120 | 120 |
It gives 120: step 5 undone. number starts at 0, and ten times 0 is 0, so the first tile needs no special case.
Leave the ten out and the faces are only added up: 3. One of this step's problems hands you that version to mend, and another asks for the last column of the table.
Swift does all of this in one call, Int("120"), and in an app that is what you would write. Problems make you do it by hand because the digits arrive one at a time, in among other characters. Then step 2's if let goes round the line:
/// The number in `text`, read from its digits alone: "1,200" gives 1200.
func readNumber(in text: String) -> Int {
var number = 0
for character in text {
if let value = character.wholeNumberValue { // a digit: one column left, add
number = number * 10 + value
}
}
return number
}For 1,200 this gives 1200. The comma has no value on its face, so it is skipped.
The largest Int has 19 digits. A string of 18 digits always fits in one, and the problems promise no more than that. The lesson "Whole-number arithmetic" has what happens to a number that does not fit.
Count each letter of a word into an array of 26 slots
This step is the shape itself, written from an empty function. Its loop and its place are old. What is new: the tray, an array in which the position means a letter.
It is three moves.
- Make the tray.
var counts = Array(repeating: 0, count: 26). Nothing in it says "letter". The meaning is in the positions: slot 0 is for a, slot 1 for b, and slot 25 for z. - Find the slot.
let place = Int(letter.asciiValue!) - 97, which is step 3. - Drop the tile.
counts[place] += 1.
Say the sentence that stays true as the loop runs: each slot holds how many times its letter has been met so far. It is true before the loop, when no letter has been met and every slot holds 0. Each drop keeps it true. So at the end the tray holds the count of every letter.
For cabbage the tray has 26 slots. To ask it about one letter, go in by that letter's place: counts[place(of: "b")] is 2.
The slots are in the order of the alphabet. So a walk along the tray meets the letters in order, and step 4 turns each place back into its letter:
/// The letters `word` uses, each once, in the order of the alphabet.
func lettersUsed(_ word: String) -> String {
let counts = letterCounts(word)
var used = ""
for place in counts.indices { // walk the tray from slot 0
if counts[place] > 0 {
used.append(letter(at: place)) // a place, back into its letter
}
}
return used
}For cabbage this gives abceg.
Every ! in this lesson rests on a promise. The shape's is that the word holds only the lowercase letters a to z. When a text may hold anything, step 3's careful place goes in the loop, and a tile with no place has no slot:
/// How many times each lowercase letter is in `text`. Every other character is skipped.
func letterCounts(in text: String) -> [Int] {
var counts = Array(repeating: 0, count: 26)
for character in text {
if let place = carefulPlace(of: character) { // nil: not a to z, so no slot
counts[place] += 1
}
}
return counts
}For Dad, a cab! the first four slots are [3, 1, 1, 1]. The capital D, the comma, the spaces and the exclamation mark are not counted.
This step has six problems: one missing line of the shape, the shape from nothing, the last two columns of the table in "Watch it run", a mend, and these two uses.
What goes wrong
Reading the back when you wanted the face. The back of "7" is 55, and its face is worth 7. asciiValue is for a letter's place, and wholeNumberValue is for a digit's value.
Subtracting before Int(…). Int(number - 97) subtracts in UInt8, and for any tile that comes before a, such as a capital, a digit or a space, the program stops. Written Int(number) - 97, a capital A gives -32, which the careful place turns away.
! with no promise. asciiValue is nil for é, and wholeNumberValue is nil for q. With no promise of lowercase letters, or of digits, open the optional with if let.
A tray that does not fit. Take 96 off where 97 was meant, and a, b and c land in slots [1, 2, 3]: every letter is one slot late. Make 25 slots where 26 were meant, and the last is slot 24. Either way there is no slot for z, and the program stops. If you forget the 97, Character("a").asciiValue will tell you.
= 1 where += 1 was meant. That marks a slot as used and forgets how many times: for abba the first two slots come out as [1, 1], where they should be [2, 2].
Trusting isNumber with any text. It is true for ½, whose wholeNumberValue is nil. For the ten digits, ask isASCII as well.
Forgetting the ten. Without * 10, the digits of 120 add up to 3.
Say it back
Why can you not add 1 to the character "7"?
Show the answerHide the answer
It is a character, not a number: a tile with a seven on its face. A tile has to be turned into a number before any arithmetic.
Which property gives a digit's value, and what does it give for a letter?
Show the answerHide the answer
wholeNumberValue. It is an Int?: 7 for "7", and nil for a letter.
What is the type of asciiValue, and what does each half of that type make you do?
Show the answerHide the answer
UInt8?. The ? makes you open it: with ! when the problem promises lowercase letters, and with if let when it does not. The UInt8 makes you write Int(…) before you subtract, because it cannot go below zero.
How do you get a lowercase letter's place, and how do you get the letter back?
Show the answerHide the answer
Int(letter.asciiValue!) - 97 is the place. Character(UnicodeScalar(UInt8(97 + place))) is the letter.
How do you get the characters of 120, and how do you read them back into a number?
Show the answerHide the answer
Array(String(120)). To read them back, start at 0 and take the digits from the left: number = number * 10 + digit.wholeNumberValue!.
How many slots has the tray, and which slot does a letter go in?
Show the answerHide the answer
26, made with Array(repeating: 0, count: 26). A letter goes in the slot of its place, and counts[place] += 1 drops it there.
Why did the seven say fifty-five when Harper turned it over?
Show the answerHide the answer
It was the character "7", a tile. The back of a tile is its asciiValue, and for "7" that is 55. What the tile is worth is on its face: wholeNumberValue, which is 7. A character is never a number. It carries one on its back and sometimes one on its face, and you ask for the one you mean.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | Digit, letter or other | Easy |
| 2 | Keep the letters and the digits | Easy |
| 3 | A half is not a digit | Easy |
| 4 | What a digit is worth | Easy |
| 5 | Add up the digits in a text | Easy |
| 6 | A letter's place in the alphabet | Easy |
| 7 | A capital stops the program | Easy |
| 8 | The letter for a place | Easy |
| 9 | The first letters of the alphabet | Easy |
| 10 | The characters of a number | Easy |
| 11 | The digits of a number, as numbers | Easy |
| 12 | A number from its digit characters | Easy |
| 13 | The number after each digit | Easy |
| 14 | A hundred and twenty comes out as three | Easy |
| 15 | A number with commas in it | Easy |
| 16 | Drop each letter in its slot | Easy |
| 17 | Count each letter of a word | Easy |
| 18 | Which slot, and how many now? | Easy |
| 19 | Two of each, counted once | Easy |
| 20 | The letters a word uses, in order | Easy |
| 21 | Count the letters of a sentence | 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.