Question

. You must complete the Vector<T> implementation by providing the following functionality: void Insert(int index, T item) Ins

Expected OUTPUT:

Test A: Create a new vector by calling Vector int> vector = new Vector<int>(50); :: SUCCESS Test B: Add a sequence of numbe

Codes Failed at Test D,E,F.

Needs to be fixed:

public class Vector<T>
{

private const int DEFAULT_CAPACITY = 10;
private T[] data;
public int Count { get; private set; } = 0;


public int Capacity
{
get { return data.Length; }
}

  
public Vector(int capacity)
{
data = new T[capacity];
}

  
public Vector() : this(DEFAULT_CAPACITY) { }


public T this[int index]
{
get
{
if (index >= Count || index < 0) throw new IndexOutOfRangeException();
return data[index];
}
set
{
if (index >= Count || index < 0) throw new IndexOutOfRangeException();
data[index] = value;
}
}


private void ExtendData(int extraCapacity)
{
T[] newData = new T[Capacity + extraCapacity];
for (int i = 0; i < Count; i++) newData[i] = data[i];
data = newData;
}

public void Add(T element)
{
if (Count == Capacity) ExtendData(DEFAULT_CAPACITY);
data[Count++] = element;
}

  
public int IndexOf(T element)
{
for (var i = 0; i < Count; i++)
{
if (data[i].Equals(element)) return i;
}
return -1;
}

public void Insert(int index, T element)
{
if (Count == Capacity) ExtendData(DEFAULT_CAPACITY);
if (index >= Count || index < 0)
throw new NotImplementedException();

int count = Count;
while (count != index)
{
data[count] = data[count - 1];
count--;
}
data[count] = element;
Count++;

}

  

public void Clear()
{
//Clear the array
Array.Clear(data, 0, Count);
Count = 0;
}

public bool Contains(T element)
{
return IndexOf(element) != -1;
}

public bool Remove(T element)
{
if (Contains(element))
{
T[] newArr = new T[Count - 1];
int cnt = 0;
for (int i = 0; i < Count; i++)
{
if (!data[i].Equals(element))
{
newArr[cnt++] = data[i];
}
}
data = newArr;

Count--;
return true;
}
return false;
}

public void RemoveAt(int index)
{
//Throw Index out of range exception
if (index < 0 || index > Count - 1)
throw new IndexOutOfRangeException();

T[] newArr = new T[Count - 1];
int cnt = 0;
for (int i = 0; i < Count; i++)
{
if (i != index)
{
newArr[cnt++] = data[i];
}
}
data = newArr;

Count--;
}

public override string ToString()
{
if (Count == 0)
return "";

string outstr = "[ ";
string comma = ",";
for (int i = 0; i < Count; ++i)
{
if (i == Count - 1)
{
outstr += data[i].ToString();
}
else
{
outstr += data[i].ToString() + comma;
}
}

outstr += " ]";
return outstr;
}
class Program
{
public static void Main(String[] args)
{
Vector<int> vector = new Vector<int>();
vector.Add(1);
vector.Add(2);
vector.Add(3);
vector.Add(4);
Console.WriteLine(vector);
}
}

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

Short Summary:

  • Implemented the methods as per given instructions
  • Implemented a main method to test all the test cases.

Source Code:

Vector.cs File:

using System;

namespace VectorTemplate

{

    public class Vector<T>

    {

        private const int DEFAULT_CAPACITY = 10;

        private T[] data;

        public int Count { get; private set; } = 0;

        public int Capacity

        {

            get { return data.Length; }

        }

        public Vector(int capacity)

        {

            data = new T[capacity];

        }

        public Vector() : this(DEFAULT_CAPACITY) { }

        public T this[int index]

        {

            get

            {

                if (index >= Count || index < 0) throw new IndexOutOfRangeException();

                return data[index];

            }

            set

            {

                if (index >= Count || index < 0) throw new IndexOutOfRangeException();

                data[index] = value;

            }

        }

        private void ExtendData(int extraCapacity)

        {

            T[] newData = new T[Capacity + extraCapacity];

            for (int i = 0; i < Count; i++) newData[i] = data[i];

            data = newData;

        }

        public void Add(T element)

        {

            if (Count == Capacity) ExtendData(DEFAULT_CAPACITY);

           data[Count++] = element;

        }

        public int IndexOf(T element)

        {

            for (var i = 0; i < Count; i++)

            {

                if (data[i].Equals(element)) return i;

            }

            return -1;

        }

        public void Insert(int index, T element)

        {

            // if count equals to Capacity, increase the capacity

            if (Count == Capacity)

            {

                ExtendData(DEFAULT_CAPACITY);

            }

            // if index equals to count, add at the end

            if(index == Count)

            {

                data[Count++] = element;

                return;

            }

            // if index is out of range

            if (index > Count || index < 0)

                throw new IndexOutOfRangeException("Index is out of range: " + index);

            // insert in the middle

            int count = Count;

            while (count != index)

            {

                data[count] = data[count - 1];

                count--;

            }

            data[count] = element;

            Count++;

        }

        public void Clear()

        {

            //Clear the array

            Array.Clear(data, 0, Count);

            Count = 0;

        }

        public bool Contains(T element)

        {

            return IndexOf(element) != -1;

        }

        public bool Remove(T element)

        {

            // Get the index of given element

            int index = IndexOf(element);

            if (index > -1)

            {

                // use RemoveAt method to remove the element

                RemoveAt(index);

                return true;

            }

            return false;

        }

        public void RemoveAt(int index)

        {

            //Throw Index out of range exception

            if (index < 0 || index > Count - 1)

                throw new IndexOutOfRangeException("Index is out of range: " + index);

            T[] newArr = new T[Count - 1];

            int cnt = 0;

            for (int i = 0; i < Count; i++)

            {

                if (i != index)

                {

                    newArr[cnt++] = data[i];

                }

            }

          data = newArr;

            Count--;

        }

        public override string ToString()

        {

            if (Count == 0)

                return "";

            string outstr = "[ ";

            string comma = ",";

            for (int i = 0; i < Count; ++i)

            {

                if (i == Count - 1)

                {

                    outstr += data[i].ToString();

                }

                else

                {

                    outstr += data[i].ToString() + comma;

                }

            }

            outstr += " ]";

            return outstr;

        }

    }

}

Program.cs File:

using System;

namespace VectorTemplate

{

    class Program

    {

        static void Main(string[] args)

        {

            // Test A

            Vector<int> vector = new Vector<int>();

            // Test B

            vector.Add(2);

            vector.Add(6);

            vector.Add(8);

            vector.Add(5);

            vector.Add(5);

            vector.Add(1);

            vector.Add(8);

            vector.Add(5);

            vector.Add(3);

            vector.Add(5);

            Console.WriteLine("After Test B: " + vector);

            // Test c

            vector.Remove(3);

            Console.WriteLine("Remove 3: " + vector);

            vector.Remove(7);

            Console.WriteLine("Remove 7: " + vector);

            vector.Remove(6);

            Console.WriteLine("Remove 6: " + vector);

            // Test D

            try

            {

                vector.Insert(6, 50);

                Console.WriteLine("insert 50 at index 6: " + vector);

            }

            catch(Exception e)

            {

                Console.WriteLine(e.Message);

            }

            try

            {

                vector.Insert(0, 0);

                Console.WriteLine("insert 0 at index 0: " + vector);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

            try

            {

                vector.Insert(vector.Count - 1, 60);

                Console.WriteLine("insert 60 at index vector.Count - 1: " + vector);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

            try

            {

                vector.Insert(vector.Count, 70);

                Console.WriteLine("insert 70 at index vector.Count: " + vector);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

            Console.WriteLine("After Test D: " + vector);

            // Test E

            try

            {

                vector.Insert(vector.Count + 1, -1);

                Console.WriteLine("insert -1 at index vector.Count+1: " + vector);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

            Console.WriteLine("After Test E: " + vector);

            // Test F

            try

            {

                vector.RemoveAt(4);

                Console.WriteLine("Remove at index 4: " + vector);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

            try

            {

                vector.RemoveAt(0);

                Console.WriteLine("Remove at index 0: " + vector);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

            try

            {

                vector.RemoveAt(vector.Count - 1);

                Console.WriteLine("Remove at index count -1: " + vector);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

           

            Console.WriteLine("After Test F: " + vector);

            // Test G

            try

            {

                vector.RemoveAt(vector.Count);

                Console.WriteLine("Remove at index count : " + vector);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

           

            Console.WriteLine("After Test G: " + vector);

            // Test H

            if (vector.Contains(1))

            {

                Console.WriteLine("It contains 1");

            }

            else

            {

                Console.WriteLine("It does not contain 1");

            }

            if (vector.Contains(2))

            {

                Console.WriteLine("It contains 2");

            }

            else

            {

                Console.WriteLine("It does not contain 2");

            }

            if (vector.Contains(4))

            {

                Console.WriteLine("It contains 4");

            }

            else

            {

                Console.WriteLine("It does not contain 4");

            }

            vector.Add(4);

            if (vector.Contains(4))

            {

                Console.WriteLine("It contains 4");

            }

            else

            {

                Console.WriteLine("It does not contain 4");

            }

            // Test I

            Console.WriteLine("Test I: " + vector);

            // Test J

            vector.Clear();

            Console.WriteLine("Test J: " + vector);

            Console.ReadKey();

        }

    }

}

Sample Run:

After Test B: [ 2,6,8,5,5,1,8,5,3,5 ] Remove 3: [ 2,6,8,5,5,1,8,5,5 ] Remove 7: [ 2,6,8,5,5,1,8,5,5 ] Remove 6: [ 2,8,5,5, 1,

******************************************************************************

Feel free to rate the answer and comment your questions, if you have any.

Please upvote the answer and appreciate our time.

Happy Studying!!!

******************************************************************************

Add a comment
Know the answer?
Add Answer to:
Expected OUTPUT: Codes Failed at Test D,E,F. Needs to be fixed: public class Vector<T> { private...
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
  • C# public int IndexOf(T element) { for (var i = 0; i < Count; i++) {...

    C# public int IndexOf(T element) { for (var i = 0; i < Count; i++) { if (data[i].Equals(element)) return i; } return -1; } You must complete the Vector<T> implementation by providing the following functionality: void Insert(int index, T item) Inserts a new element into the data structure at the specified index. This will involve four parts (Note a part may be more than a single line of code): o If Count already equals Capacity (eg the currently allocated space...

  • JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final...

    JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final int DEFAULT_CAPACITY = 2;   //default initial capacity / minimum capacity    private T[] data;   //underlying array    // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!       @SuppressWarnings("unchecked")    public SmartArray(){        //constructor        //initial capacity of the array should be DEFAULT_CAPACITY    }    @SuppressWarnings("unchecked")    public SmartArray(int initialCapacity){        // constructor        // set the initial capacity of...

  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

  • public class PQueue<E extends Comparable<E>> { private E[] elements; private int size; private int head; private...

    public class PQueue<E extends Comparable<E>> { private E[] elements; private int size; private int head; private int tail; Private int count;   } public void enqueue(E item) { if(isFull()){ return; } count++; elements[tail] = item; tail = (tail + 1) % size; } public E dequeue() { if(isEmpty()) return null; int ct = count-1; E cur = elements[head]; int index = 0; for(i=1;ct-->0;i++) { if(cur.compareTo(elements[head+i)%size])<0) cur = elements[(head+i)%size]; index = i; } } return remove((head+index%size); public E remove(int index) { E...

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

  • PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY....

    PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY. THE CODE IS IN JAVA PROGRAMMING LANGUAGE. import java.util.AbstractList; import java.util.List; import java.util.RandomAccess; import java.lang.RuntimeException; import java.util.Arrays; public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess {    protected Object[] data; protected int size; public int size() {     return size; }    private void rangeCheck(int index) {     if (index < 0 || index >= size) throw new IndexOutOfBoundsException(""); }    @SuppressWarnings("unchecked") private E...

  • public class Scheduler {    private List<Course> classes;    private List<Student> students;    public Scheduler() {...

    public class Scheduler {    private List<Course> classes;    private List<Student> students;    public Scheduler() {        classes = new ArrayList<Course>();        students = new ArrayList<Student>();    }       public void addCourse(Course course) {        this.classes.add(course);    }    public List<Course> getCourses() {        List<Course> newCList=new ArrayList<>();        for(int i=0;i<classes.size();i++){        newCList.add(classes.get(i));        }        return newCList;    }    public void addStudent(Student student) {        this.students.add(student);    }   ...

  • package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic *...

    package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic * collection to store elements where indexes represent priorities and the * priorities can change in several ways. * * This collection class uses an Object[] data structure to store elements. * * @param <E> The type of all elements stored in this collection */ // You will have an error until you have have all methods // specified in interface PriorityList included inside this...

  • I hope someone can explain this exercise to me. Thanks +++++++++++++ Programming Exercise Try to think...

    I hope someone can explain this exercise to me. Thanks +++++++++++++ Programming Exercise Try to think about how to implement KWArrayList class. Please implement the following constructor and methods: public KWArrayList() public boolean add(E anEntry) public E get(int index) { public E set(int index, E newValue) public E remove(int index) private void reallocate() public int size() public int indexOf(Object item)       Study the code for ArrayList implementation (enclosed in the folder) and work on the following exercise Provide a constructor...

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