Exemplo n.º 1
0
        void Enqueue( )
        {
            ConsoleKeyInfo _key = Console.ReadKey(true);

            onKeyPressed(new EventArgs <ConsoleKeyInfo>(_key));
            switch (_key.Key)
            {
            case ConsoleKey.Backspace:
                if (!string.IsNullOrEmpty(CurrentLine.ToString( )))
                {
                    CurrentLine.Remove(CurrentLine.Length - 1, 1);
                    onCurrentLineChanged(EventArgs.Empty);
                }
                break;

            case ConsoleKey.LeftArrow:
            case ConsoleKey.RightArrow:
            case ConsoleKey.UpArrow:
            case ConsoleKey.DownArrow:
                break;

            case ConsoleKey.Enter:
                InputLines.Enqueue(CurrentLine.ToString( ));
                CurrentLine.Clear( );
                onCurrentLineChanged(EventArgs.Empty);
                onNewInputLineAdded(EventArgs.Empty);
                break;

            default:
                CurrentLine.Append(_key.KeyChar);
                onCurrentLineChanged(EventArgs.Empty);
                break;
            }
        }
Exemplo n.º 2
0
        public int PuzzleB()
        {
            var trees = InputLines
                        .Select(str => new TreeLine(str))
                        .ToList();

            var collisionProduct = 1;

            collisionProduct *= GetCollisionCount(trees, 1, 1);

            WriteLine("");

            collisionProduct *= GetCollisionCount(trees, 3, 1);

            WriteLine("");

            collisionProduct *= GetCollisionCount(trees, 5, 1);

            WriteLine("");

            collisionProduct *= GetCollisionCount(trees, 7, 1);

            WriteLine("");

            collisionProduct *= GetCollisionCount(trees, 1, 2);

            WriteLine("");

            return(collisionProduct);
        }
Exemplo n.º 3
0
        public long PuzzleB()
        {
            var inputs = InputLines
                         .Select(long.Parse)
                         .ToArray();

            var target = FindFirstInvalidInput(inputs);

            var sum = inputs[0];
            var min = 0;
            var max = 0;

            while (true)
            {
                if (sum < target || min == max)
                {
                    max++;
                    sum += inputs[max];
                }
                else if (sum > target)
                {
                    sum -= inputs[min];
                    min++;
                }
                else
                {
                    var values = inputs
                                 .Skip(min)
                                 .Take(max - min)
                                 .ToArray();

                    return(values.Min() + values.Max());
                }
            }
        }
Exemplo n.º 4
0
        public int PuzzleB()
        {
            var rules = InputLines
                        .Select(line => new BagRule(line))
                        .ToDictionary(r => r.Title);

            var bags = new Stack <(int number, string bag)>();

            bags.Push((1, "shiny gold"));

            int result = 0;

            while (bags.Any())
            {
                var(number, bag) = bags.Pop();
                var rule = rules[bag];

                foreach (var kvp in rule.GetContents())
                {
                    var newBag = kvp.Key;
                    var count  = number * kvp.Value;
                    result += count;
                    bags.Push((count, newBag));
                }
            }

            return(result);
        }
Exemplo n.º 5
0
    public Day06Solver(string inputFilePath) : base(inputFilePath)
    {
        _groups = new List <List <string> >();
        List <string>        group = new List <string>();
        IEnumerator <string> it    = InputLines.GetEnumerator();

        while (it.MoveNext())
        {
            if (it.Current.Equals(""))
            {
                if (group.Count > 0)
                {
                    _groups.Add(group);
                    group = new List <string>();
                }
            }
            else
            {
                group.Add(it.Current);
            }
        }
        if (group.Count > 0)
        {
            _groups.Add(group);
        }
    }
Exemplo n.º 6
0
        protected override void Run()
        {
            // Part 1
            for (int i = 0; i < InputLines.Length; i++)
            {
                int first         = int.Parse(InputLines[i]);
                int desiredNumber = 2020 - first;

                bool found = InputLines.Any(x => x == desiredNumber.ToString());
                if (found)
                {
                    AnswerPart1 = (first * desiredNumber).ToString();
                    break;
                }
            }

            // Part 2
            for (int i = 0; i < InputLines.Length; i++)
            {
                int first = int.Parse(InputLines[i]);

                for (int j = i + 1; j < InputLines.Length; j++)
                {
                    int second        = int.Parse(InputLines[j]);
                    int desiredNumber = 2020 - first - second;

                    bool found = InputLines.Any(x => x == desiredNumber.ToString());
                    if (found)
                    {
                        AnswerPart2 = (first * second * desiredNumber).ToString();
                        return;
                    }
                }
            }
        }
Exemplo n.º 7
0
        protected override void Run()
        {
            var passwordPolicies = InputLines.Select(inp => new PasswordPolicy(inp)).ToList();

            // Part 1
            int countValidPasswords = 0;

            foreach (var policy in passwordPolicies)
            {
                if (IsValidPasswordPart1(policy))
                {
                    countValidPasswords++;
                }
            }
            AnswerPart1 = countValidPasswords.ToString();

            // Part 2
            countValidPasswords = 0;
            foreach (var policy in passwordPolicies)
            {
                if (IsValidPasswordPart2(policy))
                {
                    countValidPasswords++;
                }
            }
            AnswerPart2 = countValidPasswords.ToString();
        }
Exemplo n.º 8
0
        public int PuzzleA()
        {
            var rules = InputLines
                        .Select(line => new BagRule(line))
                        .ToArray();

            var bags = new Stack <string>();

            bags.Push("shiny gold");

            var foundBags = new HashSet <string>();

            while (bags.Any())
            {
                var bag     = bags.Pop();
                var newBags = rules
                              .Where(r => r.AllowedBags(bag) > 0)
                              .Select(r => r.Title)
                              .ToArray();

                foreach (var newBag in newBags)
                {
                    if (!foundBags.Contains(newBag))
                    {
                        foundBags.Add(newBag);
                        bags.Push(newBag);
                    }
                }
            }

            return(foundBags.Count);
        }
Exemplo n.º 9
0
 public override int FirstStar() => InputLines
 .Select(line => regex.Match(line).Groups.Values.Skip(1).Select(v => v.Value).ToArray())
 .Where(p => {
     int count = p[3].Count(ch => ch == p[2][0]);
     return(count >= int.Parse(p[0]) && count <= int.Parse(p[1]));
 })
 .Count();
Exemplo n.º 10
0
 public override int SecondStar() => InputLines
 .Select(line => regex.Match(line).Groups.Values.Skip(1).Select(v => v.Value).ToArray())
 .Where(p => new[] {
     p[3][int.Parse(p[0]) - 1],
     p[3][int.Parse(p[1]) - 1]
 }.Count(l => l == p[2][0]) == 1)
 .Count();
Exemplo n.º 11
0
 public Day10()
 {
     Space  = InputLines.Select(line => line.ToArray()).ToArray();
     Height = Space.Length;
     Width  = Space[0].Length;
     Depth  = Math.Max(Height, Width) - 1;
 }
Exemplo n.º 12
0
    public Day19Solver(string inputFilePath) : base(inputFilePath)
    {
        IEnumerator <string> it         = InputLines.GetEnumerator();
        List <string>        rulesLines = new List <string>();

        while (it.MoveNext() && it.Current != "")
        {
            rulesLines.Add(it.Current);
        }
        _rules = new Rules(rulesLines.Count);
        foreach (string line in rulesLines)
        {
            (string numString, string ruleString) = line.SplitIntoTwo(':', StringSplitOptions.TrimEntries);
            int   number = int.Parse(numString);
            IRule rule   = _rules.GetRuleFromString(ruleString);
            _rules[number] = rule;
        }
        while (it.Current == "")
        {
            it.MoveNext();
        }
        _messages = new List <string>();
        while (it.Current != "")
        {
            _messages.Add(it.Current);
            if (!it.MoveNext())
            {
                break;
            }
        }
    }
Exemplo n.º 13
0
        public int PuzzleB()
        {
            var codeLines = InputLines
                            .Select(line => new CodeLine(line))
                            .ToArray();

            var alternatives = codeLines
                               .Where(line => line.Command != "acc")
                               .Select(line => codeLines.Select(l => l == line
                        ? new CodeLine(l.Command == "nop" ? "jmp" : "nop", l.Value)
                        : l
                                                                )
                                       .ToArray()
                                       );

            foreach (var alternative in alternatives)
            {
                if (TryRunProgram(alternative, out int result))
                {
                    return(result);
                }
            }

            throw new Exception("No alternatives were valid");
        }
Exemplo n.º 14
0
 public Day4()
 {
     InputLines = Helpers.ParseInputLines("input_data\\day4.txt");
     InputLines.Sort();
     _GuardLogEntries = new Dictionary <DateTime, GuardLogDay>();
     Solution1        = Solve1();
     Solution2        = Solve2();
 }
Exemplo n.º 15
0
        public int PuzzleA()
        {
            var trees = InputLines
                        .Select(str => new TreeLine(str))
                        .ToList();

            return(GetCollisionCount(trees, 3, 1));
        }
Exemplo n.º 16
0
        public long PuzzleA()
        {
            var inputs = InputLines
                         .Select(long.Parse)
                         .ToArray();

            return(FindFirstInvalidInput(inputs));
        }
Exemplo n.º 17
0
    public override string SolvePart2()
    {
        long result = InputLines
                      .Select(line => CreateEquationQueue(line, true))
                      .Select(equation => ResolveEquation(equation))
                      .Sum();

        return(result.ToString());
    }
Exemplo n.º 18
0
 private IEnumerable <Passport> GetPassports()
 {
     return(InputLines
            .Split(string.IsNullOrEmpty)
            .Select(lines => lines
                    .SelectMany(str => str.Split(' '))
                    .Where(str => !string.IsNullOrEmpty(str))
                    )
            .Select(lines => new Passport(lines)));
 }
Exemplo n.º 19
0
 public Day13Solver(string inputFilePath) : base(inputFilePath)
 {
     _timestamp = int.Parse(InputLines.First());
     _buses     = InputLines
                  .Skip(1)
                  .Single()
                  .Split(',')
                  .Select(str => str == "x" ? 0 : int.Parse(str))
                  .ToArray();
 }
Exemplo n.º 20
0
 public Day12()
 {
     Moons = InputLines.Select(line => {
         Match re = Regex.Match(line, @"<x=(-?\d*), y=(-?\d*), z=(-?\d*)>");
         return(new Moon(
                    int.Parse(re.Groups[1].Value),
                    int.Parse(re.Groups[2].Value),
                    int.Parse(re.Groups[3].Value)));
     }).ToArray();
 }
Exemplo n.º 21
0
        public int PuzzleA()
        {
            var codeLines = InputLines
                            .Select(line => new CodeLine(line))
                            .ToArray();

            TryRunProgram(codeLines, out int result);

            return(result);
        }
Exemplo n.º 22
0
        public override int FirstStar()
        {
            var report = InputLines.Select(int.Parse);

            return(report
                   .SelectMany((x, i) => report.Skip(i + 1), Tuple.Create)
                   .Where(t => t.Item1 + t.Item2 == 2020)
                   .Select(t => t.Item1 * t.Item2)
                   .First());
        }
Exemplo n.º 23
0
        public override long FirstStar()
        {
            var setSize = 25;
            var input   = InputLines.Select(int.Parse);

            return(input.Skip(setSize).Where((n, i) => {
                var sub = input.Skip(i).Take(setSize);
                var mmm = sub.SelectMany((x, i) => sub.Skip(i + 1), (x, y) => x + y);
                return !mmm.Contains(n);
            }).First());
        }
Exemplo n.º 24
0
        public int PuzzleB()
        {
            var matchingPasswords = InputLines
                                    .Select(str => _regex.Match(str))
                                    .Select(Parse)
                                    .Select(t => t.Rule.MatchAlternate(t.Password));

            var result = matchingPasswords.Count(b => b);

            return(result);
        }
Exemplo n.º 25
0
        public override int SecondStar()
        {
            var report = InputLines.Select(int.Parse);

            return(report
                   .SelectMany((x, i) => report.Skip(i + 1)
                               .SelectMany((w, iw) => report.Skip(iw + 2), Tuple.Create), (x, y) => Tuple.Create(x, y.Item1, y.Item2))
                   .Where(t => t.Item1 + t.Item2 + t.Item3 == 2020)
                   .Select(t => t.Item1 * t.Item2 * t.Item3)
                   .First());
        }
Exemplo n.º 26
0
 public int PuzzleB()
 {
     return(InputLines
            .Split(string.IsNullOrEmpty)
            .Select(lines => lines
                    .Select(line => line.Cast <char>())
                    .Aggregate((l1, l2) => l1.Intersect(l2))
                    .Count()
                    )
            .Sum());
 }
Exemplo n.º 27
0
 public int PuzzleA()
 {
     return(InputLines
            .Split(string.IsNullOrEmpty)
            .Select(lines => lines
                    .SelectMany(str => str)
                    .Distinct()
                    .Count()
                    )
            .Sum());
 }
Exemplo n.º 28
0
        public override long FirstStar()
        {
            var earliest = int.Parse(InputLines.First());

            return(InputLines
                   .ElementAt(1)
                   .Split(",")
                   .Where(l => l != "x")
                   .Select(int.Parse)
                   .OrderBy(n => n - earliest % n)
                   .Select(n => (n - earliest % n) * n)
                   .First());
        }
Exemplo n.º 29
0
        public override long FirstStar()
        {
            var input     = InputLines.Select(long.Parse);
            var fullInput = input.Concat(new[] { 0, input.Max() + 3 }).OrderBy(j => j);
            var eee       = fullInput
                            .Skip(1)
                            .Select((jolts, i) => jolts - fullInput.ElementAt(i))
                            .GroupBy(j => j)
                            .Select(j => (j.Key, j.Count()))
                            .ToDictionary(j => j.Key, j => j.Item2);

            return(eee[1] * eee[3]);
        }
Exemplo n.º 30
0
        protected override void Run()
        {
            // Parse input string -> double
            AllInputs = InputLines.Select(x => double.Parse(x)).ToList();
            Sums      = AllInputs.Skip(COUNT_PREAMBLE).ToList();

            // Part 1: Check the one that is not valid
            double susNumber = Sums.FirstOrDefault((sum) => !IsValid(sum));

            AnswerPart1 = susNumber.ToString();

            // Part 2: Calculate weakness of the not valid number
            AnswerPart2 = CalculateWeakness(susNumber).ToString();
        }