Skip to content

Instantly share code, notes, and snippets.

@sagarbommidi
Created October 23, 2018 11:50
Show Gist options
  • Save sagarbommidi/243244d8c439d53d55598fff15cc45ef to your computer and use it in GitHub Desktop.
Save sagarbommidi/243244d8c439d53d55598fff15cc45ef to your computer and use it in GitHub Desktop.
class Seat
attr_accessor :person
def initialize(position)
@position = position
@person = nil
end
end
class AirPlane
attr_reader :seating_matrix
def initialize(input)
@input = input
@positions = {window: [], aisle: [], middle: []}
@seating_matrix = get_seating_matrix
populate_default_seating
end
def get_seating_matrix
@rows, @cols = 0, 0
@input.each do |arr|
@rows = [arr[0], @rows].max
@cols += arr[1]
end
Array.new(@rows) {Array.new(@cols, -1)}
end
def populate_default_seating
col_index = 0
@input.each_with_index do |arr, i|
(0...arr[1]).each do |col_i|
if (i == 0 && col_i == 0) || (i == (@input.length - 1) && (col_i == arr[1] - 1 ))
position = :window
elsif col_i == 0 || (col_i == arr[1] - 1 )
position = :aisle
else
position = :middle
end
(0...arr[0]).each do |x|
@seating_matrix[x][col_index] = Seat.new(position)
end
@positions[position] << col_index
col_index += 1
end
end
end
def arrange_persons(total)
person_order = 1
[:aisle, :window, :middle].each do |position|
(0...@rows).each do |row|
@positions[position].each do |col|
break if person_order > total
seat = @seating_matrix[row][col]
if seat.kind_of? Seat
seat.person = person_order
person_order += 1
end
end
end
end
end
def print_seating
(0...@rows).each do |row|
puts "-----"
(0...@cols).each do |col|
seat = seating_matrix[row][col]
if seat.kind_of? Seat
print "| #{seat.person} |"
else
print " "
end
end
puts "\n"
end
end
end
input = [ [2, 3], [3, 4], [3, 2], [4, 3] ] # reverse
passengers = 30
plane = AirPlane.new(input)
plane.arrange_persons(30)
plane.print_seating
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment