Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. public class BoundedBag<T> : Bag<T> where T : class
  2. {
  3. private string bagName; // the name of the bag
  4. private int size; // max size of the bag
  5. private int lastIndex;
  6. private T[] items;
  7. private Random rnd;
  8.  
  9. public BoundedBag(string name, int size)
  10. {
  11. lastIndex = -1;
  12. bagName = name;
  13. this.size = size;
  14. rnd = new Random();
  15. items = new T[size];
  16. }
  17. public int Size()
  18. {
  19. return size;
  20. }
  21. public string getName()
  22. {
  23. return bagName;
  24. }
  25. public bool isEmpty()
  26. {
  27. return lastIndex == -1;
  28. }
  29. public bool isFull()
  30. {
  31. if(lastIndex == size-1)
  32. {
  33. return true;
  34. }
  35. return false;
  36. }
  37. public void loadBag(string path)
  38. {
  39. String line;
  40. //Pass the filepath and filename to the StreamWriter Constructor
  41. StreamReader sr = new StreamReader(path);
  42. line = sr.ReadLine();
  43.  
  44. while (line != null)
  45. {
  46. insert((T)Convert.ChangeType(line, typeof(T)));
  47. line = sr.ReadLine();
  48. }
  49. sr.Close();
  50. }
  51. public void saveBag(string path)
  52. {
  53. //Pass the filepath and filename to the StreamWriter Constructor
  54. StreamWriter sw = new StreamWriter(path);
  55.  
  56. for(int i = 0; i <= lastIndex ; i++)
  57. {
  58. sw.WriteLine(items[i]);
  59. }
  60.  
  61. //Close the file
  62. sw.Close();
  63. }
  64. public T remove()
  65. {
  66. if (isEmpty())
  67. {
  68. throw new BagEmptyException("Bag is Empty and nothing to remove.");
  69. }
  70. else
  71. {
  72. T removed_item;
  73. int rnd_index = rnd.Next(0, lastIndex);
  74. removed_item = items[rnd_index];
  75. items[rnd_index] = items[lastIndex];
  76. lastIndex--;
  77. return removed_item;
  78.  
  79.  
  80.  
  81. }
  82.  
  83. }
  84. public void insert(T item)
  85. {
  86. if (isFull())
  87. {
  88. throw new BagFullException("Bag is Full and out of Capacity.");
  89. }
  90. else
  91. {
  92. lastIndex++;
  93. items[lastIndex] = item;
  94.  
  95. }
  96.  
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement