public void AddCashItem(CashItem item) { if (capacity >= current + item.Value && GemItemsValue >= CashItemsValue + item.Value) { var cashItems = GetCashItems(); if (cashItems.Any(gi => gi.Key == item.Key)) { cashItems.Single(gi => gi.Key == item.Key).IncreaseValue(item.Value); } else { bag.Add(item); } current += item.Value; } }
private static void InsertItem(string key, long value, Bag bag) { if (key.Length == 3) { CashItem cash = new CashItem(key, value); bag.AddCashItem(cash); } else if (key.Length >= 4 && key.ToLower().EndsWith("gem")) { GemItem gem = new GemItem(key, value); bag.AddGemItem(gem); } else if (key.ToLower().Equals("gold")) { GoldItem gold = new GoldItem(key, value); bag.AddGoldItem(gold); } }
//------------- Public Methods --------------- public void Run() { this.bag = new Bag(long.Parse(Console.ReadLine())); string[] tokens = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); string goldPattern = @"\b(?i)gold\b"; string gemPattern = @"\b(?i)[a-z0-9]{1,}gem\b"; string cashPatern = @"\b(?i)[a-z]{3}\b"; for (int i = 0; i < tokens.Length; i += 2) { string item = tokens[i]; long quantity = long.Parse(tokens[i + 1]); Match goldMatch = Regex.Match(item, goldPattern); Match gemMatch = Regex.Match(item, gemPattern); Match cashMatch = Regex.Match(item, cashPatern); if (goldMatch.Success) { GoldItem goldItem = new GoldItem(goldMatch.Value, quantity); this.bag.AddGoldItem(goldItem); } else if (gemMatch.Success) { GemItem gemItem = new GemItem(gemMatch.Value, quantity); this.bag.AddGemItem(gemItem); } else if (cashMatch.Success) { CashItem cashItem = new CashItem(cashMatch.Value, quantity); this.bag.AddCashItem(cashItem); } } if (!String.IsNullOrEmpty(this.bag.ToString())) { Console.WriteLine(this.bag); } }