private bool IsValid(TrainTicketRule rule) { foreach (int value in fields) { if (!rule.Validate(value)) { return(false); } } return(true); }
public override bool Equals(object obj) { //Check for null and compare run-time types. if ((obj == null) || !this.GetType().Equals(obj.GetType())) { return(false); } else { TrainTicketRule p = (TrainTicketRule)obj; return(name.Equals(p.name)); } }
public static string B(string input) { ParseInput(input); //Prune the shitty tickets for (int i = otherTickets.Count - 1; i >= 0; i--) { if (!otherTickets[i].IsValid(rules)) { otherTickets.RemoveAt(i); } } // Work out the fields // Bundle each field up List <List <int> > fieldsValues = new List <List <int> >(); for (int i = 0; i < otherTickets[0].Fields.Count(); i++) { fieldsValues.Add(new List <int>()); } foreach (TrainTicket ticket in otherTickets) { for (int i = 0; i < ticket.Fields.Count; i++) { fieldsValues[i].Add(ticket.Fields[i]); } } Dictionary <int, TrainTicketRule> foundFields = new Dictionary <int, TrainTicketRule>(); while (foundFields.Count < rules.Count) { // If a field matches only one rule, we know what that field is for (int i = 0; i < fieldsValues.Count; i++) { if (!foundFields.ContainsKey(i)) { TrainTicketRule matchingRule = null; int matchingRuleCount = 0; foreach (TrainTicketRule rule in rules) { if (!foundFields.ContainsValue(rule)) { if (rule.Validate(fieldsValues[i])) { //Console.WriteLine("Field " + i + " matches rule " + rule.Name); matchingRule = rule; matchingRuleCount++; } } } if (matchingRuleCount == 1) { //Console.WriteLine("Field " + i + " only matches rule " + matchingRule.Name + " so it must be that"); foundFields.Add(i, matchingRule); } } } } long total = 1; foreach (KeyValuePair <int, TrainTicketRule> pair in foundFields) { //Console.WriteLine(pair.Value.Name + " " + myTicket.Fields[pair.Key]); if (pair.Value.Name.Contains("departure")) { total = total * myTicket.Fields[pair.Key]; } } return(total.ToString()); }