コード例 #1
0
        static void Main(string[] args)
        {
            Directory.CreateDirectory("pathes");
            foreach (var file in Directory.EnumerateFiles(FileHelper.PatchDirectoryName("clusters.v2")).OrderBy(x => int.Parse(pathRegex.Match(x).Groups[1].Value)))
            {
                var code        = $"{int.Parse(pathRegex.Match(file).Groups[1].Value):D3}";
                var resFileName = Path.Combine(FileHelper.PatchDirectoryName("clusters.v2"), $"prob-{code}.path");
                if (File.Exists(resFileName))
                {
                    continue;
                }

                Console.Out.WriteLine(code);

                var problem = ProblemReader.Read(int.Parse(pathRegex.Match(file).Groups[1].Value));

                var records = File.ReadAllLines(file)
                              .Select(JsonConvert.DeserializeObject <ClusterRecord>)
                              .ToList();
                var startRecord = records.First(r => new V(r.X, r.Y).Equals(problem.Point));
                var hierarchy   = new ClusterHierarchy(records);
                hierarchy.CalculateDistancesBetweenChilds();
                var path = hierarchy.BuildPath(startRecord.cluster_hierarchy, null, new List <int>());

                //File.WriteAllLines($"pathes/prob-{code}", path.Select(p => p.Points[p.Points.Count / 2]).Select(p => $"{p.X}\t{p.Y}"));
                File.WriteAllLines(resFileName, path.Select(p => p.Id.ToString()));
            }
        }
コード例 #2
0
        public void TestMapConvert([Range(1, 300)] int id)
        {
            var problem = ProblemReader.Read(id);

            problem.Obstacles = new List <List <V> >();

            var state = problem.ToState().Map;
            var map   = new Map <PuzzleCell>(state.SizeX, state.SizeY);

            for (int x = 0; x < map.SizeX; x++)
            {
                for (int y = 0; y < map.SizeY; y++)
                {
                    map[new V(x, y)] = state[new V(x, y)] != CellState.Obstacle ? PuzzleCell.Inside : PuzzleCell.Outside;
                }
            }

            var converted = PuzzleConverter.ConvertMapToPoints(map);

            var expected = problem.Map;
            var i        = expected.IndexOf(converted[0]);

            if (i != 0)
            {
                expected = expected.Skip(i).Concat(expected.Take(i)).ToList();
            }

            converted.Should().BeEquivalentTo(expected, options => options.WithStrictOrdering());
        }
コード例 #3
0
        public void DoSomething_WhenSomething()
        {
            var problem = ProblemReader.Read("(0,0),(3,0),(3,1),(5,1),(5,2),(3,2),(3,3),(0,3)#(0,0)##");
            var state   = problem.ToState();

            Console.WriteLine(state.Map);
            var calc = new CellCostCalculator(state);

            calc.Cost.Should().Be(10);
            //2 2 2
            //1 * 3 2 1
            //* * 1
            //1 1 1
            //2 0 0 1 2
            //0 0 2
            calc.BeforeWrapCell("2,1");
            //2 2 1
            //1 * * 1 1
            //* * 0
            //1 1 2
            //2 0 0 2 2
            //0 0 3
            calc.Cost.Should().Be(13);
            calc.AfterUnwrapCell("2,1");
            calc.Cost.Should().Be(10);
        }
コード例 #4
0
        public void ToState2()
        {
            var problem = ProblemReader.Read(9);
            var state   = problem.ToState();

            state.Map.ToString()
            .Should()
            .Be(
                "###...################\n" +
                "###...################\n" +
                "####...###############\n" +
                "####...###############\n" +
                "####...###############\n" +
                "####...####......#####\n" +
                "####...#.........#####\n" +
                "#####............#####\n" +
                "##.........###########\n" +
                "........##############\n" +
                ".*......#.............\n" +
                "**###...#.............\n" +
                "######.......#########\n" +
                "######.......#########\n" +
                "######...#...#########\n" +
                "##########...#########\n" +
                "######.......#########\n" +
                "######.......#########\n" +
                "######.......#....####\n" +
                "######....#.......####\n" +
                "###.......#.......####\n" +
                "###.......#...########\n" +
                "###...#####...########\n" +
                "#######.......########\n" +
                "#######.......########\n" +
                "#######....###########");
        }
コード例 #5
0
        public void ToState()
        {
            var state       = ProblemReader.Read(1).ToState();
            var expectedMap = new Map(8, 3)
            {
                [new V(0, 0)] = CellState.Void, [new V(1, 0)] = CellState.Void, [new V(2, 0)] = CellState.Void, [new V(3, 0)] = CellState.Void, [new V(4, 0)] = CellState.Void, [new V(5, 0)] = CellState.Void, [new V(6, 0)] = CellState.Obstacle, [new V(7, 0)] = CellState.Obstacle,
                [new V(0, 1)] = CellState.Void, [new V(1, 1)] = CellState.Void, [new V(2, 1)] = CellState.Void, [new V(3, 1)] = CellState.Void, [new V(4, 1)] = CellState.Void, [new V(5, 1)] = CellState.Void, [new V(6, 1)] = CellState.Void, [new V(7, 1)] = CellState.Void,
                [new V(0, 2)] = CellState.Void, [new V(1, 2)] = CellState.Void, [new V(2, 2)] = CellState.Void, [new V(3, 2)] = CellState.Void, [new V(4, 2)] = CellState.Void, [new V(5, 2)] = CellState.Void, [new V(6, 2)] = CellState.Obstacle, [new V(7, 2)] = CellState.Obstacle,
            };

            state.Should()
            .BeEquivalentTo(
                new State(
                    new Worker
            {
                Position     = new V(0, 0),
                Manipulators = new List <V> {
                    new V(1, 0), new V(1, 1), new V(1, -1)
                }
            },
                    expectedMap,
                    new List <Booster>(),
                    1
                    ));
            state.Map.ToString()
            .Should()
            .Be(
                "......##\n" +
                ".*......\n" +
                "**....##");
        }
コード例 #6
0
        public void Read()
        {
            var source  = "(0,0),(10,0),(10,10),(0,10)#(0,0)#(4,2),(6,2),(6,7),(4,7);(5,8),(6,8),(6,9),(5,9)#B(0,1);B(1,1);F(0,2);F(1,2);L(0,3);X(0,9)";
            var problem = ProblemReader.Read(source);

            problem.ToString().Should().Be(source);
        }
コード例 #7
0
        public Solved Solve(State state2)
        {
            var list = Storage.GetSingleMeta(state2.ProblemId).Select(
                solutionMeta =>
            {
                if (!string.IsNullOrEmpty(solutionMeta.BuyBlob))
                {
                    return(null);
                }
                var solved = Emulator.ParseSolved(solutionMeta.SolutionBlob, solutionMeta.BuyBlob);
                if (solved.Actions.Any(aa => aa.Any(a => a is UseDrill || a is UseFastWheels)))
                {
                    return(null);
                }

                return(new { solutionMeta, solved });
            })
                       .Where(x => x != null)
                       .ToList();

            var selected = list.OrderBy(x => x.solutionMeta.OurTime).DistinctBy(x => x.solutionMeta.OurTime).Take(10).ToList();

            var    bestTime   = int.MaxValue;
            Solved bestSolved = null;

            foreach (var sss in selected)
            {
                var state = ProblemReader.Read(sss.solutionMeta.ProblemId).ToState();
                Emulator.Emulate(state, sss.solved);
                var postprocessor = new PostprocessorSimple(state, sss.solved);
                postprocessor.TransferSmall();

                var buildSolved = state.History.BuildSolved();

                try
                {
                    state = ProblemReader.Read(sss.solutionMeta.ProblemId).ToState();
                    Emulator.Emulate(state, buildSolved);
                    if (state.UnwrappedLeft > 0)
                    {
                        throw new InvalidOperationException("Bad mother f****r!");
                    }
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine(e);
                    continue;
                }

                var time = buildSolved.CalculateTime();
                if (time < bestTime)
                {
                    bestTime   = time;
                    bestSolved = buildSolved;
                }
            }

            return(bestSolved);
        }
コード例 #8
0
        public void METHOD()
        {
            var state = ProblemReader.Read(2).ToState();
            var clusterSourceLines = ClustersStateReader.Read(2);
            var clustersState      = new ClustersState(clusterSourceLines, state);

            clustersState.RootLevel.Should().Be(3);
            clustersState.RootIds.Should().Equal(0, 1);
        }
コード例 #9
0
        private static void PrepareDataToCluster()
        {
            var moves = new List <V> {
                new V(-1, 0), new V(1, 0), new V(0, -1), new V(0, 1), new V(-1, -1), new V(1, 1), new V(1, -1), new V(-1, 1)
            };

            Directory.CreateDirectory("maps2");

            var mapsPath = "../../../../problems/all/";

            foreach (var file in Directory.EnumerateFiles(mapsPath).Where(path => path.EndsWith(".desc")))
            {
                var problem = ProblemReader.Read(File.ReadAllText(file));
                var state   = problem.ToState();
                var map     = state.Map;

                var points  = new List <GraphPoint>();
                var vecToId = new ConcurrentDictionary <V, int>();

                for (int y = 0; y < map.SizeY; y++)
                {
                    for (int x = 0; x < map.SizeX; x++)
                    {
                        var point = new V(x, y);
                        if (map[point] == CellState.Obstacle)
                        {
                            continue;
                        }
                        var gp = new GraphPoint {
                            X = point.X, Y = point.Y, Id = vecToId.GetOrAdd(point, _ => vecToId.Count), ConnectedIds = new List <int>()
                        };

                        for (int m = 0; m < moves.Count; m++)
                        {
                            var point2 = point + moves[m];

                            if (!point2.Inside(map) || map[point2] == CellState.Obstacle)
                            {
                                continue;
                            }
                            gp.ConnectedIds.Add(vecToId.GetOrAdd(point2, _ => vecToId.Count));
                        }

                        points.Add(gp);
                    }
                }

                var newFileName = "maps2/" + file.Substring(mapsPath.Length, file.Length - mapsPath.Length - 5) + ".graph";
                File.WriteAllLines(newFileName, points.Select(JsonConvert.SerializeObject));
            }
        }
コード例 #10
0
        public void METHOD()
        {
            var list = Storage.GetSingleMeta(255).Select(
                solutionMeta =>
            {
                if (!string.IsNullOrEmpty(solutionMeta.BuyBlob))
                {
                    return(null);
                }
                var solved = Emulator.ParseSolved(solutionMeta.SolutionBlob, solutionMeta.BuyBlob);
                if (solved.Actions.Any(aa => aa.Any(a => a is UseDrill || a is UseFastWheels)))
                {
                    return(null);
                }

                return(new { solutionMeta, solved });
            })
                       .Where(x => x != null)
                       .ToList();

            var selected = list
                           .OrderBy(x => x.solutionMeta.OurTime)
                           .DistinctBy(x => x.solutionMeta.OurTime)
                           .Where(x => x.solutionMeta.AlgorithmId.Contains("spread-clone"))
                           .Take(10)
                           .ToList();

            foreach (var sss in selected
                     //    .Where(x => x.solutionMeta.OurTime == 2217)
                     )
            {
                Save(sss.solved, sss.solutionMeta.ProblemId, "-original" + sss.solved.CalculateTime());

                var state = ProblemReader.Read(sss.solutionMeta.ProblemId).ToState();
                Emulator.Emulate(state, sss.solved);
                var postprocessor = new PostprocessorSimple(state, sss.solved);
                postprocessor.TransferSmall();

                var buildSolved = state.History.BuildSolved();
                Console.Out.WriteLine($"current: {sss.solved.CalculateTime()}, processed: {buildSolved.CalculateTime()}");
                Save(buildSolved, sss.solutionMeta.ProblemId, "-fixed" + buildSolved.CalculateTime());

                state = ProblemReader.Read(sss.solutionMeta.ProblemId).ToState();
                Emulator.Emulate(state, buildSolved);
                if (state.UnwrappedLeft > 0)
                {
                    throw new InvalidOperationException("Bad mother f****r!");
                }
            }
        }
        // [TestCase(214, 20066, "CC")]
        // [TestCase(214, 20066, "CCC")]
        public void SolveOne(int problemId, int prevBestTime, string buy, bool useWheels, bool useDrill)
        {
            var solver = new ParallelDeepWalkSolver(2, new Estimator(useWheels, false, false), usePalka: false, useWheels: useWheels, useDrill: useDrill, buy.ToBuyBoosters());

            var solved = SolveOneProblem(solver, problemId);
            
            var nextTime = solved.CalculateTime();
            var map = ProblemReader.Read(problemId).ToState().Map;

            var mapScore = Math.Log(map.SizeX * map.SizeY, 2) * 1000;

            var prevScore = Math.Ceiling(mapScore * nextTime / prevBestTime);
            var nextScore = Math.Ceiling(mapScore);

            var cost = solved.BuyCost();
            var nextScoreWithCost = nextScore - cost;

            Console.Out.WriteLine($"{(nextScoreWithCost - prevScore > 0 ? "WIN" : "---")} Delta={nextScoreWithCost - prevScore}; PrevScore={prevScore};" +
                                  $"NextScore={nextScore}; Cost: {cost}; NextScoreWithCost={nextScoreWithCost}; " +
                                  $"PrevBestTime={prevBestTime}; NextTime={nextTime}");
        }
コード例 #12
0
        public State ReadFromFile(int id)
        {
            var problem = ProblemReader.Read(id);

            return(problem.ToState());
        }
コード例 #13
0
 public void ReadFromFile([Range(1, 300)] int problem)
 {
     var state = ProblemReader.Read(problem).ToState();
     var clusterSourceLines = ClustersStateReader.Read(problem);
     var clustersState      = new ClustersState(clusterSourceLines, state);
 }
コード例 #14
0
        public void IsReachableOnFirstMap(string from, string to, bool expected)
        {
            var problem = ProblemReader.Read(1);

            problem.ToState().Map.IsReachable(from, to).Should().Be(expected);
        }
コード例 #15
0
        private static List <(SolutionMeta @base, SolutionMeta best, double delta)> EnumerateBestSolutionTuples(double minDeltaCoeff)
        {
            var metas      = new List <(SolutionMeta @base, SolutionMeta best, double delta)>();
            var problemIds = MetaCollection.Distinct <int>("ProblemId", new BsonDocument()).ToList();

            foreach (var problemId in problemIds)
            {
                var map      = ProblemReader.Read(problemId).ToState().Map;
                var mapScore = Math.Log(map.SizeX * map.SizeY, 2) * 1000;

                var pipeline = new[]
                {
                    new BsonDocument
                    {
                        {
                            "$match", new BsonDocument(
                                new Dictionary <string, object>
                            {
                                { "ProblemId", problemId }
                            })
                        }
                    },
                    new BsonDocument()
                    {
                        {
                            "$group", new BsonDocument(
                                new Dictionary <string, object>
                            {
                                { "_id", "$MoneySpent" },
                                {
                                    "time", new BsonDocument(
                                        new Dictionary <string, string>
                                    {
                                        { "$min", "$OurTime" },
                                    })
                                },
                            })
                        }
                    }
                };
                var minScoresForProblem = MetaCollection
                                          .Aggregate <MinTimeResult>(pipeline)
                                          .ToList();
                var baselineSolution = minScoresForProblem.First(s => s._id == 0);

                var estimatedSolutions = minScoresForProblem.Select(
                    s =>
                {
                    var bestTime      = s.time;
                    var baseScore     = (int)Math.Ceiling(mapScore * bestTime / baselineSolution.time);
                    var score         = (int)Math.Ceiling(mapScore * bestTime / s.time);
                    var scoreWithCost = score - s._id;

                    // var limit = mapScore - mapScore / minDeltaCoeff;
                    var delta = scoreWithCost - baseScore < 1000 ? -1 : (double)(baselineSolution.time - s.time) / baselineSolution.time;

                    return(new { s, delta });
                })
                                         .ToList();

                var optimalSolution = estimatedSolutions
                                      .OrderByDescending(s => s.delta)
                                      .First();

                var best = MetaCollection.FindSync(
                    y => y.ProblemId == problemId &&
                    y.OurTime == optimalSolution.s.time &&
                    y.MoneySpent == optimalSolution.s._id)
                           .First();
                var @base = MetaCollection.FindSync(
                    y => y.ProblemId == problemId &&
                    y.OurTime == baselineSolution.time &&
                    y.MoneySpent == baselineSolution._id)
                            .First();

                metas.Add((@base, best, optimalSolution.delta));
            }

            return(metas);
        }
コード例 #16
0
        public void ReadFromFile([Range(1, 300)] int problem)
        {
            var fileName = Path.Combine(FileHelper.PatchDirectoryName("problems"), "all", $"prob-{problem:000}.desc");

            ProblemReader.Read(problem).ToString().Should().Be(File.ReadAllText(fileName));
        }