-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInventory.cs
145 lines (119 loc) · 3.39 KB
/
Inventory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MultipleEnumerator
{
enum ItemType
{
Shirt, Trouser, Jean, Blazer
}
enum ItemSize
{
Small, Medium, Large
}
class Inventory
{
Dictionary<Item, int> items;
public IComparer<Item> InventoryComparer
{
set;
private get;
}
public Inventory()
{
if (InventoryComparer == null)
InventoryComparer = new TypeWiseComparer();
items = new Dictionary<Item, int>();
}
public void add(Item item, int units)
{
if (items.ContainsKey(item))
items[item] = units;
else
items.Add(item, units);
}
public void add(ItemType type, ItemSize size, int units)
{
Item i = new Item(type, size);
add(i, units);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (var item in items)
{
sb.AppendLine(String.Format("{0} contains {1} units", item.Key.ToString(), item.Value));
}
return sb.ToString();
}
private InventoryEnumerator EnumerateAs()
{
return new InventoryEnumerator(items);
}
public IEnumerator GetEnumerator()
{
return (IEnumerator)EnumerateAs();
}
}
class TypeWiseComparer : IComparer<Item>
{
}
class InventoryEnumerator : IEnumerator<KeyValuePair<Item, int>>
{
Dictionary<Item, int> _items;
private KeyValuePair<Item, int> _current;
public IComparer<Item> InventoryComparer { get; set; }
public InventoryEnumerator(Dictionary<Item, int> items)
: this(items, new TypeWiseComparer())
{
}
public InventoryEnumerator(Dictionary<Item, int> items, IComparer<Item> comparer)
{
_items = items;
InventoryComparer = comparer;
}
public KeyValuePair<Item, int> Current
{
get { return _current; }
}
public void Dispose()
{
throw new NotImplementedException();
}
object IEnumerator.Current
{
get { return _current; }
}
public bool MoveNext()
{
bool moved = false;
KeyValuePair<Item, int> NGE;
foreach (var i in _items)
{
if (Current.Key.CompareTo(i.Key) < 0 && NGE.Key.CompareTo(i.Key) < 0)
{
NGE = i;
moved = true;
}
}
if (moved)
_current = NGE;
return moved;
}
public void Reset()
{
KeyValuePair<Item, int> first = _items.First();
foreach (var i in _items)
{
if (first.Key.CompareTo(i.Key) < 0)
{
first = i;
}
}
_current = first;
}
}
}