Menu
Coddy logo textTech

Weekly Grid

Part of the Logic & Flow section of Coddy's Swift journey — lesson 36 of 56.

It's time to print the calendar. For every habit, render a seven-character grid with X on done days and . elsewhere.

// days = [1, 3, 5]
// renders: X.X.X..

Useful idiom: build the grid as an array of characters, then String-ify it once.

var slots = Array(repeating: ".", count: 7)
for d in days {
    slots[d - 1] = "X"
}
let row = slots.joined()

days is 1-indexed (Mon = 1) but Swift arrays are 0-indexed, so subtract 1 when assigning. Out-of-range days would crash, so trust the input format.

challenge icon

Challenge

Medium

Read a single line of input: a comma-separated list of habit:day entries. Build the dictionary as before, then print one line per habit (sorted alphabetically) in the format:

<habit> |<grid>| <count>

where grid is the seven-character X/. string and count is the number of unique done days for that habit.

For input read:1,read:3,read:5,workout:2,workout:4, the output is:

read |X.X.X..| 3
workout |.X.X...| 2

Cheat sheet

Build a 7-character grid with X on done days and . elsewhere (days are 1-indexed):

var slots = Array(repeating: ".", count: 7)
for d in days {
    slots[d - 1] = "X"
}
let row = slots.joined()

Try it yourself

var habits: [String: [Int]] = [:]
let ops = readLine()!.components(separatedBy: ",")
for op in ops {
    let parts = op.components(separatedBy: ":")
    let day = Int(parts[1])!
    if !(habits[parts[0], default: []].contains(day)) {
        habits[parts[0], default: []].append(day)
    }
}

// TODO: build a 7-slot grid for each habit; print '<name> |<grid>| <count>'
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow