-
Notifications
You must be signed in to change notification settings - Fork 0
/
Book.cs
92 lines (89 loc) · 2.8 KB
/
Book.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
namespace econrpg
{
public class Book
{
private static Random random = new Random();
static String[] acceptedOfferTypes = { "bid", "ask" };
public String type;
public int commodityId;
List<Offer> offers;
public Book(String type, int commodityId)
{
this.type = type;
this.commodityId = commodityId;
this.offers = new List<Offer>();
}
private void suffleBook()
{
int n = this.offers.Count;
while (n > 1)
{
n--;
int k = random.Next(n + 1);
Offer value = this.offers[k];
this.offers[k] = this.offers[n];
this.offers[n] = value;
}
}
public void sortOffers()
{
this.offers.Sort();
if (this.type == "bid") this.offers.Reverse();
}
public void finishOffers()
{
foreach (Offer offer in this.offers)
{
Agent agent = Agent.getAgentById(offer.agentId);
agent.receiveOfferResult(offer);
}
this.cleanBook();
}
public int getOffersTotalAmount()
{
return this.offers.Aggregate(0, (total, next) => total + next.amount);
}
public double getOffersPriceAvg()
{
if (this.offers.Count() <= 0) return 0.0;
IEnumerable<double> offersPrices = this.offers.Select(offer => offer.price);
double sum = offersPrices.Aggregate(0.0, (total, price) => total + price);
return Math.Round(sum / offersPrices.Count(), 2);
}
public bool stillOpenOffers()
{
return this.offers.Exists(x => x.open);
}
public Offer getOpenOfferOnTop()
{
foreach (Offer offer in this.offers)
{
if (offer.open)
{
return offer;
}
}
// it should not get here
return this.offers[0];
}
public void addOffer(Offer offer)
{
this.offers.Add(offer);
this.suffleBook();
}
private void cleanBook()
{
this.offers.Clear();
}
public void printOffers()
{
Console.WriteLine("\nThese are the offers in this Book");
Console.WriteLine("Commodity: " + Commodities.getOneById(this.commodityId).getName());
Console.WriteLine("AgId\tCmmId\tType\tAmount\tPrice\tOpen");
foreach (Offer offer in this.offers)
{
Console.WriteLine($"{offer.agentId}\t{offer.commodityId}\t{offer.type}\t{offer.amount}\t{offer.price}\t{offer.open}");
}
}
}
}