This exercise was given to me recently. It represents an elevator. You call the elevator with a param of values, and the elevator comes to you stopping at each floor you’ve told it to. There are actually hundreds of hangups on this problem and hopefully I will gain more time to extend this example more effectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
def elevator( command )
  # create a random starting point for the elevator
  current_level = rand( 100 )
  if current_level == command.first
  # same floor   
    puts "current level is #{current_level} and elevator is on #{current_level}"
    return
  elsif command.length == 1 
  # single selections  
    if current_level < command.first
      puts "current level is #{current_level}, go up to #{command}"
    else
      puts "current level is #{current_level}, go down to #{command}"  
    end
  else
  # multiple selections  
    first_button = command.first
    if current_level < first_button
      command.sort!
      adjusted = command.select { |v| v < first_button && v > current_level }
      adjusted << first_button
      puts "current level is #{current_level}, elevator go up to #{adjusted.inspect}"
    else
      command.sort!
      adjusted = command.select { |v| v > first_button && v < current_level }
      adjusted << first_button
      adjusted.sort!  {|x,y| y <=> x }
      puts "current level is #{current_level}, elevator go down to #{adjusted.inspect}"
    end 
  end
end
 
# puts elevator([40])
puts elevator([50, 4, 5, 60, 75, 21, 48, 32, 12, 90])

Leave a Reply

Your email address will not be published. Required fields are marked *