Reputation: 7832
I'm writing a "bot" that will have a list of predefined actions and, while processing each action, the action code will be able to add more actions to the queue, as something to be processed next (not on the end).
Say I will start the queue with actions A, B and C and while processing B it adds B1 and B2 that need to be processed before C. Leaving the final order of processed actions as A B B1 B2 C.
A normal FIFO queue won't cut it because items can only be added to the end of the queue.
A normal LIFO stack won't do either, I believe.
What would you use for this scenario?
Upvotes: 1
Views: 120
Reputation: 8646
You can use an array and simply add tasks to the front (unshift
) and taking tasks from the front (shift
)
queue = ["A", "B", "C"]
def process_next_step(queue)
puts "Tasks are #{queue}"
task = queue.shift
puts "Current task is #{task}"
if task == "B"
puts "adding subtasks"
queue.unshift("B1")
queue.unshift("B2")
else
puts "Doing #{task}"
end
end
while !queue.empty?
process_next_step(queue)
end
This will produce
Tasks are ["A", "B", "C"]
Current task is A
Doing A
Tasks are ["B", "C"]
Current task is B
adding subtasks
Tasks are ["B2", "B1", "C"]
Current task is B2
Doing B2
Tasks are ["B1", "C"]
Current task is B1
Doing B1
Tasks are ["C"]
Current task is C
Doing C
Upvotes: 2
Reputation: 81
I would use some sort of tree.
First it goes into A. Checks if A has any leafs if not moves to B. In B it does B and then checks if there are any leafs. Finds B1 and B2. Does B1 and checks to see if B1 has any leafs. Doesn't find any leafs. Does B2. Chekcs if B2 has leafs. Finds none. Does C
You can add processes as leafs as you go and should work for your bot
You could also use a linked list where each process is a node and points to a next process. Can easily add B1 as the next process with B2 as its next and then C as the next process of B2.
Upvotes: 2