From dbfae330743f8a1350de7f6863ac1a3980c90cc9 Mon Sep 17 00:00:00 2001 From: Speiger Date: Sun, 26 Dec 2021 00:08:19 +0100 Subject: [PATCH] Fixed Bug with FIFOQueue performance --- .../templates/queues/ArrayFIFOQueue.template | 7 ++++--- .../ints/base/BaseIntPriorityQueueTest.java | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/builder/resources/speiger/assets/collections/templates/queues/ArrayFIFOQueue.template b/src/builder/resources/speiger/assets/collections/templates/queues/ArrayFIFOQueue.template index 6e0fc2c0..05cb2714 100644 --- a/src/builder/resources/speiger/assets/collections/templates/queues/ArrayFIFOQueue.template +++ b/src/builder/resources/speiger/assets/collections/templates/queues/ArrayFIFOQueue.template @@ -82,7 +82,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K */ public ARRAY_FIFO_QUEUE(int capacity) { if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative"); - array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity)); + array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity+1)); minCapacity = array.length; } @@ -133,7 +133,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K #if TYPE_OBJECT array[first] = null; #endif - first = ++first % array.length; + if(++first == array.length) first = 0; reduce(); return data; } @@ -153,7 +153,8 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K @Override public KEY_TYPE peek(int index) { if(first == last || index < 0 || index > size()) throw new NoSuchElementException(); - return array[(first + index) % array.length]; + index += first; + return index > array.length ? array[index-array.length] : array[index]; } @Override diff --git a/src/test/java/speiger/src/collections/ints/base/BaseIntPriorityQueueTest.java b/src/test/java/speiger/src/collections/ints/base/BaseIntPriorityQueueTest.java index ec65be31..6e53787e 100644 --- a/src/test/java/speiger/src/collections/ints/base/BaseIntPriorityQueueTest.java +++ b/src/test/java/speiger/src/collections/ints/base/BaseIntPriorityQueueTest.java @@ -82,6 +82,24 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest } } + @Test + public void testUnorderedPeek() { + EnumSet valid = getValidPriorityQueueTests(); + if(valid.contains(PriorityQueueTest.IN_OUT) && valid.contains(PriorityQueueTest.PEEK) && !isUnsortedRead()) { + IntPriorityQueue queue = create(EMPTY_ARRAY); + for(int i = 0;i<100;i++) { + queue.enqueue(i); + } + for(int i = 0;i<25;i++) { + queue.dequeue(); + queue.enqueue(i); + } + for(int i = 0;i<100;i++) { + Assert.assertEquals((i+25) % 100, queue.peek(i)); + } + } + } + @Test @SuppressWarnings("deprecation") public void testToArray() {