Exemple #1
0
        private Result OperationAcc(List <InstructionOperation> instructionsMap)
        {
            Result result = new Result();
            int    index  = 0;

            InstructionOperation currOperation    = instructionsMap[index];
            List <int>           visitedOperation = new List <int>();

            while (!visitedOperation.Contains(index))
            {
                visitedOperation.Add(index);
                switch (currOperation.operation)
                {
                case "nop":
                    ++index;
                    break;

                case "jmp":
                    index += currOperation.argument;
                    break;

                case "acc":
                    result.accumulator += currOperation.argument;
                    ++index;
                    break;

                default:
                    break;
                }
                if (index >= instructionsMap.Count)
                {
                    break;
                }
                currOperation = instructionsMap[index];
            }

            if (visitedOperation.Contains(index))
            {
                result.isLooping = true;
            }

            return(result);
        }
Exemple #2
0
        private Result Part2(List <InstructionOperation> instructionsMap)
        {
            Result result;
            int    index  = 0;
            string oldIns = string.Empty;

            do
            {
                bool found = false;
                while (!found && index < instructionsMap.Count)
                {
                    InstructionOperation currIns = instructionsMap[index];

                    if (currIns.operation == "jmp")
                    {
                        found             = true;
                        oldIns            = currIns.operation;
                        currIns.operation = "nop";
                    }
                    else if (currIns.operation == "nop")
                    {
                        found             = true;
                        oldIns            = currIns.operation;
                        currIns.operation = "jmp";
                    }
                    ++index;
                }

                result = OperationAcc(instructionsMap);
                if (result.isLooping)
                {
                    instructionsMap[index - 1].operation = oldIns;
                }
                else
                {
                    break;
                }
            } while (index < instructionsMap.Count);

            return(result);
        }