andrey
andrey

Reputation: 681

How to work with a queue

I have implemented a queue in C. I can add and remove elements. Now I have to implement a function which compares each new element with the sum of the latest 86 elements in the queue. For example, each of first n elements, n <= 86, I compare to the sum of first n-1 elements, but 87th element I have to compare with sum of latest 86 elements. How could I manage this?

Can you give me some directions on how I should think (maybe some reading or something)? I just want to understand this kind of thing.

Thanks.

Upvotes: 0

Views: 159

Answers (1)

Wyzard
Wyzard

Reputation: 34563

If I understand correctly, you want to add 430 items to a queue, and you want to compare each new item with the sum of the 86 "most recent" items in the queue, but ignore older items in the queue.

What I'd do is keep a running total and add to it each time you add an item to the queue, but also use a separate queue that'll keep track of the last 86 items added to the real one. While adding the first 86 item, you'll basically have two copies of the queue. For the 87th and subsequent items, you'll remove the oldest item from the "newest 86" queue and subtract its value from the running total.

Upvotes: 1

Related Questions