Start learning free

LESSON 628 OF 639 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Ticket Booking in Go

Practice O(1)

You build the struct Event. An event has a name and a number of free seats.

Write these, as the Errors and Exceptions lesson does in Go:

  • NewEvent(name, seats) returns an Event with seats free seats.
  • Name is an exported field, so any code can read it.
  • The seats left are an unexported field, seatsLeft.
  • book(n) books n seats. It returns two values: the seats left and an error.
  • When the booking works, the error is nil.
  • When it fails, book returns 0 and an error made with errors.New.

A booking can fail. Then book returns an error with a message, and nothing changes.

  • When n is 0 or less, the message is "invalid number".
  • When n is more than the seats left, the message is "sold out".

The input lists the bookings of each event, in order. The tests call book and check its error. For each event they print its name. Then they print one line per booking:

  • booked 2, 3 left when 2 seats were booked and 3 are left.
  • error: sold out when the booking failed with the message "sold out".

 

Example 1:

Input:
    NewEvent("Concert", 5)
    book(2)
    book(4)
    book(3)
Output:
Concert
booked 2, 3 left
error: sold out
booked 3, 0 left

Explanation:
2 seats are booked, so 3 are left.
4 is more than 3, so the error is "sold out".
The failed booking changed nothing.
So book(3) gets the last 3 seats.

Example 2:

Input:
    NewEvent("Play", 4)
    book(-1)
    book(4)
Output:
Play
error: invalid number
booked 4, 0 left

Explanation:
No one can book -1 seats.
book(4) then takes all 4 seats.

Example 3:

Input:
    NewEvent("Match", 0)
    book(0)
Output:
Match
error: invalid number

Explanation:
The event has no seats at all.
Booking 0 seats is never valid, so the error is "invalid number".

 

Constraints:

  • Each event has 0 to 100,000 seats.
  • Each n is a whole number from -100 to 100,000.
  • An event gets 1 to 1,000 bookings.
  • Event names are one word of English letters.
STEP 1 OF 6
    Ctrl + Enter to check

    Ticket Booking in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free