logo CodeStepByStep logo

GameOfFlights

Write a method named GameOfFlights that processes a file of seats on an airplane and models where the passengers will choose to sit. Your method accepts as its parameter a string representing the name of a file of seat data. Your code should model the behavior of passengers sitting in the various seats according to rules that will be described below until the arrangement becomes stable, then return the number of occupied seats.

The seat layout fits neatly on a grid. Each position on the grid is either a floor (.), an empty seat (L), or an occupied seat (#). For example, suppose the file named seats.txt contains the following text:

L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL

Passengers follow a simple set of rules based on the number of occupied seats adjacent to a given seat (one of the eight positions immediately up, down, left, right, or diagonal from the seat). The following rules are applied to every seat simultaneously:

  • If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied.
  • If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty.
  • Otherwise, the seat's state does not change.
  • Floor (.) never changes; seats don't move, and nobody sits on the floor.

After one round of these rules, every seat in the example layout becomes occupied:

#.##.##.##
#######.##
#.#.#..#..
####.##.##
#.##.##.##
#.#####.##
..#.#.....
##########
#.######.#
#.#####.##

After a second round, the seats with four or more occupied adjacent seats become empty again:

#.LL.L#.##
#LLLLLL.L#
L.L.L..L..
#LLL.LL.L#
#.LL.LL.LL
#.LLLL#.##
..L.L.....
#LLLLLLLL#
#.LLLLLL.L
#.#LLLL.##

This process continues for three more rounds:

#.##.L#.##
#L###LL.L#
L.#.#..#..
#L##.##.L#
#.##.LL.LL
#.###L#.##
..#.#.....
#L######L#
#.LL###L.L
#.#L###.##
#.#L.L#.##
#LLL#LL.L#
L.L.L..#..
#LLL.##.L#
#.LL.LL.LL
#.LL#L#.##
..L.L.....
#L#LLLL#L#
#.LLLLLL.L
#.#L#L#.##
#.#L.L#.##
#LLL#LL.L#
L.#.L..#..
#L##.##.L#
#.#L.LL.LL
#.#L#L#.##
..L.L.....
#L#L##L#L#
#.LLLLLL.L
#.#L#L#.##

At this point, the seating arrangement stabilizes and no seats change state on any further iterations. At this point there are 37 occupied seats. So the call of GameOfFlights("seats.txt") should return 37.

You may assume that the file exists and is readable, that it follows the format described above, that there will be at least one line of input in the file, and that the file will eventually stabilize if the rules described here are followed properly.

(This exercise is based on the Advent of Code 2020, day 11.)

Method: Write a C# method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.