Example #1
0
 public Processor(Func<SingleFeature> FeatureGenerator,
     string processName = "", int featureCount = 5000, string filepath = @"C:\Users\Amichai\Data\digits.csv")
 {
     this.loader = new InputLoader();
     this.loader.LoadFile(filepath);
     this.allfeatures = new AllFeatures(featureCount, 28, FeatureGenerator);
     this.success = new FeatureSuccess();
     processID = processCounter++;
     this.Name = processName;
     this.LogFileLocation = @"C:\IR\" + DateTime.Now.ToLongTimeString().Replace(":", ".").Replace(" ", "") + "_" + this.processID.ToString() + ".txt";
 }
Example #2
0
 public ComputeProcess(InputLoader loader)
 {
     InitializeComponent();
     this.UpdateStats = true;
     this.DataContext = this;
     this.OutputFilePath = Logger.Inst.OutputFilePath();
     this.workbench = new ImageRecognition.Workbench();
     this.loader = loader;
     Logger.Inst.logFile.SetColumns("TimeStamp", "Number of trials", "Success rate (last 100)", "Feautre count", "Average Attractiveness", "Average Interestingness", "Average number of points", "Average number of data seen", "Max attractiveness", "Max interestingeness");
     workbench.FeaturesTrained += workbench_FeaturesTrained;
     bw.DoWork += bw_DoWork;
     this.Settings.Text = Logger.Inst.SerializeParams().ToString();
     this.ProcessIndex = processCounter++;
     this.featureLogDestination.Text = "featureLog.txt";
     this.PurgePercentage = workbench.PurgeVal;
     this.RecombinePercentage = workbench.RecombineVal;
 }
        public static void solve()
        {
            var input  = InputLoader.loadAsString("08");
            var width  = 25;
            var height = 6;

            var image = new Image(input, width, height);

            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    Console.Write(image.getPixel(x, y) == 1 ? '#' : ' ');
                }

                Console.WriteLine();
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            List <string> inputList = (args.Count() > 0) ? InputLoader.GetInputAsList(args[0]) : InputLoader.GetInputAsList("input.txt");
            var           slope     = new Slope(inputList)
            {
                PositionX = 0, PositionY = 0, MovementRight = 3, MovementBottom = 1
            };

            slope.Start();
            Console.WriteLine($"Trees encountered in part 1: {slope.TreesEncountered}");
            // right 3, below 1
            var slope31 = slope.TreesEncountered;

            // right 1, below 1
            slope.PositionX     = slope.PositionY = 0;
            slope.MovementRight = slope.MovementBottom = 1;
            slope.Start();
            var slope11 = slope.TreesEncountered;

            // right 5, below 1
            slope.PositionX      = slope.PositionY = 0;
            slope.MovementRight  = 5;
            slope.MovementBottom = 1;
            slope.Start();
            var slope51 = slope.TreesEncountered;

            // right 7, below 1
            slope.PositionX      = slope.PositionY = 0;
            slope.MovementRight  = 7;
            slope.MovementBottom = 1;
            slope.Start();
            var slope71 = slope.TreesEncountered;

            // right 1, below 2
            slope.PositionX      = slope.PositionY = 0;
            slope.MovementRight  = 1;
            slope.MovementBottom = 2;
            slope.Start();
            var slope12 = slope.TreesEncountered;

            // part 2
            Console.WriteLine($"Number for part 2: {slope11*slope31*slope51*slope71*slope12}");
            Console.ReadLine();
        }
Example #5
0
        static void Main(string[] args)
        {
            var input = InputLoader.GetInputAsList("input.txt");
            var dict  = new Dictionary <int, Instruction>();

            for (int i = 0; i < input.Count; i++)
            {
                dict.Add(i, Instruction.FromInput(input[i]));
            }
            var simulator1 = new BootSimulator(dict);

            simulator1.BeginBoot();
            Console.WriteLine($"Solution for task 1: {simulator1.AccumulatorState}");
            var accResult = 0;

            foreach (var instructionId in dict.Keys)
            {
                var dictCopy = CopyDictionary(dict);
                if (dictCopy[instructionId].Type.Equals(InstructionType.DoNothing))
                {
                    dictCopy[instructionId].Type = InstructionType.Jump;
                    var simulator = new BootSimulator(dictCopy);
                    simulator.BeginBoot();
                    if (simulator.BootSimulatorState.Equals(BootSimulatorState.FinishedSuccess))
                    {
                        accResult = simulator.AccumulatorState;
                        break;
                    }
                }
                else if (dictCopy[instructionId].Type.Equals(InstructionType.Jump))
                {
                    dictCopy[instructionId].Type = InstructionType.DoNothing;
                    var simulator = new BootSimulator(dictCopy);
                    simulator.BeginBoot();
                    if (simulator.BootSimulatorState.Equals(BootSimulatorState.FinishedSuccess))
                    {
                        accResult = simulator.AccumulatorState;
                        break;
                    }
                }
            }
            Console.WriteLine($"Solution for task 2: {accResult}");
            Console.ReadLine();
        }
Example #6
0
 public MainWindow()
 {
     Logger.Inst.Deserialize(@"..\..\..\Logger\TrialParams.xml");
     InitializeComponent();
     bw = new BackgroundWorker();
     bw.DoWork += bw_DoWork;
     loader = new InputLoader();
     loader.LoadFile(@"C:\Users\Amichai\Data\digits.csv");
     workbench = new Workbench();
     //Listen to all the events here
     this.GridRoot.DataContext = this;
     //workbench.InputLoaded += workbench_InputLoaded;
     workbench.FeaturesTrained += workbench_FeaturesTrained;
     this.TrialParams.Text = Logger.Inst.SerializeParams().ToString();
     this.OutputFile.Text = "Output Filepath: " + Logger.Inst.OutputFilePath();
     Logger.Inst.logFile.SetColumns("TimeStamp", "Number of trials", "Success rate (last 100)", "Feautre count", "Average Attractiveness", "Average Interestingness", "Average number of points", "Average number of data seen", "Max attractiveness", "Max interestingeness");
     bw.RunWorkerAsync();
     //this.FeautresList.ItemsSource = this.Features;
 }
        public static void solve()
        {
            var input = InputLoader.loadAsString("04").Split("-");

            var min = Int32.Parse(input[0]);
            var max = Int32.Parse(input[1]);

            var validCount = 0;

            for (var value = min; value <= max; value++)
            {
                if (isValid(String.Format("{0}", value)))
                {
                    validCount++;
                }
            }

            Console.WriteLine(validCount);
        }
Example #8
0
        static void Main(string[] args)
        {
            var input = InputLoader.GetInputAsList("input.txt");

            BagDict = input
                      .Select(x => new Bag(x))
                      .ToDictionary(x => x.Name, x => x);
            var prepareParentsList = BagDict
                                     .Where(x => x.Value.ContainsBags.ContainsKey("shiny gold bags"))
                                     .Select(x => x.Key)
                                     .ToList();

            SearchedParents.AddRangeUnique(prepareParentsList);
            RecursionParents(prepareParentsList);
            Console.WriteLine($"Solution for task 1: {SearchedParents.Count}");
            RecursionChildren("shiny gold bags", 1);
            Console.WriteLine($"Solution for task 2: {RollingCount-1}");
            Console.ReadLine();
        }
        public static void solve()
        {
            var input = InputLoader.loadAsStringArray("06");

            var planets = new Dictionary <string, Planet>();

            foreach (var line in input)
            {
                var planetIds = line.Split(")");

                Planet parent;
                if (planets.ContainsKey(planetIds[0]))
                {
                    parent = planets[planetIds[0]];
                }
                else
                {
                    planets.Add(planetIds[0], parent = new Planet());
                }

                Planet child;
                if (planets.ContainsKey(planetIds[1]))
                {
                    child = planets[planetIds[1]];
                }
                else
                {
                    planets.Add(planetIds[1], child = new Planet());
                }

                child.orbitsAround = parent;
            }

            var sum = 0;

            foreach (var planet in planets.Values)
            {
                sum += planet.getTotalOrbitCount();
            }

            Console.WriteLine(sum);
        }
Example #10
0
        public static void solve()
        {
            var input = InputLoader.loadAsString("09").Split(",");

            var program = new Dictionary <Int64, Int64>();

            for (int i = 0; i < input.Length; i++)
            {
                program[i] = Int64.Parse(input[i]);
            }

            var computer = new IntcodeComputer(program);

            var outputs = computer.execute(new int[] { 2 });

            foreach (var output in outputs)
            {
                Console.WriteLine(output);
            }
        }
Example #11
0
        public MainWindow()
        {
            InitializeComponent();
            var parameters = Logger.Inst.Deserialize(@"..\..\..\Logger\TrialParams.xml");
            this.DataContext = this;
            this.NumberOfFeatures = Logger.Inst.GetIntVal("FeaturesToRecombine");
            this.Feature1 = Logger.Inst.GetString("FeatureType");
            this.Feature2 = Logger.Inst.GetString("FeatureType2");
            this.ComputePixelFeatures = Logger.Inst.GetBool("usePixelFeatures");
            this.WeighFeaturesBySuccess = Logger.Inst.GetBool("WeighFeaturesBySuccess");
            this.CompareValExponent = Logger.Inst.GetDouble("compareValExponent");
            this.SourceInPixelFeaturesOnly = Logger.Inst.GetBool("SourceInPixelFeaturesOnly");
            this.Purge = Logger.Inst.GetBool("purge");
            this.AttractivenessThreshold = Logger.Inst.GetDouble("attractivenessPurgeThreshold");
            this.InterestingnessThreshold = Logger.Inst.GetDouble("interestingnessPurgeThreshold");
            this.OnlyTrainOnFailure = Logger.Inst.GetBool("OnlyTrainOnFailure");

            this.timer = new Timer(updateSuccessRates, null, 1000, 1000);
            this.loader = new InputLoader();
            this.loader.LoadFile(@"C:\Users\Amichai\Data\digits.csv");
        }
Example #12
0
        static void Main(string[] args)
        {
            var inputList      = (args.Count() > 0) ? InputLoader.GetInputAsList(args[0]) : InputLoader.GetInputAsList("input.txt");
            var boardingPasses = inputList.Select(anon => BoardingPass.ParseInput(anon)).ToList();
            var highestID      = boardingPasses.Max(anon => anon.SeatID);

            Console.WriteLine($"The highest seat ID (part 1): {highestID}");
            var emptySeats = new List <BoardingPass>();

            for (var i = 0; i < 128; i++)
            {
                for (var j = 0; j < 8; j++)
                {
                    var doesExistInPasses = boardingPasses
                                            .Where(anon => anon.SeatID.Equals(i * 8 + j))
                                            .Count();
                    if (doesExistInPasses == 0)
                    {
                        emptySeats.Add(new BoardingPass()
                        {
                            Row = i, Column = j
                        });
                    }
                }
            }
            foreach (var mySeat in emptySeats)
            {
                var leftSeatExists = boardingPasses
                                     .Where(anon => (mySeat.SeatID - 1).Equals(anon.SeatID))
                                     .Count() != 0;
                var rightSeatExists = boardingPasses
                                      .Where(anon => (mySeat.SeatID + 1).Equals(anon.SeatID))
                                      .Count() != 0;
                if (leftSeatExists && rightSeatExists)
                {
                    Console.WriteLine($"My seat is ID: {mySeat.SeatID}");
                }
            }
            Console.ReadLine();
        }
        public static void solve()
        {
            var input = InputLoader.loadAsString("13").Split(",");

            var computer = new IntcodeComputer(input);

            var output = computer.execute(new int[] { });

            var blockCount = 0;

            for (int i = 0; i < output.Length / 3; i++)
            {
                var offset = i * 3;

                if (output[offset + 2] == 2)
                {
                    blockCount++;
                }
            }

            Console.WriteLine(blockCount);
        }
Example #14
0
        public void Run()
        {
            try
            {
                int count = 0;
                Dictionary <string, QuestionType> questionMap = QuestionMap.GetQuestionMap();
                IList <string> questions = InputLoader.LoadQuestions(ConstStr.QUESTIONFILEPATH);
                IDictionary <MultplePrimKey, int> roads = InputLoader.LoadInputs(ConstStr.INPUTFILEPATH);
                foreach (string key in questionMap.Keys)
                {
                    count++;
                    ICaculator caculator = CaculatorFactory.Create(questionMap[key]);
                    caculator.LoadQuestionAndInput(questions[count - 1], roads);
                    caculatorEngine.AddCaculator(caculator);
                }

                caculatorEngine.Caculate();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void solve()
        {
            var input = InputLoader.loadAsString("02").Split(",");

            var codes = new int[input.Length];

            for (int i = 0; i < input.Length; i++)
            {
                codes[i] = Int32.Parse(input[i]);
            }

            for (int noun = 0; noun <= 99; noun++)
            {
                for (int verb = 0; verb <= 99; verb++)
                {
                    var result = executeProgram(codes, noun, verb);
                    if (result == 19690720)
                    {
                        Console.WriteLine(100 * noun + verb);
                        return;
                    }
                }
            }
        }
Example #16
0
        static void Main(string[] args)
        {
            var input = InputLoader.GetInputAsList("input.txt");
            var list  = input
                        .Select(x => new List <Place>(x.ToList().Select(y => new Place(y)).ToList()))
                        .ToList();

            var simulation1 = new SeatingSimulation(list);

            simulation1.BeginTask1Simulation();

            var simulationSeats = simulation1.Places.Select(x => x.Where(y => y.Type.Equals(PlaceType.TakenSeat)).Count()).Sum();

            Console.WriteLine($"Solution for task 1: {simulationSeats}");

            var simulation2 = new SeatingSimulation(list);

            simulation2.BeginTask2Simulation();

            simulationSeats = simulation2.Places.Select(x => x.Where(y => y.Type.Equals(PlaceType.TakenSeat)).Count()).Sum();
            Console.WriteLine($"Solution for task 2: {simulationSeats}");

            Console.ReadLine();
        }
        public static void solve()
        {
            var input = InputLoader.loadAsString("15").Split(",");

            var computer = new IntcodeComputer(input);

            var map = new Map();

            map.set(Tuple.Create(0, 0), 'X');

            var pathes = new LinkedList <Path>();

            pathes.AddFirst(new Path(Direction.North, null));
            pathes.AddFirst(new Path(Direction.East, null));
            pathes.AddFirst(new Path(Direction.South, null));
            pathes.AddFirst(new Path(Direction.West, null));

            var oxygenStation = Tuple.Create(0, 0);

            while (pathes.Count > 0)
            {
                var currentPath = pathes.Last.Value;
                pathes.RemoveLast();

                var state = currentPath.apply(computer, map);

                if (state.Item2 != 0)
                {
                    if (!map.isVisited(state.Item1, Direction.North))
                    {
                        pathes.AddFirst(new Path(Direction.North, currentPath));
                    }

                    if (!map.isVisited(state.Item1, Direction.East))
                    {
                        pathes.AddFirst(new Path(Direction.East, currentPath));
                    }

                    if (!map.isVisited(state.Item1, Direction.South))
                    {
                        pathes.AddFirst(new Path(Direction.South, currentPath));
                    }

                    if (!map.isVisited(state.Item1, Direction.West))
                    {
                        pathes.AddFirst(new Path(Direction.West, currentPath));
                    }
                }

                if (state.Item2 == 2)
                {
                    oxygenStation = state.Item1;
                }

                currentPath.revert(computer);
            }


            var oxygens = new LinkedList <Tuple <int, int> >();

            oxygens.AddFirst(oxygenStation);

            var minutes = 0;

            while (oxygens.Count > 0)
            {
                var newList = new LinkedList <Tuple <int, int> >();
                for (var current = oxygens.First; current != null; current = current.Next)
                {
                    map.set(current.Value, 'O');

                    if (map.get(Tuple.Create(current.Value.Item1 + 1, current.Value.Item2)) == '.')
                    {
                        newList.AddFirst(Tuple.Create(current.Value.Item1 + 1, current.Value.Item2));
                    }

                    if (map.get(Tuple.Create(current.Value.Item1 - 1, current.Value.Item2)) == '.')
                    {
                        newList.AddFirst(Tuple.Create(current.Value.Item1 - 1, current.Value.Item2));
                    }

                    if (map.get(Tuple.Create(current.Value.Item1, current.Value.Item2 + 1)) == '.')
                    {
                        newList.AddFirst(Tuple.Create(current.Value.Item1, current.Value.Item2 + 1));
                    }

                    if (map.get(Tuple.Create(current.Value.Item1, current.Value.Item2 - 1)) == '.')
                    {
                        newList.AddFirst(Tuple.Create(current.Value.Item1, current.Value.Item2 - 1));
                    }
                }

                oxygens = newList;

                minutes++;
            }

            Console.WriteLine(minutes);
        }
Example #18
0
 protected Day(string inputPath)
 {
     _inputPath   = inputPath;
     _inputLoader = new InputLoader();
 }
Example #19
0
        static void Main(string[] args)
        {
            List <string> inputList = (args.Count() > 0) ? InputLoader.GetInputAsList(args[0]) : InputLoader.GetInputAsList("input.txt");
            var           passwordPart1ValidCount = inputList
                                                    .Select(inputLine => PasswordMinMax.ParseInput(inputLine))
                                                    .Where(password => password?.IsValid ?? false)
                                                    .Count();

            Console.WriteLine($"Number of valid passwords for part 1: {passwordPart1ValidCount}");
            var passwordPart2ValidCount = inputList
                                          .Select(inputLine => PasswordPositions.ParseInput(inputLine))
                                          .Where(password => password?.IsValid ?? false)
                                          .Count();

            Console.WriteLine($"Number of valid passwords for part 2: {passwordPart2ValidCount}");
            Console.ReadLine();
        }
Example #20
0
 protected FileStream GetInputStream()
 {
     return(InputLoader.LoadInputsAsFileStream($"InputFiles/Day{Day}.txt"));
 }
Example #21
0
#pragma warning restore IDE0022 // Use block body for methods

        protected string GetInput()
        {
            return(InputLoader.LoadInputsFromFileAsString($"InputFiles/Day{Day}.txt"));
        }
Example #22
0
        static void Main2(string[] args)
        {
            double      purgeThreshold = .7;
            InputLoader loader         = new InputLoader();

            loader.LoadFile("digits.csv");
            StreamProcessor processor = new StreamProcessor(28, 28);

            //var count = processor.AddContextFeautres();
            //Debug.Print(count.ToString() + " context features added.");
            processor.GenerateRandomFeatures(1150);
            LinkedList <bool> rollingRightWrong = new LinkedList <bool>();
            int thresholdIdx = 2;
            int correct      = 0;
            int i            = 1;

            //for (int i = 1; i < 25000; i++) {
            while (true)
            {
                i = i % 25000;

                //Debug.Print(i.ToString());
                Label l;
                var   a = loader.AccessElement(i, out l);
                processor.SetNextFeautreContext(a, l);
                var output = processor.Predict();
                processor.Train();
                var best = output.BestResult();
                if (best != null && best.Item2 != 0)
                {
                    //Debug.Print(i.ToString() + "  " +
                    //    best.Item1.TextRepresentation + " "
                    //    + best.Item2.ToString());
                    //Debug.Print("Desired: " + processor.DataLabel.TextRepresentation);
                    bool guessedRight = processor.DataLabel.TextRepresentation == best.Item1.TextRepresentation;
                    rollingRightWrong.AddLast(guessedRight);
                    if (guessedRight)
                    {
                        correct++;
                    }
                    if (rollingRightWrong.Count() > 100)
                    {
                        if (rollingRightWrong.First())
                        {
                            correct--;
                        }
                        rollingRightWrong.RemoveFirst();
                    }
                }


                //if(processor.PurgeFeautres(purgeThreshold) > 1000) purgeThreshold+= .01;
                if (i % 400 == 0)
                {
                    Debug.Print("Idx: " + i.ToString() + " " + ((double)correct / 100).ToString());
                    processor.PrintUtil(thresholdIdx);
                    thresholdIdx += 2;
                    //string output2 = processor.DescribeAllFeatures();
                    //Debug.Print(output2);
                }
                i++;
            }
            //Get the ability to quickly serialize good heuristics for the future
        }
Example #23
0
        public static void solve()
        {
            var input = InputLoader.loadAsString("13").Split(",");

            input[0] = "2";

            var screen   = new Dictionary <Tuple <Int64, Int64>, Int64>();
            var computer = new IntcodeComputer(input);

            var   joystick = 0;
            Int64 score    = 0;

            do
            {
                var output = computer.execute(new int[] { joystick });

                Int64 ballX   = 0;
                Int64 paddleX = 0;
                for (int i = 0; i < output.Length / 3; i++)
                {
                    var offset = i * 3;

                    var x        = output[offset];
                    var y        = output[offset + 1];
                    var position = Tuple.Create(x, y);
                    var value    = output[offset + 2];

                    if (x == -1 && y == 0)
                    {
                        score = value;
                    }
                    else
                    {
                        screen[position] = value;
                    }

                    if (value == 3)
                    {
                        paddleX = x;
                    }

                    if (value == 4)
                    {
                        ballX = x;
                    }
                }

                if (ballX > paddleX)
                {
                    joystick = 1;
                }
                else if (ballX < paddleX)
                {
                    joystick = -1;
                }
                else
                {
                    joystick = 0;
                }
            }while (hasBlocksLeft(screen));

            Console.WriteLine(score);
        }
Example #24
0
        static void Main(string[] args)
        {
            List <string> maze = new List <string>();

            foreach (string line in InputLoader.LoadByLines("input.txt"))
            {
                maze.Add(line);
            }

            // Maze walker
            int           x     = FindMazeStart(maze);
            int           y     = 0;
            EDirections   dir   = EDirections.eDown;
            int           steps = 0;
            StringBuilder sb    = new StringBuilder();

            while (true)
            {
                switch (dir)
                {
                case EDirections.eUp:
                    y--;
                    break;

                case EDirections.eDown:
                    y++;
                    break;

                case EDirections.eLeft:
                    x--;
                    break;

                case EDirections.eRight:
                    x++;
                    break;
                }
                steps++;

                if (maze[y][x] == '+') // direction change
                {
                    switch (dir)
                    {
                    case EDirections.eUp:
                        if ((maze[y][x - 1] == '-') || char.IsLetter(maze[y][x - 1]))
                        {
                            dir = EDirections.eLeft;
                        }
                        else if ((maze[y][x + 1] == '-') || char.IsLetter(maze[y][x + 1]))
                        {
                            dir = EDirections.eRight;
                        }
                        break;

                    case EDirections.eDown:
                        if ((maze[y][x - 1] == '-') || char.IsLetter(maze[y][x - 1]))
                        {
                            dir = EDirections.eLeft;
                        }
                        else if ((maze[y][x + 1] == '-') || char.IsLetter(maze[y][x + 1]))
                        {
                            dir = EDirections.eRight;
                        }
                        break;

                    case EDirections.eLeft:
                        if ((maze[y - 1][x] == '|') || char.IsLetter(maze[y - 1][x]))
                        {
                            dir = EDirections.eUp;
                        }
                        else if ((maze[y + 1][x] == '|') || char.IsLetter(maze[y + 1][x]))
                        {
                            dir = EDirections.eDown;
                        }
                        break;

                    case EDirections.eRight:
                        if ((maze[y - 1][x] == '|') || char.IsLetter(maze[y - 1][x]))
                        {
                            dir = EDirections.eUp;
                        }
                        else if ((maze[y + 1][x] == '|') || char.IsLetter(maze[y + 1][x]))
                        {
                            dir = EDirections.eDown;
                        }
                        break;
                    }
                }
                else if (maze[y][x] == ' ') // Reached end of maze
                {
                    break;
                }
                else
                {
                    if (char.IsLetter(maze[y][x]))
                    {
                        sb.Append(maze[y][x]);
                    }
                }
            }
            Console.WriteLine(string.Format("Passed letters: {0}", sb.ToString()));
            Console.WriteLine(string.Format("Steps taken: {0}", steps));
            Console.ReadLine();
        }
Example #25
0
 public void ResetBind()
 {
     InputLoader.PlayerPrefsDelete(this.standardInputSave);
     InputLoader.PlayerPrefsLoad(this.defaultInputSave);
     this.UpdateAllButtons();
 }
        public static void solve()
        {
            var input = InputLoader.loadAsString("05").Split(",");

            var values = new int[input.Length];

            for (int i = 0; i < input.Length; i++)
            {
                values[i] = Int32.Parse(input[i]);
            }

            var register = 5;

            var current = 0;

            while (true)
            {
                var opCode = getOpCode(values[current]);

                if (opCode == OpCode.Add)
                {
                    var value1 = getParameterValue(values, current, 1);
                    var value2 = getParameterValue(values, current, 2);
                    var value3 = values[current + 3];

                    values[value3] = value1 + value2;

                    current += 4;
                }
                else if (opCode == OpCode.Mul)
                {
                    var value1 = getParameterValue(values, current, 1);
                    var value2 = getParameterValue(values, current, 2);
                    var value3 = values[current + 3];

                    values[value3] = value1 * value2;

                    current += 4;
                }
                else if (opCode == OpCode.Input)
                {
                    values[values[current + 1]] = register;

                    current += 2;
                }
                else if (opCode == OpCode.Output)
                {
                    register = values[values[current + 1]];

                    current += 2;
                }
                else if (opCode == OpCode.JumpIfTrue)
                {
                    var value1 = getParameterValue(values, current, 1);
                    var value2 = getParameterValue(values, current, 2);

                    if (value1 != 0)
                    {
                        current = value2;
                    }
                    else
                    {
                        current += 3;
                    }
                }
                else if (opCode == OpCode.JumpIfFalse)
                {
                    var value1 = getParameterValue(values, current, 1);
                    var value2 = getParameterValue(values, current, 2);

                    if (value1 == 0)
                    {
                        current = value2;
                    }
                    else
                    {
                        current += 3;
                    }
                }
                else if (opCode == OpCode.LessThan)
                {
                    var value1 = getParameterValue(values, current, 1);
                    var value2 = getParameterValue(values, current, 2);
                    var value3 = values[current + 3];

                    values[value3] = value1 < value2 ? 1 : 0;

                    current += 4;
                }
                else if (opCode == OpCode.Equals)
                {
                    var value1 = getParameterValue(values, current, 1);
                    var value2 = getParameterValue(values, current, 2);
                    var value3 = values[current + 3];

                    values[value3] = value1 == value2 ? 1 : 0;

                    current += 4;
                }
                else if (opCode == OpCode.Terminate)
                {
                    break;
                }
            }

            Console.WriteLine(register);
        }
Example #27
0
        static void Main(string[] args)
        {
            var inputList    = (args.Count() > 0) ? InputLoader.GetInputAsList(args[0]) : InputLoader.GetInputAsList("input.txt");
            var customsInput = new List <List <string> >();
            var i            = 0;

            customsInput.Add(new List <string>());
            foreach (var input in inputList)
            {
                if (!string.IsNullOrWhiteSpace(input))
                {
                    customsInput[i].Add(input);
                }
                else
                {
                    i++;
                    customsInput.Add(new List <string>());
                }
            }
            var customsText = new List <string>();

            foreach (var list in customsInput)
            {
                var passportText = "";
                list.ForEach(delegate(string e) { passportText += e; });
                customsText.Add(passportText);
            }
            // part 1
            var numberOfTotalAnswers = customsText
                                       .Select(anon => anon.Distinct())
                                       .Sum(anon => anon.Count());

            Console.WriteLine($"Number for part 1: {numberOfTotalAnswers}");
            // part 2 - very dirty way of doing it
            var customsMemberText      = new List <List <string> >();
            var customsResultIntersect = new List <int>();

            foreach (var list in customsInput)
            {
                var passportText = "";
                list.ForEach(delegate(string e) { passportText += " " + e; });
                customsMemberText.Add(passportText.Trim().Split(' ').ToList());
            }
            for (i = 0; i < customsMemberText.Count; i++)
            {
                var first = customsMemberText[i][0];
                for (int j = 1; j < customsMemberText[i].Count; j++)
                {
                    first = new string(first.Intersect(customsMemberText[i][j]).ToArray());
                }
                customsResultIntersect.Add(first.Length);
            }
            var part2Result = customsResultIntersect.Sum();

            Console.WriteLine($"Number for part 2: {part2Result}");
            Console.ReadLine();
        }
Example #28
0
        static void Main(string[] args)
        {
            var inputList      = (args.Count() > 0) ? InputLoader.GetInputAsList(args[0]) : InputLoader.GetInputAsList("input.txt");
            var passportsInput = new List <List <string> >();
            var i = 0;

            passportsInput.Add(new List <string>());
            foreach (var input in inputList)
            {
                if (!string.IsNullOrWhiteSpace(input))
                {
                    passportsInput[i].Add(input);
                }
                else
                {
                    i++;
                    passportsInput.Add(new List <string>());
                }
            }
            var passportsText = new List <string>();

            foreach (var list in passportsInput)
            {
                var passportText = "";
                list.ForEach(delegate(string e) { passportText += " " + e; });
                passportsText.Add(passportText.Trim());
            }
            var passports = passportsText.Select(anon => Passport.ParseString(anon)).ToList();

            Console.WriteLine($"Number of passports with all required fields (part 1): {passports.Where(anon => anon.HasRequiredFields).Count()}");
            Console.WriteLine($"Number of passports with correct fields (part 2): {passports.Where(anon => anon.HasRequiredFields && anon.AreFieldsValid).Count()}");
            Console.ReadLine();
        }
        public static void solve()
        {
            var             input     = InputLoader.loadAsStringArray("10");
            List <Asteroid> asteroids = load(input);

            for (int i = 0; i < asteroids.Count; i++)
            {
                for (int j = 0; j < asteroids.Count; j++)
                {
                    if (i == j)
                    {
                        continue;
                    }

                    var slope = getSlope(asteroids[i], asteroids[j]);

                    if (!asteroids[i].directions.ContainsKey(slope))
                    {
                        asteroids[i].directions[slope] = new List <Asteroid>();
                    }

                    asteroids[i].directions[slope].Add(asteroids[j]);
                }

                foreach (var asteroidsInDirection in asteroids[i].directions.Values)
                {
                    asteroidsInDirection.Sort((Asteroid a, Asteroid b) =>
                    {
                        var distance1 = getDistance(asteroids[i], a);
                        var distance2 = getDistance(asteroids[i], b);

                        return(distance1.CompareTo(distance2));
                    });
                }
            }

            Asteroid monitoringStation = getBestMonitoringStation(asteroids);

//            Console.WriteLine(monitoringStation.x + ","+ monitoringStation.y);

            var order = new List <Tuple <int, int> >(monitoringStation.directions.Keys);

            order.Sort((Tuple <int, int> a, Tuple <int, int> b) =>
            {
                var angle1 = getAngle(0, 0, a.Item1, a.Item2);
                var angle2 = getAngle(0, 0, b.Item1, b.Item2);

                return(angle1.CompareTo(angle2));
            });

            var vaporiseCount = 0;

            while (vaporiseCount < 200)
            {
                foreach (var tuple in order)
                {
                    var asteroidsInDirection = monitoringStation.directions[tuple];
                    if (asteroidsInDirection.Count > 0)
                    {
                        vaporiseCount++;

                        if (vaporiseCount == 200)
                        {
                            Console.WriteLine(asteroidsInDirection[0].x * 100 + asteroidsInDirection[0].y);
                        }

                        asteroidsInDirection.RemoveAt(0);
                    }
                }
            }
        }
        public static void solve()
        {
            var input = InputLoader.loadAsString("11").Split(",");

            var program = new Dictionary <Int64, Int64>();

            for (int i = 0; i < input.Length; i++)
            {
                program[i] = Int64.Parse(input[i]);
            }

            var computer = new IntcodeComputer(program);

            var panels = new Dictionary <Tuple <int, int>, int>();

            var robotPos = Tuple.Create(0, 0);
            var robotDir = Direction.Up;

            panels[robotPos] = 1;

            var minX = 0;
            var minY = 0;
            var maxX = 0;
            var maxY = 0;

            while (!computer.isHalted())
            {
                var currentColor = 0;
                if (panels.ContainsKey(robotPos))
                {
                    currentColor = panels[robotPos];
                }

                // Compute
                var outputs = computer.execute(new int[] { currentColor });

                // Rotate
                if (outputs[1] == 0)
                {
                    robotDir = rotateLeft(robotDir);
                }
                else
                {
                    robotDir = rotateRight(robotDir);
                }

                // Paint
                panels[robotPos] = (int)outputs[0];

                // Move
                robotPos = move(robotPos, robotDir);

                // Update min/max
                minX = Math.Min(minX, robotPos.Item1);
                minY = Math.Min(minY, robotPos.Item2);
                maxX = Math.Max(maxX, robotPos.Item1);
                maxY = Math.Max(maxY, robotPos.Item2);
            }

            for (int y = minY; y <= maxY; y++)
            {
                for (int x = minX; x <= maxX; x++)
                {
                    var pos = Tuple.Create(x, y);

                    if (panels.ContainsKey(pos) && panels[pos] == 1)
                    {
                        Console.Write('#');
                    }
                    else
                    {
                        Console.Write(' ');
                    }
                }

                Console.WriteLine();
            }
        }