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()); }
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())); } }
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); }
public void RunTest() { var cache = new MockCache(); var connectionStringBuilder = new SqliteConnectionStringBuilder() { DataSource = ":memory:" }; string connectionString = connectionStringBuilder.ToString(); var connection = new SqliteConnection(connectionString); var dbContextOptionsBuilder = new DbContextOptionsBuilder <IffleyRoutesRecordContext>(); dbContextOptionsBuilder.UseSqlite(connection); var repository = new IffleyRoutesRecordContext(dbContextOptionsBuilder.Options); repository.Database.OpenConnection(); repository.Database.EnsureCreated(); var styleSymbolManager = new StyleSymbolManager(repository, cache); var ruleManager = new RuleManager(repository, cache); var holdManager = new HoldManager(repository, cache, ruleManager); var gradeManager = new GradeManager(repository, cache); var problemReader = new ProblemReader(repository, cache, styleSymbolManager, ruleManager, holdManager, gradeManager); var validator = new ProblemRequestValidator(repository); var staticDataPopulater = new PopulateDatabaseWithStaticData(repository, existingDataFilePath); staticDataPopulater.Populate(); var populator = new PopulateDatabaseWithExistingProblems(repository, existingDataFilePath, validator); populator.Populate(false); }
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" + "#######....###########"); }
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" + "**....##"); }
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); }
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); }
public static void Register(CommandLineApplication app) { app.Command( "solve", (command) => { command.Description = "Solve all problems with all solvers"; command.HelpOption("-?|-h|--help"); var solverOption = command.Option( "-s|--solver", "Solver name prefix", CommandOptionType.SingleValue); var problemsOption = command.Option( "-p|--problems", "Single problem id or problem ids range", CommandOptionType.SingleValue); command.OnExecute( () => { var solvers = RunnableSolvers .Enumerate() .Select(x => x.Invoke()) .Where(x => !solverOption.HasValue() || solverOption.HasValue() && x.GetName().StartsWith(solverOption.Value())) .ToList(); var problemIds = new List <int>(); if (problemsOption.HasValue()) { if (int.TryParse(problemsOption.Value(), out var problemId)) { problemIds.Add(problemId); } else { var parts = problemsOption.Value().Split(new [] { ".." }, StringSplitOptions.RemoveEmptyEntries); var pStart = int.Parse(parts[0]); var pEnd = int.Parse(parts[1]); problemIds.AddRange(Enumerable.Range(pStart, pEnd - pStart + 1)); Console.WriteLine($"Will solve problems: {string.Join(", ", problemIds)}"); } } solvers.ForEach( solver => { ProblemReader .ReadAll() .Where(x => !problemIds.Any() || problemIds.Contains(x.ProblemId)) .ToList() .ForEach(problemMeta => Common.Solve(solver, problemMeta)); }); return(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); }
public static void Register(CommandLineApplication app) { app.Command( "solve-unsolved", (command) => { command.Description = "Create solutions for all nonexistent problem-solver pairs"; command.HelpOption("-?|-h|--help"); var threadsOption = command.Option( "-t|--threads", "Number of worker threads", CommandOptionType.SingleValue); command.OnExecute( () => { var threadsCount = threadsOption.HasValue() ? int.Parse(threadsOption.Value()) : Environment.ProcessorCount; var threads = Enumerable.Range(0, threadsCount).ToList(); Parallel.ForEach( threads, new ParallelOptions { MaxDegreeOfParallelism = threadsCount }, thread => { while (true) { var solvers = RunnableSolvers .Enumerate() .OrderBy(_ => Guid.NewGuid()) .Select(x => x.Invoke()) .ToList(); var problems = ProblemReader.ReadAll(); solvers.ForEach( solver => { var solved = Storage.EnumerateSolved(solver).Select(x => x.ProblemId); var unsolved = problems .Select(x => x.ProblemId) .Except(solved) .OrderBy(_ => Guid.NewGuid()) .ToList() .First(); Common.Solve(solver, problems.Find(x => x.ProblemId == unsolved), thread); }); } }); return(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)); } }
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!"); } } }
private static int GetOnlineTime(this SolutionMeta meta, string geckodriverExecName) { var problemPath = ProblemReader.GetProblemPath(meta.ProblemId); var solutionPath = Path.GetTempFileName(); File.WriteAllText(solutionPath, meta.SolutionBlob); var driverDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).FullName; var service = FirefoxDriverService.CreateDefaultService(driverDirectory, geckodriverExecName); var options = new FirefoxOptions { LogLevel = FirefoxDriverLogLevel.Error }; options.AddArgument("-headless"); var driver = new FirefoxDriver(service, options); driver.Navigate().GoToUrl("https://icfpcontest2019.github.io/solution_checker/"); var problemField = driver.FindElement(By.Id("submit_task")); var solutionField = driver.FindElement(By.Id("submit_solution")); var submitButton = driver.FindElement(By.Id("execute_solution")); var outputElement = driver.FindElement(By.Id("output")); var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(100)); problemField.SendKeys(problemPath); wait.Until(drv => outputElement.Text == "Done uploading task description"); solutionField.SendKeys(solutionPath); wait.Until(drv => outputElement.Text == "Done uploading solution"); submitButton.Click(); wait.Until(drv => outputElement.Text != "Done uploading solution"); var result = outputElement.Text; driver.Quit(); var match = Regex.Match(result, "Success! Your solution took (\\d+) time units\\."); var timeUnits = int.Parse(match.Groups[1].Captures[0].Value); return(timeUnits); }
// [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}"); }
public void MakeMapImage() { var sb = new StringBuilder(); var dir = Path.Combine(FileHelper.PatchDirectoryName("problems"), "all", "images"); var problems = ProblemReader.ReadAll(); foreach (var problemMeta in problems) { var map = problemMeta.Problem.ToState().Map; var bmp = new Image <Rgba32>(Configuration.Default, map.SizeX + 2, map.SizeY + 2, Rgba32.Black); foreach (var cell in map.EnumerateCells()) { bmp[cell.Item1.X + 1, cell.Item1.Y + 1] = GetColor(cell.Item2); } foreach (var booster in problemMeta.Problem.Boosters) { bmp[booster.Position.X + 1, booster.Position.Y + 1] = GetColor(booster.Type); } var factor = 1; if (map.SizeX < 100) { factor *= 2; } if (map.SizeX < 20) { factor *= 2; } bmp.Mutate(x => x.Resize(map.SizeX * factor, map.SizeY * factor, new BoxResampler())); bmp.Save(Path.Combine(dir, problemMeta.ProblemId + ".png")); sb.Append($"<img style=\"margin:10px\" src=\"{problemMeta.ProblemId}.png\" alt=\"{problemMeta.ProblemId} title=\"{problemMeta.ProblemId}\"\">"); } File.WriteAllText(Path.Combine(dir, "index.html"), sb.ToString()); }
public void IsReachableOnFirstMap(string from, string to, bool expected) { var problem = ProblemReader.Read(1); problem.ToState().Map.IsReachable(from, to).Should().Be(expected); }
public async Task ReadCurrentFromApi() { var problem = await ProblemReader.ReadCurrentFromApiAsync(); problem.Should().NotBeNull(); }
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); }
public ProblemController(ProblemReader problemReader, ProblemCreator problemCreator, IConfiguration configuration) : base(configuration) { this.problemReader = problemReader; this.problemCreator = problemCreator; }
public State ReadFromPuzzleFile(int id) { var problem = ProblemReader.ReadPuzzleTask(id); return(problem.ToState()); }
public State ReadFromFile(int id) { var problem = ProblemReader.Read(id); return(problem.ToState()); }
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)); }
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); }