Last active
January 20, 2022 10:27
-
-
Save AlexAvlonitis/1c4429ae2769be2b796398b1ef8cdde3 to your computer and use it in GitHub Desktop.
Elevator Algorithm in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Continue traveling in the same direction while there are remaining requests in that same direction. | |
# If there are no further requests in that direction, then stop and become idle, | |
# or change direction if there are requests in the opposite direction. | |
require 'set' | |
class Elevator | |
attr_reader :floors_up, :floors_down | |
attr_accessor :direction, :current_floor | |
def initialize(elevator_rules = [ElevatorRule.new]) | |
@elevator_rules = elevator_rules | |
@current_floor = 3 | |
@direction = :up | |
@floors_up = SortedSet.new | |
@floors_down = SortedSet.new | |
end | |
def press_floor(floor) | |
return if current_floor == floor | |
current_floor > floor ? @floors_down << floor : @floors_up << floor | |
puts "floors: #{floors_down + floors_up}" | |
end | |
def next_floor | |
@elevator_rules.each { |rule| rule.apply(self) } | |
end | |
end | |
class ElevatorRule | |
def apply(elevator) | |
@elevator = elevator | |
return 'No floors to go' if @elevator.floors_down.empty? && @elevator.floors_up.empty? | |
set_elevator_direction! | |
set_current_floor! | |
end | |
private | |
def set_elevator_direction! | |
@elevator.direction = :up if @elevator.floors_up.any? && @elevator.floors_down.empty? | |
@elevator.direction = :down if @elevator.floors_up.empty? && @elevator.floors_down.any? | |
end | |
def set_current_floor! | |
if @elevator.direction == :up | |
next_floor = @elevator.floors_up.min | |
@elevator.current_floor = next_floor | |
@elevator.floors_up.delete(next_floor) | |
elsif @elevator.direction == :down | |
next_floor = @elevator.floors_down.max | |
@elevator.current_floor = next_floor | |
@elevator.floors_down.delete(next_floor) | |
end | |
puts "current_floor: #{@elevator.current_floor}" | |
end | |
end | |
e = Elevator.new | |
e.press_floor(1) | |
e.press_floor(3) | |
e.press_floor(5) | |
e.press_floor(8) | |
e.next_floor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment