Question

IN C# The fun for today is to build your own circular array to support a...

IN C#

The fun for today is to build your own circular array to support a queue.

The challenge here is in adjusting your queueFront and queueRear markers (they are just integer array indices), and dealing with what happens when they wrap around the First/last element of the array.

The tricky part here is worrying about the edge cases.

There are only two methods you need to fix up

addBack – this should correctly add an item at the rear of the queue without overwriting any other elements, and then correctly update the queueRear Index

removeFront should remove the first element of the Array (note that I give you code on how to a basic case)

The advanced problem is to figure out when and how to grow the array, if at all.

Here is the code:

public class CircularArray<T>
{
private T[] array;
private int queueFront;
private int queueRear;
// Basic Constructor
// Creates an array and initializes the front and rear
// O(1) in time O (N) in size
public CircularArray(int size)
{
array = new T[size + 1];
queueFront = 0;
queueRear = 0;
}
// NYI fully.  
public void addBack(T value) //addBack is enqueue
{

array[queueRear] = value;
queueRear++;// Also inadequate

}
//Also NYI fully
// Note that I've made it return the value being removed, that's not strictly required but makes the most sense.
public T removeFront() //removeFront is dequeue
{
//Right now calling this on an empty queue will crash
T sample = array[queueFront];
// Because technically T could be not nullable we need to use default(T), which is null.  
array[queueFront] = default(T);
queueFront++; // this is inadequate, need to watch wraparound
return sample;
}

// Just returns the front element O(1)
public T getFront()
{
//Calling this on an empty queue will probably crash too
return array[queueFront];
}
// Same old Grow, bit hard to know where to use it if at all though...
// O(N)
public void grow(int newsize)
{
Array.Resize(ref array, newsize);
}

}

class Program
{
static void Main(string[] args)
{
CircularArray<String> Demo;
int numelemnts = 10;
Demo = new CircularArray<String>(numelemnts);

Demo.addBack("Richard");
String deleted = Demo.removeFront();
Console.WriteLine("The following was just removed: " + deleted);
//Demo.removeFront(); works by itself on a line, the result just doesn't go anywhere.  
Demo.addBack("Brian");
Demo.addBack("Bonnie");
Demo.addBack("Sabine");
Demo.addBack("Jamie");
Demo.addBack("Wenying");
Demo.addBack("Omar");

Console.WriteLine(Demo.getFront());
Console.ReadLine();

}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1
using System;

class MainClass {
  public static void Main (string[] args) {
        CircularArray<String> Demo;
        int numelemnts = 3;
        Demo = new CircularArray<String>(numelemnts);

        Demo.addBack("Richard");
        String deleted = Demo.removeFront();
        Console.WriteLine("The following was just removed: " + deleted);

        //Demo.removeFront(); works by itself on a line, the result just doesn't go anywhere.  
        Demo.addBack("Brian");
        Demo.addBack("Bonnie");

        Console.WriteLine(Demo.removeFront());
        Console.WriteLine(Demo.removeFront());

        Demo.addBack("Sabine");
        Demo.addBack("Jamie");
        Demo.addBack("Wenying");
        Demo.addBack("Omar");

        Console.WriteLine(Demo.removeFront());
        Console.WriteLine(Demo.removeFront());
        Console.WriteLine(Demo.removeFront());
        Console.WriteLine(Demo.removeFront());

  }
}


///////////////////////////////////////////////

using System;

public class CircularArray<T>
{
        private T[] array;
        private int queueFront;
        private int queueRear;

        // Basic Constructor
        // Creates an array and initializes the front and rear
        // O(1) in time O (N) in size
        public CircularArray(int size)
        {
                array = new T[size];
                queueFront = -1;
                queueRear = -1;
        }

        public void addBack(T value) //addBack is enqueue
        {
                int size = array.Length;
                if ((queueFront == 0 && queueRear == size-1) ||
                        (queueRear == (queueFront-1)%(size-1))) {
                        //Queue is Full
                        grow(2 * size);
                        addBack(value);
                        return;
                } else if(queueFront == -1) {
                        // empty queue
                        queueFront = queueRear = 0;
                        array[queueRear] = value;
                }  else if(queueRear == size-1 && queueFront != 0) {
                        queueRear = 0;
                        array[queueRear] = value;
                }  else {
                        queueRear += 1;
                        array[queueRear] = value;
                }
        }

        //Also NYI fully
        // Note that I've made it return the value being removed, that's not strictly required but makes the most sense.
        public T removeFront() //removeFront is dequeue
        {
                if(queueFront == -1) {
                        return default(T);
                }
                T data = array[queueFront];

                if(queueFront == queueRear) {
                        // single element
                        queueFront = -1;
                        queueRear = -1;
                } else if (queueFront == array.Length-1) {
                        queueFront = 0;
                } else {
                        queueFront++;
                }
                return data;
        }

        // Just returns the front element O(1)
        public T getFront()
        {
                if(queueFront != -1) {
                        return array[queueFront];
                } else {
                        return default(T);
                }
        }

        // Same old Grow, bit hard to know where to use it if at all though...
        // O(N)
        public void grow(int newsize)
        {
                T[] newArray = new T[newsize];
                int count = 0;

                if (queueRear >= queueFront) {
                        for (int i = queueFront; i <= queueRear; i++) {
                                newArray[count++] = array[i];
                        }
                } else {
                        for (int i = queueFront; i < array.Length; i++) {
                                newArray[count++] = array[i];
                        }
                        for (int i = 0; i <= queueRear; i++) {
                                newArray[count++] = array[i];
                        }
                }

                if(count == 0) {
                        queueFront = queueRear = -1;
                } else {
                        queueFront = 0;
                        queueRear = count - 1;
                }

                array = newArray;
        }

}

Mono C# compiler version 4.0.4.0 share saved CircularArray.cs 35 The following was just removed: Richard Brian Bonnie SabineHi. please find the answer above.. i have given comments so that it is very easy for you to understand the flow. In case of any doubts, please ask in comments. If the answer helps you, please upvote. Thanks!

Add a comment
Know the answer?
Add Answer to:
IN C# The fun for today is to build your own circular array to support a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I’m giving you code for a Class called GenericArray, which is an array that takes a...

    I’m giving you code for a Class called GenericArray, which is an array that takes a generic object type. As usual this is a C# program, make a new console application, and for now you can stick all of this in one big file. And a program that will do some basic stuff with it Generic Array List What I want you to do today: Create methods for the GenericArray, Easy(ish): public void Append (T, value) { // this should...

  • //Look for** to complete this program --C+ please --please add comments // using namespace std; #include...

    //Look for** to complete this program --C+ please --please add comments // using namespace std; #include <iostream> #include <stdlib.h> #include < string> #include "queue.h" //Purpose of the program: ** Algorithm: * int main() /** "A", "B", "C" in the queue //** while loop -- indefinitely { try {//** catches } //* end of loop } |/ II II II II II //File type: ** queue.cpp using namespace std; #include <iostream> #include "queue.h" // constructor queue::queue () } //destructor queue::~queue() queue::queue...

  • Build and use your own minimal queue class using an array of type String of fixed...

    Build and use your own minimal queue class using an array of type String of fixed size to hold the queue. The array should have the default size of 5. The array size should be setable via a constructor. The following methods must be implemented: enqueue – inserts a value at the rear of the queue dequeue – returns the value at the front of the queue, removing the value from the queue isEmpty – returns true if the queue...

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

  • (C++) (VISUAL STUDIO) Circular Queue is a linear data structure in which the operations are performed...

    (C++) (VISUAL STUDIO) Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. In a normal Queue, we can insert elements until queue becomes full. But once queue becomes full, we cannot insert the next element even if there is a space in front of queue. Efficiently implement a queue class using a circular...

  • +array:int[] This is provided to facilitate testing and grading. Use it as your internal array. +size:int...

    +array:int[] This is provided to facilitate testing and grading. Use it as your internal array. +size:int i.e. after items are added to the array, or deleted from it. One default constructor (receives nothing and initializes an array of size 0), and another constructor that receives an int[] and initializes the internal array with the input parameter. both of the constructors exist and work fine. In initializing the internal array with the input parameter, you should make a copy of the...

  • Assuming you have the following ordered-array class definition: class ordered_array { public: ordered_array(int c) { data...

    Assuming you have the following ordered-array class definition: class ordered_array { public: ordered_array(int c) { data = new int[c]; cp = c; sz = 0; } ... private: int sz, cp; // Current size, total capacity int* data = nullptr; }; Suppose that ordered_arrays can contain duplicates. Implement a method remove_duplicates(e)which takes an element e and removes it and any duplicates of it. (Note that e is the actual value to be removed, not its index in the array.) If...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • Hello! I have a problem in my code please I need help, I don't know How I can wright precondition, so I need help about assertion of pre_condition of peek. Java OOP Task is! Improve the circular a...

    Hello! I have a problem in my code please I need help, I don't know How I can wright precondition, so I need help about assertion of pre_condition of peek. Java OOP Task is! Improve the circular array implementation of the bounded queue by growing the elements array when the queue is full. Add assertions to check all preconditions of the methods of the bounded queue implementation. My code is! public class MessageQueue{ public MessageQueue(int capacity){ elements = new Message[capacity];...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT