private (long, IntCode) MoveRobot(IntCode intCode, int[] moves, ref bool end) { int[] movesNew = new int[moves.Length + 1]; for (int index = 0; index < moves.Length; index++) { movesNew[index] = moves[index]; } var returnValue = (0L, intCode); if (moves.Length == 0 || moves.Length > 0 && moves[moves.Length - 1] != 2) { IntCode intCodeCopy = intCode.DeepCopy(); intCode.SetNewReadBuffer(new long[1] { 1 }); long returnCode = intCode.RunProgram(); if (returnCode == 1) { movesNew[moves.Length] = 1; returnValue = MoveRobot(intCode, movesNew, ref end); if (!end) { intCode = intCodeCopy; } } else if (returnCode == 2) { end = true; return(movesNew.Length, intCode.DeepCopy()); } } if (end) { return(returnValue); } if (moves.Length == 0 || moves.Length > 0 && moves[moves.Length - 1] != 1) { IntCode intCodeCopy = intCode.DeepCopy(); intCode.SetNewReadBuffer(new long[1] { 2 }); long returnCode = intCode.RunProgram(); if (returnCode == 1) { movesNew[moves.Length] = 2; returnValue = MoveRobot(intCode, movesNew, ref end); if (!end) { intCode = intCodeCopy; } } else if (returnCode == 2) { end = true; return(movesNew.Length, intCode.DeepCopy()); } } if (end) { return(returnValue); } if (moves.Length == 0 || moves.Length > 0 && moves[moves.Length - 1] != 4) { IntCode intCodeCopy = intCode.DeepCopy(); intCode.SetNewReadBuffer(new long[1] { 3 }); long returnCode = intCode.RunProgram(); if (returnCode == 1) { movesNew[moves.Length] = 3; returnValue = MoveRobot(intCode, movesNew, ref end); if (!end) { intCode = intCodeCopy; } } else if (returnCode == 2) { end = true; return(movesNew.Length, intCode.DeepCopy()); } } if (end) { return(returnValue); } if (moves.Length == 0 || moves.Length > 0 && moves[moves.Length - 1] != 3) { IntCode intCodeCopy = intCode.DeepCopy(); intCode.SetNewReadBuffer(new long[1] { 4 }); long returnCode = intCode.RunProgram(); if (returnCode == 1) { movesNew[moves.Length] = 4; returnValue = MoveRobot(intCode, movesNew, ref end); //if (!end) { intCode = intCodeCopy; } } else if (returnCode == 2) { end = true; return(movesNew.Length, intCode.DeepCopy()); } } return(returnValue); }