Data Structures & Algorithms in Swift · Challenge: Queue | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/977854-data-structures-algorithms-in-swift/lessons/6

Hey, just a very small comment on this challenge. Although it should be obvious from the context, the players take turns in rounds. In other words, once the last player has taken a turn, it’s the first player’s turn again. If you miss this point (as I initially did :grinning:) and write a naive implementation of nextPlayer() like this

@discardableResult
mutating func nextPlayer() -> T? {
    return dequeue()
}

the test_playerOrder() unit test as currently written will still pass. To test whether the implementation really works and has players going in rounds, a few lines should be added to the bottom of it, something like this.

func test_playerOrder() {
    var queue = QueueStack<String>()
    queue.enqueue("Kirby")
    queue.enqueue("Samus")
    queue.enqueue("Pikachu")
    queue.enqueue("Toon Ozma")
    
    XCTAssertEqual(queue.peek, "Kirby")
    queue.nextPlayer()
    queue.nextPlayer()
    XCTAssertEqual(queue.peek, "Pikachu")
    queue.nextPlayer()
    XCTAssertEqual(queue.peek, "Toon Ozma")
    // Add this check that we go back to the first player.
    queue.nextPlayer()
    XCTAssertEqual(queue.peek, "Kirby")
  }
2 Likes

That’s a great observation about the test! Thanks so much for sharing. :]

Also, I don’t think we explicitly said that nextPlayer() had to account for multiple rounds of a game, so your implementation is totally valid for a game that consists of one round! :joy_cat: