Example #1
0
 /// <summary>
 /// Copy constructor.
 /// </summary>
 internal Snapshot(Snapshot other)
 {
     CurrentUnit = other.CurrentUnit;
     Field = new Field(other.Field);
     Finished = other.Finished;
     Score = other.Score;
     UnitIndex = other.UnitIndex;
     UnitsQueue = other.UnitsQueue;
     UnitHistory = new List<Unit>(other.UnitHistory);
     FieldEstimate = other.FieldEstimate;
     PrevUnitClearedLines = other.PrevUnitClearedLines;
 }
Example #2
0
		public SolutionViewModel(ExecutionResult result, Snapshot initialSnapshot)
		{
			InitialSnapshot = initialSnapshot;
			CurrentSnapshot = initialSnapshot;
			CurrentIndex = 0;
			Commands = result.Commands;
			Estimate = result.Estimate;

			MoveNextCommand = new DelegateCommand(MoveNext, () => CurrentIndex < Commands.Length);
			ResetCommand = new DelegateCommand(Reset);
			PlayCommand = new DelegateCommand(Play);
			MoveToFinalCommand = new DelegateCommand(MoveToFinal);
		}
Example #3
0
        private static IEnumerable<ExecutionResult> Calculate(
			Snapshot baseSnapshot,
			MoveDirection? move,
			ExecutionOptions options,
			int depth,
			double minEstimate)
        {
            var snapshot = move.HasValue
                ? Game.MakeMove(baseSnapshot, move.Value)
                : baseSnapshot;
            if (snapshot == null) // illegal move
                yield break;
            var estimate = SnapshotEvaluate(snapshot, options);

            bool nextUnit = snapshot.UnitIndex > baseSnapshot.UnitIndex;
            // stop recursion
            if (snapshot.Finished || depth <= 0 || estimate < minEstimate || nextUnit) // TODO: some diff
            {
                yield return new ExecutionResult
                {
                    Commands = new [] { move.Value },
                    Estimate = estimate,
                    Snapshot = snapshot
                };
                yield break;
            }

            var candidateMoves = (MoveDirection[])Enum.GetValues(typeof (MoveDirection));

            var childResults = candidateMoves
                .SelectMany(m => Calculate(snapshot, m, options, depth - 1, estimate))
                .OrderByDescending(r => r.Estimate)
                .Take((int)Math.Ceiling(options.MaxWidth));
            foreach (var result in childResults)
            {
                var commands = move.HasValue
                    ? result.Commands.Prepend(move.Value).ToArray()
                    : result.Commands;

                yield return new ExecutionResult
                {
                    Commands = commands,
                    Estimate = result.Estimate + CommandEncoding.GetWordsPower(commands) * options.PowerWordsBonus,
                    Snapshot = result.Snapshot
                };
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            int[] numberToSolve = args.Length == 1
                ? new[] {Convert.ToInt32(args[0])}
                : Enumerable.Range(0, 25).ToArray();

            var outputs = new List<Output>();

            foreach (var number in numberToSolve)
            {
                var file = string.Format(@"inputs\problem_{0}.json", number);
                Console.WriteLine("Processing file " + file);
                var input = JsonConvert.DeserializeObject<Input>(File.ReadAllText(file));
                Console.WriteLine("Seeds: " + input.SourceSeeds.Length);
                foreach (var seed in input.SourceSeeds)
                {
                    Console.WriteLine("Seed: " + seed);
                    Console.WriteLine("-----------------");
                    var snapshot = new Snapshot(input, seed);
                    var result = GeneticSolver.Run(snapshot);
                    Console.WriteLine("Score: " + result.Score);
                    Console.WriteLine("Options:");
                    Console.WriteLine(JsonConvert.SerializeObject(result.Options));
                    Console.WriteLine("Commands:");
                    //Console.WriteLine(string.Join("", result.Commands.Select(c => ((int)c).ToString())));
                    HashSet<string> usedWords;
                    var commandsStr = CommandEncoding.Encode(result.Commands, out usedWords);
                    Console.WriteLine("Different words: " + string.Join(", ", usedWords));
                    Console.WriteLine(commandsStr);

                    outputs.Add(new Output
                    {
                        Commands = commandsStr,
                        ProblemId = number,
                        Seed = seed
                    });
                }
                Console.WriteLine("__________________");
            }
            File.WriteAllText("solution.json", JsonConvert.SerializeObject(outputs.ToArray()));
            Console.WriteLine("Press ENTER to exit...");
            Console.ReadLine();
        }
Example #5
0
 private void ShowSnapshot(Snapshot snapshot)
 {
     background.DrawUnit(snapshot.Field, snapshot.CurrentUnit, snapshot.UnitIndex);
 }
Example #6
0
        public static Result Run(Snapshot snapshot)
        {
            var knownsPhrases = new[] {"r'lyeh", "ei!"};
            int iterations = 10;
            int populationSize = 12;
            int bestSize = 6;
            double mutationPercent = 0.3;

            Result globalBest = null;
            // Initialize population:
            var population = Enumerable.Range(0, populationSize)
                .Select(_ => Generate())
                .ToList();
            for (int i = 0; i < iterations; i++)
            {
                mutationPercent = mutationPercent * (iterations - i) / iterations;
                Console.WriteLine("========= Generation #" + i);
                var tasks = population
                    .ToDictionary(o => o, o => Task.Run(() => Calculate(snapshot, o)));
                Task.WaitAll(tasks.Values.ToArray());

                var results = tasks.Select(
                    item => new Result
                    {
                        Options = item.Key,
                        Score = item.Value.Result.Snapshot.Score,
                        UnitIndex = item.Value.Result.Snapshot.UnitIndex,
                        Commands = item.Value.Result.Commands
                    }).ToArray();

                var manyWordResults = results.Where(
                    r =>
                    {
                        HashSet<string> usedWords;
                        CommandEncoding.Encode(r.Commands, out usedWords);
                        usedWords.ExceptWith(knownsPhrases);
                        return usedWords.Count > 1;
                    }).ToArray();

                //if (manyWordResults.Length > 0)
                //{
                //	return manyWordResults.OrderByDescending(r => r.Score).First();
                //}

                int pos = 0;
                foreach (var result in results.OrderByDescending(r => r.Score))
                {
                    ++pos;
                    PrintResult(pos, result);
                }

                var bestResults = results
                    .OrderByDescending(r => r.Score).Take(bestSize)
                    .ToArray();

                if (globalBest == null || globalBest.Score < bestResults.First().Score)
                {
                    globalBest = bestResults.First();
                }

                population = new List<ExecutionOptions>(bestResults.Select(r => r.Options));

                for (int j = 0; j < populationSize - bestSize; j++)
                {
                    int firstIndex;
                    int secondIndex;
                    do
                    {
                        // TODO: carousel?
                        firstIndex = Random.Next(0, bestSize);
                        secondIndex = Random.Next(0, bestSize);
                    } while (firstIndex == secondIndex);
                    var child = Crossover(population[firstIndex], population[secondIndex]);
                    population.Add(child);
                }
                foreach (var options in population)
                {
                    Mutate(options, mutationPercent);
                }
            }
            return globalBest;
        }
Example #7
0
 private static ExecutionResult Calculate(Snapshot snapshot, ExecutionOptions options)
 {
     var request = new ExecutionRequest
     {
         Snapshot = snapshot,
         Options = options
     };
     var solver = new IterativeSearchSolver(1200); //new TraverseSolver();
     return solver.Solve(request).First();
 }
Example #8
0
 private static double SnapshotEvaluate(Snapshot snapshot, ExecutionOptions options)
 {
     if (snapshot.UnitHistory.Count <= 1) // new unit, so field has changed
     {
         snapshot.FieldEstimate = GetFieldEstimate(snapshot.Field, options);
     }
     return snapshot.Score
         + snapshot.FieldEstimate
         + GetUnitPositionBonus(snapshot.Field, snapshot.CurrentUnit, options);
 }