Question

C#

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

bool Remove T item) Removes the first occurrence of the specified item from the data collection. It returns true if the item

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

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

Program

using System;

//Vector class
class Vector<T>
{
    //private data members
    private T []data;
    private int Count;
    private int Capacity;
    
    //constructor
    public Vector(int n)
    {
        Capacity = n;
        data = new T[Capacity];
        Count = 0;
    }
    
    //IndexOf method
    public int IndexOf(T element)
    {
        for (var i = 0; i < Count; i++)
        {
            if (data[i].Equals(element)) return i;
        }
        return -1;
    }
    
    //insert method
    public void insert(int index, T item)
    {
        //check for invalid index
        if(index < 0 || index>Count)
            throw new IndexOutOfRangeException();
        
        //check Count equals to Capacity
        if(Count==Capacity)
        {
            //twice the Capacity
            Capacity = 2*Capacity;
            //create the new array
            T[]newData = new T[Capacity];
            //copy the existing array to new array
            for(var i=0; i<Count; i++)
            {
                newData[i] = data[i];
            }
            data = newData;
        }
        //check index equals to Count then insert at the end
        if(index==Count)
        {
            data[Count] = item;
        }
        //insert somewhere in the middle
        else   
        {
            for(var i=Count-1; i>=index; i--)
            {
                data[i+1] = data[i];
            }
            data[index] = item;
        }
        //increse the Count
        Count = Count + 1;
    }
    
    //Remove method
    public bool Remove(T item)
    {
        //get the index
        int i = IndexOf(item);
        //check for invalid index and
        //return false for invalid index
        if(i==-1) return false;
        //remove for valid index
        RemoveAt(i);
        //return true for valid index
        return true;
    }
    
    //RemoveAt method
    public void RemoveAt(int index)
    {
        //check for invalid index
        if(index < 0 || index>Count)
            throw new IndexOutOfRangeException();
        
        //remove the item from array
        for(var i=index; i<Count-1; i++)
        {
            data[i] = data[i+1];
        }
        //decrease the Count
        Count = Count - 1;
    }
    
    public void print()
    {
        for(var i=0; i<Count; i++)
        {
            Console.Write(data[i] + " ");
        }
        Console.WriteLine();
    }
}


class Program
{
    public static void Main(string[] args)
    {
        Vector<int> vec = new Vector<int>(3);
        
        vec.insert(0, 10);
        vec.insert(1, 20);
        vec.insert(2, 30);
        vec.insert(3, 40);
        vec.insert(4, 50);
        vec.print();
        vec.RemoveAt(3);
        vec.print();
        
            
        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

Output:

10 20 30 40 50
10 20 30 50
Press any key to continue . . .

Note:  Whether you face any problem or need any modification then share with me in the comment section, I'll happy to help you.

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

    Expected OUTPUT: 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...

  • Part I: Create a doubly linked circular list class named LinkedItemList that implements the following interface:...

    Part I: Create a doubly linked circular list class named LinkedItemList that implements the following interface: /** * An ordered list of items. */ public interface ItemList<E> {      /**       * Append an item to the end of the list       *       * @param item – item to be appended       */ public void append(E item);      /**       * Insert an item at a specified index position       *       * @param item – item to be...

  • 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...

  • 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...

  • 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...

  • 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 - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public...

    JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public E previous() { // Returns the previous Element return null; } Explanation: We have this class with these two implemented inferfaces: The interfaces are: package edu.ics211.h04; /** * Interface for a List211. * * @author Cam Moore * @param the generic type of the Lists. */ public interface IList211 { /** * Gets the item at the given index. * @param index the index....

  • Given the Interface Code write a java class that implements this interface and show the working...

    Given the Interface Code write a java class that implements this interface and show the working functionality in the main method: public interface CustomList<T> { /** * This method should add a new item into the <code>CustomList</code> and should * return <code>true</code> if it was successfully able to insert an item. * @param item the item to be added to the <code>CustomList</code> * @return <code>true</code> if item was successfully added, <code>false</code> if the item was not successfully added (note: it...

  • Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr,...

    Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr, int count, int key ) { 1: find the index of the first occurance of key. By first occurance we mean lowest index that contains this value. hint: copy the indexOf() method from Lab#3 into the bottom of this project file and call it from inside this remove method. The you will have the index of the value to remove from the array 2:...

  • 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...

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