Skip to content

Commit 974afc5

Browse files
committed
Improving queue code
1 parent d4f4816 commit 974afc5

2 files changed

Lines changed: 35 additions & 5 deletions

File tree

source/code/projects/CQueue/CQueue/CQueue.cs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ class CQueue<T>
55
private int front,
66
end,
77
size;
8+
89
private T[] mArray;
910

1011
public CQueue(int capacity = 10)
@@ -31,11 +32,11 @@ public bool IsFull()
3132
return size == mArray.Length;
3233
}
3334

34-
public void Enqueue(T newItem)
35+
public void Enqueue(T dataP)
3536
{
3637
if (!IsFull())
3738
{
38-
mArray[end] = newItem;
39+
mArray[end] = dataP;
3940
Increment(ref end);
4041
size++;
4142
}
@@ -53,8 +54,8 @@ public T Dequeue()
5354

5455
public void Resize()
5556
{
56-
throw new Exception(
57-
"Queue Resize is not implemented - you could implement it"
57+
throw new NotImplementedException(
58+
"Queue Resize is not implemented."
5859
);
5960
}
6061

@@ -70,6 +71,9 @@ private void Increment(ref int value)
7071
{
7172
value = 0;
7273
}
74+
// This if statement could be replaced
75+
// with
76+
// value %= mArray.Length;
7377
}
7478

7579
public int Capacity
@@ -82,6 +86,7 @@ public override string ToString()
8286
string returned = "";
8387
returned +=
8488
$"Front : {front}, end : {end}, size : {size}, capacity: {Capacity}\n";
89+
// Note how the for is constructed:
8590
for (int i = front; i < size + front; i++)
8691
{
8792
returned += mArray[i % mArray.Length] + ":";

source/lectures/data/queue.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,29 @@ Our implementation can recover the capacity of the queue by using:
7878
```
7979
capacity = mArray.Length - size;
8080
```
81-
.
81+
82+
However, trying to recover the size from the `front` and `end` values is not possible.
83+
One could try, using
84+
85+
```
86+
public int CSize
87+
{
88+
get
89+
{
90+
int csize = 0;
91+
if (front < end) { csize = end - front; }
92+
else if (front == end) { csize = mArray.Length; }
93+
else
94+
{
95+
csize = mArray.Length - front + end;
96+
}
97+
if (csize != size)
98+
{
99+
throw new NotImplementedException("CSize is not correctly implemented!");
100+
}
101+
return csize;
102+
}
103+
}
104+
```
105+
106+
but the exception would be thrown: can you figure out in which case(s) the "computed size" would be incorrect?

0 commit comments

Comments
 (0)