예제 #1
0
        protected virtual async Task <GameResult> ExecuteAsync(Game game, KeepDoorOption keepDoorOption, CancellationToken token)
        {
            if (game == null)
            {
                throw new System.Exception(ErrorMessages.InvalidGameObject);
            }

            if (token.IsCancellationRequested)
            {
                token.ThrowIfCancellationRequested();
            }

            //Step 1: User choose first door
            int randomDoorIndex;
            int selectedDoorIndex;

            selectedDoorIndex = new System.Random().Next(game.Doors.Length);
            randomDoorIndex   = svc.ChooseFirstDoor(game, selectedDoorIndex);

            //Step 2: User does not keep door
            if (keepDoorOption == KeepDoorOption.NotKeepDoor)
            {
                var execludedDoorIndex = new List <int>()
                {
                    selectedDoorIndex, randomDoorIndex
                };
                selectedDoorIndex = Enumerable.Range(0, 3).Except(execludedDoorIndex).First();
            }

            svc.ChooseSecondDoor(game, selectedDoorIndex);

            return(svc.GetGameResult(game));
        }
예제 #2
0
 public async Task <IEnumerable <GameResult> > SimulateAsync(int noOfSimulations, KeepDoorOption keepDoorOption, CancellationToken token)
 {
     try
     {
         var games      = Enumerable.Range(0, noOfSimulations).Select(x => { return(new Game()
             {
                 index = x
             }); }).ToList();
         var gamesTasks = games.AsParallel().WithCancellation(token).Select(x => { return(ExecuteAsync(x, keepDoorOption, token)); });
         return(await Task.WhenAll(gamesTasks.ToList()).ConfigureAwait(false));
     }
     catch (Exception ex)
     {
         logger.LogError(ex.Message);
         throw;
     }
 }
        public async Task <IActionResult> SimulateAsync([FromQuery] uint noOfSimulations, [FromQuery] KeepDoorOption keepDoorOption, CancellationToken token)
        {
            _logger.LogInformation($"Simulate started Total: {noOfSimulations}");

            var results = await svc.SimulateAsync((int)noOfSimulations, keepDoorOption, token);

            _logger.LogInformation($"Simulate completed Total: {noOfSimulations}");

            var summary = new GamesResultSummary
            {
                TotalWin   = results.Count(x => x == GameResult.Win),
                TotalLoose = results.Count(x => x == GameResult.Loose)
            };

            return(new ObjectResult(summary));
        }