Last active
April 19, 2023 20:02
-
-
Save woodRock/5effd6fa0a38e6c6596b667b6a76358d to your computer and use it in GitHub Desktop.
You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API: record(order_id): adds the order_id to the log get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N. You should be as efficient with time and space…
This file contains hidden or 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
#!/usr/bin/env ruby | |
class Log | |
def initialize(log=["1","2","3","4"]) | |
@log = log | |
end | |
def size | |
return @log.length | |
end | |
def record(order_id) | |
if order_id.respond_to?("each") | |
order_id.each do |o| | |
@log << o | |
end | |
else | |
@log << order_id | |
end | |
end | |
def get_last(i) | |
if i>size() || i<1 | |
puts "Index Invalid!" | |
return | |
end | |
return @log.slice(size()-i,size()) | |
end | |
end | |
l = Log.new() | |
l.record("5") | |
puts l.get_last(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment