Example #1
0
        static void Main(string[] args)
        {
            int checksum = 0;

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                int[] values = line.Split('\t', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse)
                               .ToArray();

                for (int i = 0; i < values.Length; i++)
                {
                    List <int> temp = new List <int>(values);
                    temp.RemoveAt(i);
                    List <int> mods = temp.Select(v => values[i] % v).ToList();
                    int        idx  = mods.IndexOf(0);

                    if (idx >= 0)
                    {
                        int otherNumber = temp[idx];
                        checksum += values[i] / otherNumber;
                        break;
                    }
                }
            }


            Console.WriteLine($"The checksum is {checksum}");
            Console.ReadKey(true);
        }
Example #2
0
        static void Main(string[] args)
        {
            List <int> jumps = new List <int>();

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                jumps.Add(int.Parse(line));
            }

            int index = 0;
            int count = 0;

            while (index >= 0 && index < jumps.Count)
            {
                int inst = jumps[index];
                if (inst >= 3)
                {
                    jumps[index] = jumps[index] - 1;
                }
                else
                {
                    jumps[index] = jumps[index] + 1;
                }


                index += inst;
                count++;
            }

            Console.WriteLine($"Escaping took {count} jumps");
            Console.ReadKey(true);
        }
Example #3
0
        static void Main(string[] args)
        {
            Regex           reg       = new Regex(@"p=<(?<px>[^,]+),(?<py>[^,]+),(?<pz>[^>]+)>, v=<(?<vx>[^,]+),(?<vy>[^,]+),(?<vz>[^>]+)>, a=<(?<ax>[^,]+),(?<ay>[^,]+),(?<az>[^>]+)>");
            List <Particle> particles = new List <Particle>();

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                Match m = reg.Match(line);

                Vector3 pos = new Vector3(float.Parse(m.Groups["px"].Value), float.Parse(m.Groups["py"].Value), float.Parse(m.Groups["pz"].Value));
                Vector3 vel = new Vector3(float.Parse(m.Groups["vx"].Value), float.Parse(m.Groups["vy"].Value), float.Parse(m.Groups["vz"].Value));
                Vector3 acc = new Vector3(float.Parse(m.Groups["ax"].Value), float.Parse(m.Groups["ay"].Value), float.Parse(m.Groups["az"].Value));

                particles.Add(new Particle(pos, vel, acc));
            }

            RemoveColisions(particles);

            for (int i = 0; i < 10000; i++)
            {
                particles.AsParallel().ForAll(p => p.MoveParticle());
                RemoveColisions(particles);
            }

            Console.WriteLine($"particle count is {particles.Count}");
            Console.ReadKey(true);
        }
Example #4
0
        private static void LoadTree(Dictionary <string, TreeNode> nodes)
        {
            Dictionary <TreeNode, string> supports = new Dictionary <TreeNode, string>();
            Regex inputRegex = new Regex(@"(?<name>[^ ]+) \((?<weight>\d+)\)(?: -> ){0,1}(?<supporting>.*)");

            foreach (string line in FileIterator.Create("input.txt"))
            {
                Match  m          = inputRegex.Match(line);
                string name       = m.Groups["name"].Captures[0].Value;
                int    weight     = int.Parse(m.Groups["weight"].Captures[0].Value);
                string supporters = m.Groups["supporting"].Captures[0].Value;

                TreeNode node = new TreeNode(name, weight);
                nodes.Add(name, node);
                if (!string.IsNullOrEmpty(supporters))
                {
                    supports.Add(node, supporters);
                }
            }

            foreach (KeyValuePair <TreeNode, string> pair in supports)
            {
                TreeNode node = pair.Key;

                foreach (string supported in pair.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()))
                {
                    TreeNode other = nodes[supported];
                    other.Parents.Add(node);
                    node.Children.Add(other);
                }
            }
        }
Example #5
0
        static void Main(string[] args)
        {
            Emulator em0 = new Emulator(0);
            Emulator em1 = new Emulator(1);

            em1.ReceiveQueue = em0.SendQueue;
            em0.ReceiveQueue = em1.SendQueue;

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                em0.LoadInstruction(line);
                em1.LoadInstruction(line);
            }

            Task tsk0 = Task.Run(async() =>
            {
                while (!em0.Terminated)
                {
                    await em0.NextInst().ConfigureAwait(false);
                }
            });

            Task tsk1 = Task.Run(async() =>
            {
                while (!em1.Terminated)
                {
                    await em1.NextInst().ConfigureAwait(false);
                }
            });

            Task.WhenAll(tsk0, tsk1).GetAwaiter().GetResult();

            Console.WriteLine($"Recovered value is {em1.SendCount}");
            Console.ReadKey(true);
        }
Example #6
0
        static void Main(string[] args)
        {
            int largest = 0;
            Dictionary <string, int> registers = new Dictionary <string, int>();
            Regex inst = new Regex(@"(?<register>.+) (?<inst>inc|dec) (?<qty>[-\d]+) if (?<testreg>.+) (?<op>.{1,2}) (?<opqty>[-\d]+)");

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                Match m = inst.Match(line);

                string register    = m.Groups["register"].Captures[0].Value;
                string instruction = m.Groups["inst"].Captures[0].Value;
                int    qty         = int.Parse(m.Groups["qty"].Captures[0].Value);


                string testReg = m.Groups["testreg"].Captures[0].Value;
                string oper    = m.Groups["op"].Captures[0].Value;
                int    opQty   = int.Parse(m.Groups["opqty"].Captures[0].Value);

                if (!registers.ContainsKey(register))
                {
                    registers.Add(register, 0);
                }

                if (!registers.ContainsKey(testReg))
                {
                    registers.Add(testReg, 0);
                }

                if (IsTestPassed(registers, testReg, oper, opQty))
                {
                    if (instruction == "inc")
                    {
                        registers[register] += qty;
                    }
                    else
                    {
                        registers[register] -= qty;
                    }
                }

                int largestTmp = registers.Max(r => r.Value);

                if (largestTmp > largest)
                {
                    largest = largestTmp;
                }
            }



            Console.WriteLine($"The largest value is {largest}");
            Console.ReadKey(true);
        }
Example #7
0
        static void Main(string[] args)
        {
            List <string> rows = FileIterator.Create("./input.txt").ToList();
            int           x    = rows.First().Length;
            int           y    = rows.Count;

            char[,] map = new char[x, y];

            for (int j = 0; j < y; j++)
            {
                char[] row = rows[j].ToCharArray();
                for (int i = 0; i < x; i++)
                {
                    map[i, j] = row[i];
                }
            }

            Point         pos   = new Point(rows[0].IndexOf('|'), 0);
            Point         dir   = new Point(0, 1);
            StringBuilder sb    = new StringBuilder();
            bool          cont  = true;
            int           steps = 0; //we will end up with an extra step at the end for stepping off the puzzle, so we start at 0 instead of 1 so as to not count stepping onto the puzzle

            while (cont)
            {
                while (map[pos.X, pos.Y] != '+' && map[pos.X, pos.Y] != ' ')
                {
                    if (map[pos.X, pos.Y] != '|' && map[pos.X, pos.Y] != '-')
                    {
                        sb.Append(map[pos.X, pos.Y]);
                    }

                    pos.Offset(dir);
                    steps++;
                }

                var res = CalculateDirection(dir, pos, map);
                if (res.Item1)
                {
                    dir = res.Item2;
                    pos.Offset(dir);
                    steps++;
                }
                else
                {
                    cont = false;
                }
            }

            Console.WriteLine(sb.ToString());
            Console.WriteLine($"{steps} steps");
            Console.ReadKey(true);
        }
Example #8
0
        static void Main(string[] args)
        {
            List <ProgramDefinition> Definitions = new List <ProgramDefinition>();

            foreach (string line in FileIterator.Create("input.txt"))
            {
                string[] halves = line.Split("<->");

                int   id    = int.Parse(halves[0].Trim());
                int[] links = halves[1].Trim().Split(',').Select(int.Parse).ToArray();

                ProgramDefinition def = Definitions.FirstOrDefault(d => d.Id == id);

                if (def == null)
                {
                    def = new ProgramDefinition(id);
                    Definitions.Add(def);
                }

                foreach (int link in links)
                {
                    ProgramDefinition lnk = Definitions.FirstOrDefault(d => d.Id == link);
                    if (lnk == null)
                    {
                        lnk = new ProgramDefinition(link);
                        Definitions.Add(lnk);
                    }
                    def.Links.Add(lnk);
                }
            }

            foreach (ProgramDefinition definition in Definitions)
            {
                if (definition.GroupId == default(Guid))
                {
                    definition.AssignGroups();
                }
            }

            int groups = Definitions.GroupBy(g => g.GroupId).Count();

            Console.WriteLine($"The number of groups is {groups}");
            Console.ReadKey(true);
        }
Example #9
0
        static void Main(string[] args)
        {
            int valid = 0;

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                string[] words = line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
                                 .Select(s => new string(s.ToCharArray().OrderBy(c => c).ToArray()))
                                 .ToArray();

                if (words.Distinct().Count() == words.Length)
                {
                    valid++;
                }
            }

            Console.WriteLine($"The valid count is {valid}");
            Console.ReadKey(true);
        }
Example #10
0
        static void Main(string[] args)
        {
            Emulator em = new Emulator(new Dictionary <string, long> {
                { "a", 1 }, { "b", 0 }, { "c", 0 }, { "d", 0 }, { "e", 0 }, { "f", 0 }, { "g", 0 }, { "h", 0 }
            });

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                em.LoadInstruction(line);
            }

            while (!em.Terminated)
            {
                em.NextInst().GetAwaiter().GetResult();
            }

            Console.WriteLine($"The count is {em.DebugCounts[typeof(MulInstruction).Name]}");
            Console.WriteLine($"Register h is {em.GetRegisterValue("h")}");
            Console.ReadKey(true);
        }
Example #11
0
        static void Main(string[] args)
        {
            List <Link> links = new List <Link>();

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                int[] vals = line.Split('/').Select(int.Parse).ToArray();
                links.Add(new Link(vals[0], vals[1]));
            }

            Bridge b = new Bridge(links);

            while (!b.IsAllComplete())
            {
                b.SolveNext();
            }

            Bridge longest = b.GetLongest();

            Console.WriteLine($"Greatest strength is {longest.MyScore}");
            Console.ReadKey(true);
        }
Example #12
0
        static void Main(string[] args)
        {
            Dictionary <string, string> recipies = new Dictionary <string, string>();

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                string[] split = line.Split("=>").Select(s => s.Trim()).ToArray();
                recipies.Add(split[0], split[1]);
            }

            Img full = new Img(".#./..#/###");

            for (int i = 0; i < 18; i++)
            {
                Console.WriteLine($"Iteration {i}");
                Img[]      split;
                List <Img> expanded = new List <Img>();

                if (full.Rows.Count % 2 == 0)
                {
                    split = full.Split(2).ToArray();
                }
                else
                {
                    split = full.Split(3).ToArray();
                }

                foreach (Img img in split)
                {
                    string result  = null;
                    Img    working = img;
                    while (result == null)
                    {
                        result = CheckMatch(working, recipies);
                        if (result != null)
                        {
                            break;
                        }
                        working = working.Flip();
                        result  = CheckMatch(working, recipies);
                        if (result != null)
                        {
                            break;
                        }
                        working = working.Flip().Rotate();
                    }

                    expanded.Add(new Img(result)
                    {
                        Row = img.Row, Col = img.Col
                    });
                }

                full = expanded[0].Assemble(expanded.Skip(1));
            }

            int cnt = full.Rows.SelectMany(r => r).Count(r => r.Equals("#"));

            Console.WriteLine($"the answer is {cnt}");
            Console.ReadKey(true);
        }
Example #13
0
        static void Main(string[] args)
        {
            Console.CursorVisible = false;
            int          curDepth      = 0;
            List <Layer> layers        = new List <Layer>();
            int          totalSeverity = 0;

            foreach (string line in FileIterator.Create("./input.txt"))
            {
                string[] vals  = line.Split(':').Select(s => s.Trim()).ToArray();
                int      depth = int.Parse(vals[0]);
                int      range = int.Parse(vals[1]);

                while (curDepth < depth)
                {
                    layers.Add(new Layer(curDepth++, null));
                }

                layers.Add(new Layer(curDepth++, range));
            }

            int delay = 1;

            Layer[] cloned = layers.Select(l => l.Clone()).ToArray();

            while (true)
            {
                if (delay % 100 == 0)
                {
                    Console.WriteLine($"Trying delay of {delay}");
                }

                layers = new List <Layer>(cloned);

                bool caught = false;

                layers.ForEach(l => l.MoveScanner());
                cloned = layers.Select(l => l.Clone()).ToArray();

                delay++;

                for (int i = 0; i < layers.Count; i++)
                {
                    if (layers[i].MoveIntoLayer())
                    {
                        caught = true;
                        break;
                    }

                    layers.ForEach(l => l.MoveScanner());
                }

                if (!caught)
                {
                    break;
                }
            }

            Console.WriteLine($"The total delay is {delay - 1}");
            Console.ReadKey(true);
        }
Example #14
0
        static void Main(string[] args)
        {
            int y = -12;

            Dictionary <Point, NodeState> states = new Dictionary <Point, NodeState>();
            Point  cur         = new Point(0, 0);
            Facing facing      = new Facing();
            int    infectCount = 0;

            foreach (string input in FileIterator.Create("./input.txt"))
            {
                int x = -12;
                foreach (char c in input)
                {
                    if (c == '#')
                    {
                        states.Add(new Point(x, y), NodeState.Infected);
                    }
                    else
                    {
                        states.Add(new Point(x, y), NodeState.Clean);
                    }
                    x++;
                }
                y++;
            }

            for (int i = 0; i < 10000000; i++)
            {
                if (!states.ContainsKey(cur))
                {
                    states.Add(cur, NodeState.Clean);
                }

                NodeState curState = states[cur];

                switch (curState)
                {
                case NodeState.Clean:
                    states[cur] = NodeState.Weakened;
                    facing.TurnLeft();
                    break;

                case NodeState.Weakened:
                    states[cur] = NodeState.Infected;
                    infectCount++;
                    break;

                case NodeState.Infected:
                    states[cur] = NodeState.Flagged;
                    facing.TurnRight();
                    break;

                case NodeState.Flagged:
                    states[cur] = NodeState.Clean;
                    facing.TurnRight();
                    facing.TurnRight();
                    break;
                }

                cur = facing.Move(cur);
            }

            Console.WriteLine($"The answer is {infectCount}");
            Console.ReadKey(true);
        }