Beispiel #1
0
        public void Puzzle2()
        {
            string inputFile = AppDomain.CurrentDomain.BaseDirectory + @"..\..\PassportData.txt";

            if (File.Exists(inputFile))
            {
                string   line;
                int      validPassports = 0;
                Passport passport       = new Passport();;

                System.IO.StreamReader file = new System.IO.StreamReader(inputFile);

                while ((line = file.ReadLine()) != null)
                {
                    if (line.Length == 0)
                    {
                        validPassports += passport.IsValid() ? 1 : 0;
                        passport        = new Passport();
                    }
                    else
                    {
                        passport.ProcessInput(line);

                        if (file.EndOfStream)
                        {
                            validPassports += passport.IsValid() ? 1 : 0;
                        }
                    }
                }

                file.Close();

                Console.WriteLine("Puzzel2 - Valid Passports = {0}", validPassports);
            }
        }
        private static void BothParts()
        {
            List <Passport> passports = new List <Passport>();
            int             allRequiredFieldsCount = 0, validCount = 0;

            foreach (var line in input)
            {
                Passport newPassport = new Passport();

                // Replace spaces with new lines then split on new lines to a new string array
                string[] passportData = line.Replace(' ', '\n').Split('\n');

                // Iterate through array of passport data
                foreach (var item in passportData)
                {
                    // Split on : to get key and value pair
                    string[] keyValuePair = item.Split(':');
                    string   key          = keyValuePair[0];
                    string   val          = keyValuePair[1];

                    // Try parsing the key and value to the passport object
                    newPassport.TryParse(key, val);
                }

                // Add the passport to the list
                passports.Add(newPassport);

                // Check if the passport meets the criteria for each part
                if (newPassport.HasRequiredFields())
                {
                    allRequiredFieldsCount++;
                }
                if (newPassport.IsValid())
                {
                    validCount++;
                }
            }

            Console.WriteLine($"Part 1: {allRequiredFieldsCount} valid passports");

            Console.WriteLine($"\nPart 2: {validCount} valid passports");
        }