roll a die 20 times and print any adjacent repeated rolls in parentheses in swift

main.swift
var rolls = [Int]()

// roll the die 20 times and store the results in an array
for _ in 1...20 {
    let roll = Int.random(in: 1...6)
    rolls.append(roll)
}

// print the rolls and add parentheses around any adjacent repeated rolls
for i in 0..<rolls.count {
    if i > 0 && rolls[i] == rolls[i-1] {
        print("(\(rolls[i]))", terminator: "")
    } else {
        print(rolls[i], terminator: "")
    }
    print(" ", terminator: "")
}
442 chars
18 lines

Explanation:

  • We start by creating an empty array to store the results of the die rolls.

  • We then use a loop to roll the die 20 times and append the result to the array.

  • Next, we loop through the array and print each roll. If the current roll is the same as the previous roll, we add parentheses around it.

  • The terminator parameter is used to specify what should be printed after each roll. By default it is a new line, but we set it to a space so the printed rolls are separated by spaces instead.

gistlibby LogSnag