Skip to content

Instantly share code, notes, and snippets.

@AlexVKO
Created June 9, 2018 01:36
Show Gist options
  • Save AlexVKO/065dffaca70b0b2c61ff07a8f756007c to your computer and use it in GitHub Desktop.
Save AlexVKO/065dffaca70b0b2c61ff07a8f756007c to your computer and use it in GitHub Desktop.
class Queue
def initialize(max_size: nil)
@head_node = nil
@max_size = max_size
end
def enqueue(element)
if last_node
last_node.next_node = Node.new(element)
else
@head_node = Node.new(element)
end
end
def dequeue
return if head_node.nil?
node_to_be_dequeued = head_node
@head_node = head_node.next_node
node_to_be_dequeued.content
end
def last_node
last_node = @head_node
while last_node && last_node.next_node
last_node = last_node.next_node
end
last_node
end
def first_node
head_node
end
def full?
if max_size.nil?
false
else
size == max_size
end
end
def empty?(*args)
size == 0
end
def many?
size > 1
end
private
attr_accessor :head_node, :max_size
def size
return 0 if head_node.nil?
counter = 1
last = head_node
while last.next_node
counter += 1
last = last.next_node
end
counter
end
end
class QueuesWithSubQueues
SUB_QUEUES_MAX_SIZE = 5
def initialize
@sub_queues = ::Queue.new
generate_new_sub_queue
end
def enqueue(element)
last = last_sub_queue
generate_new_sub_queue if last.full?
last.enqueue(element).content
end
def dequeue
first = first_sub_queue
dequeued = first.dequeue
if first.empty? && @sub_queues.many?
@sub_queues.dequeue
end
dequeued
end
def sub_queues_count
counter = 1
last = @sub_queues.first_node
while last.next_node
counter +=1
last = last.next_node
end
counter
end
private
def generate_new_sub_queue
@sub_queues.enqueue( ::Queue.new(max_size: SUB_QUEUES_MAX_SIZE) )
end
def last_sub_queue
@sub_queues.last_node.content
end
def first_sub_queue
@sub_queues.first_node.content
end
end
class Node
attr_accessor :content, :next_node
def initialize(content)
@content = content
end
end
queue = QueuesWithSubQueues.new
puts "queue.sub_queues_count #{queue.sub_queues_count} "
puts '========='
puts 'Enqueue'
puts queue.enqueue('Alex')
15.times do |n|
puts queue.enqueue(n)
end
puts "queue.sub_queues_count #{queue.sub_queues_count} "
puts '========='
puts 'Dequeue'
17.times do |n|
puts queue.dequeue
end
puts "queue.sub_queues_count #{queue.sub_queues_count} "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment