Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BoundedBag<T> : Bag<T> where T : class
- {
- private string bagName; // the name of the bag
- private int size; // max size of the bag
- private int lastIndex;
- private T[] items;
- private Random rnd;
- public BoundedBag(string name, int size)
- {
- lastIndex = -1;
- bagName = name;
- this.size = size;
- rnd = new Random();
- items = new T[size];
- }
- public int Size()
- {
- return size;
- }
- public string getName()
- {
- return bagName;
- }
- public bool isEmpty()
- {
- return lastIndex == -1;
- }
- public bool isFull()
- {
- if(lastIndex == size-1)
- {
- return true;
- }
- return false;
- }
- public void loadBag(string path)
- {
- String line;
- //Pass the filepath and filename to the StreamWriter Constructor
- StreamReader sr = new StreamReader(path);
- line = sr.ReadLine();
- while (line != null)
- {
- insert((T)Convert.ChangeType(line, typeof(T)));
- line = sr.ReadLine();
- }
- sr.Close();
- }
- public void saveBag(string path)
- {
- //Pass the filepath and filename to the StreamWriter Constructor
- StreamWriter sw = new StreamWriter(path);
- for(int i = 0; i <= lastIndex ; i++)
- {
- sw.WriteLine(items[i]);
- }
- //Close the file
- sw.Close();
- }
- public T remove()
- {
- if (isEmpty())
- {
- throw new BagEmptyException("Bag is Empty and nothing to remove.");
- }
- else
- {
- T removed_item;
- int rnd_index = rnd.Next(0, lastIndex);
- removed_item = items[rnd_index];
- items[rnd_index] = items[lastIndex];
- lastIndex--;
- return removed_item;
- }
- }
- public void insert(T item)
- {
- if (isFull())
- {
- throw new BagFullException("Bag is Full and out of Capacity.");
- }
- else
- {
- lastIndex++;
- items[lastIndex] = item;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement