Search in sources :

Example 1 with Pieces

use of common.datastore.blocks.Pieces in project solution-finder by knewjade.

the class CheckmateUsingHoldTest method assertResult.

private void assertResult(Result result, Field field, int maxClearLine, LockedReachable reachable, List<Piece> blocks) {
    // Check blocks is same
    List<Piece> resultPieces = parseToBlocks(result);
    Piece lastHoldPiece = result.getLastHold();
    HashSet<LongPieces> pieces = OrderLookup.reverseBlocks(resultPieces, blocks.size()).stream().map(StackOrder::toStream).map(stream -> stream.map(block -> block != null ? block : lastHoldPiece)).map(LongPieces::new).collect(Collectors.toCollection(HashSet::new));
    assertThat(pieces).contains(new LongPieces(blocks));
    // Check can build result
    Operations operations = parseToOperations(result);
    List<MinoOperationWithKey> operationWithKeys = OperationTransform.parseToOperationWithKeys(field, operations, minoFactory, maxClearLine);
    boolean cansBuild = BuildUp.cansBuild(field, operationWithKeys, maxClearLine, reachable);
    assertThat(cansBuild).isTrue();
}
Also used : java.util(java.util) Pieces(common.datastore.blocks.Pieces) OperationTransform(common.parser.OperationTransform) common.datastore(common.datastore) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) LongPieces(common.datastore.blocks.LongPieces) ResultHelper(common.ResultHelper) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) LockedCandidate(core.action.candidate.LockedCandidate) Action(common.datastore.action.Action) MinoFactory(core.mino.MinoFactory) PerfectValidator(searcher.common.validator.PerfectValidator) OrderLookup(common.order.OrderLookup) Candidate(core.action.candidate.Candidate) FieldFactory(core.field.FieldFactory) ArgumentsProvider(org.junit.jupiter.params.provider.ArgumentsProvider) MinoRotation(core.srs.MinoRotation) StackOrder(common.order.StackOrder) LockedReachable(core.action.reachable.LockedReachable) MinoShifter(core.mino.MinoShifter) Piece(core.mino.Piece) Files(java.nio.file.Files) BuildUp(common.buildup.BuildUp) BlockInterpreter(common.parser.BlockInterpreter) IOException(java.io.IOException) Arguments(org.junit.jupiter.params.provider.Arguments) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Field(core.field.Field) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) LongTest(module.LongTest) ArgumentsSource(org.junit.jupiter.params.provider.ArgumentsSource) Piece(core.mino.Piece) LongPieces(common.datastore.blocks.LongPieces)

Example 2 with Pieces

use of common.datastore.blocks.Pieces in project solution-finder by knewjade.

the class PatternCSVPathOutput method output.

@Override
public void output(List<PathPair> pathPairs, Field field, SizedBit sizedBit) throws FinderExecuteException {
    this.lastException = null;
    outputLog("Found path = " + pathPairs.size());
    AtomicInteger validCounter = new AtomicInteger();
    AtomicInteger allCounter = new AtomicInteger();
    try (AsyncBufferedFileWriter writer = outputBaseFile.newAsyncWriter()) {
        writer.writeAndNewLine("ツモ,対応地形数,使用ミノ,未使用ミノ,テト譜");
        generator.blocksStream().parallel().map(blocks -> {
            // シーケンス名を取得
            String sequenceName = blocks.blockStream().map(Piece::getName).collect(Collectors.joining());
            // パフェ可能な地形を抽出
            List<PathPair> valid = pathPairs.stream().filter(pathPair -> {
                HashSet<? extends Pieces> buildBlocks = pathPair.blocksHashSetForPattern();
                return buildBlocks.contains(blocks);
            }).collect(Collectors.toList());
            // パフェ可能な地形数
            int possibleSize = valid.size();
            // パフェ可能ならカウンターをインクリメント
            allCounter.incrementAndGet();
            if (0 < possibleSize)
                validCounter.incrementAndGet();
            // パフェ可能な地形のテト譜を連結
            String fumens = valid.stream().sorted(Comparator.comparing(PathPair::getPatternSize).reversed()).map(pathPair -> "v115@" + pathPair.getFumen()).collect(Collectors.joining(";"));
            // 使うミノ一覧を抽出
            Set<PieceCounter> usesSet = valid.stream().map(PathPair::getBlockCounter).collect(Collectors.toSet());
            String uses = usesSet.stream().map(blockCounter -> {
                return blockCounter.getBlockStream().sorted().map(Piece::getName).collect(Collectors.joining());
            }).collect(Collectors.joining(";"));
            // 残せるミノ一覧を抽出
            PieceCounter orderPieceCounter = new PieceCounter(blocks.blockStream());
            String noUses = usesSet.stream().map(orderPieceCounter::removeAndReturnNew).distinct().map(blockCounter -> {
                return blockCounter.getBlockStream().sorted().map(Piece::getName).collect(Collectors.joining());
            }).collect(Collectors.joining(";"));
            return String.format("%s,%d,%s,%s,%s", sequenceName, possibleSize, uses, noUses, fumens);
        }).forEach(writer::writeAndNewLine);
        writer.flush();
    } catch (IOException e) {
        throw new FinderExecuteException("Failed to output file", e);
    }
    outputLog("");
    outputLog("perfect clear percent");
    outputLog(String.format("  -> success = %.2f%% (%d/%d)", 100.0 * validCounter.get() / allCounter.get(), validCounter.get(), allCounter.get()));
    if (lastException != null)
        throw new FinderExecuteException("Error to output file", lastException);
}
Also used : Piece(core.mino.Piece) Pieces(common.datastore.blocks.Pieces) PatternGenerator(common.pattern.PatternGenerator) Set(java.util.Set) ReducePatternGenerator(entry.path.ReducePatternGenerator) IOException(java.io.IOException) FinderExecuteException(exceptions.FinderExecuteException) FinderInitializeException(exceptions.FinderInitializeException) Collectors(java.util.stream.Collectors) File(java.io.File) HashSet(java.util.HashSet) PieceCounter(common.datastore.PieceCounter) SizedBit(searcher.pack.SizedBit) List(java.util.List) Field(core.field.Field) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncBufferedFileWriter(lib.AsyncBufferedFileWriter) PathPair(entry.path.PathPair) Comparator(java.util.Comparator) PathEntryPoint(entry.path.PathEntryPoint) PathSettings(entry.path.PathSettings) Set(java.util.Set) HashSet(java.util.HashSet) PieceCounter(common.datastore.PieceCounter) IOException(java.io.IOException) PathPair(entry.path.PathPair) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncBufferedFileWriter(lib.AsyncBufferedFileWriter) Piece(core.mino.Piece) List(java.util.List) FinderExecuteException(exceptions.FinderExecuteException)

Example 3 with Pieces

use of common.datastore.blocks.Pieces in project solution-finder by knewjade.

the class PercentCore method run.

void run(Field field, Set<LongPieces> searchingPiecesSet, int maxClearLine, int maxDepth) throws FinderExecuteException {
    List<Pieces> searchingPieces = new ArrayList<>(searchingPiecesSet);
    this.resultPairs = invoker.search(field, searchingPieces, maxClearLine, maxDepth);
    // 最低限の探索結果を集計する
    this.resultTree = new AnalyzeTree();
    for (Pair<Pieces, Boolean> resultPair : resultPairs) {
        Pieces pieces = resultPair.getKey();
        Boolean result = resultPair.getValue();
        resultTree.set(result, pieces);
    }
}
Also used : ArrayList(java.util.ArrayList) Pieces(common.datastore.blocks.Pieces) LongPieces(common.datastore.blocks.LongPieces) AnalyzeTree(common.tree.AnalyzeTree)

Example 4 with Pieces

use of common.datastore.blocks.Pieces in project solution-finder by knewjade.

the class PercentEntryPoint method run.

@Override
public void run() throws FinderException {
    output("# Setup Field");
    // Setup field
    Field field = settings.getField();
    Verify.field(field);
    // Setup max clear line
    int maxClearLine = settings.getMaxClearLine();
    Verify.maxClearLineUnder12(maxClearLine);
    // Output field
    output(FieldView.toString(field, maxClearLine));
    // Setup max depth
    // パフェに必要なミノ数
    int maxDepth = Verify.maxDepth(field, maxClearLine);
    output();
    // ========================================
    // Output user-defined
    output("# Initialize / User-defined");
    output("Max clear lines: " + maxClearLine);
    output("Using hold: " + (settings.isUsingHold() ? "use" : "avoid"));
    output("Drop: " + settings.getDropType().name().toLowerCase());
    output("Searching patterns:");
    // Setup patterns
    List<String> patterns = settings.getPatterns();
    PatternGenerator generator = Verify.patterns(patterns, maxDepth);
    // Output patterns
    for (String pattern : patterns) output("  " + pattern);
    output();
    // ========================================
    // Setup core
    output("# Initialize / System");
    ExecutorService executorService = createExecutorService();
    output("Version = " + FinderConstant.VERSION);
    output("Necessary Pieces = " + maxDepth);
    output();
    // ========================================
    // Holdができるときは必要なミノ分(maxDepth + 1)だけを取り出す。maxDepth + 1だけないときはブロックの個数をそのまま指定
    output("# Enumerate pieces");
    int piecesDepth = generator.getDepth();
    int popCount = settings.isUsingHold() && maxDepth < piecesDepth ? maxDepth + 1 : maxDepth;
    output("Piece pop count = " + popCount);
    if (popCount < piecesDepth) {
        output();
        output("####################################################################");
        output("WARNING: Inputted pieces is more than 'necessary blocks'.");
        output("         Because reduce unnecessary pieces,");
        output("         there is a possibility of getting no expected percentages.");
        output("####################################################################");
        output();
    }
    // 探索パターンの列挙
    NormalEnumeratePieces normalEnumeratePieces = new NormalEnumeratePieces(generator, maxDepth, settings.isUsingHold());
    Set<LongPieces> searchingPieces = normalEnumeratePieces.enumerate();
    output("Searching pattern size (duplicate) = " + normalEnumeratePieces.getCounter());
    output("Searching pattern size ( no dup. ) = " + searchingPieces.size());
    output();
    // ========================================
    // 探索を行う
    output("# Search");
    output("  -> Stopwatch start");
    Stopwatch stopwatch = Stopwatch.createStartedStopwatch();
    ThreadLocal<Candidate<Action>> candidateThreadLocal = createCandidateThreadLocal(settings.getDropType(), maxClearLine);
    ThreadLocal<? extends Reachable> reachableThreadLocal = createReachableThreadLocal(settings.getDropType(), maxClearLine);
    MinoFactory minoFactory = new MinoFactory();
    PercentCore percentCore = new PercentCore(executorService, candidateThreadLocal, settings.isUsingHold(), reachableThreadLocal, minoFactory);
    percentCore.run(field, searchingPieces, maxClearLine, maxDepth);
    AnalyzeTree tree = percentCore.getResultTree();
    List<Pair<Pieces, Boolean>> resultPairs = percentCore.getResultPairs();
    stopwatch.stop();
    output("  -> Stopwatch stop : " + stopwatch.toMessage(TimeUnit.MILLISECONDS));
    output();
    // ========================================
    // Output tree
    output("# Output");
    output(tree.show());
    output();
    // Output failed patterns
    int treeDepth = settings.getTreeDepth();
    if (piecesDepth < treeDepth)
        treeDepth = piecesDepth;
    output(String.format("Success pattern tree [Head %d pieces]:", treeDepth));
    output(tree.tree(treeDepth));
    output("-------------------");
    int failedMaxCount = settings.getFailedCount();
    // skip if failedMaxCount == 0
    if (0 < failedMaxCount) {
        output(String.format("Fail pattern (max. %d)", failedMaxCount));
        List<Pair<Pieces, Boolean>> failedPairs = resultPairs.stream().filter(pair -> !pair.getValue()).limit(failedMaxCount).collect(Collectors.toList());
        outputFailedPatterns(failedPairs);
    } else if (failedMaxCount < 0) {
        output("Fail pattern (all)");
        List<Pair<Pieces, Boolean>> failedPairs = resultPairs.stream().filter(pair -> !pair.getValue()).collect(Collectors.toList());
        outputFailedPatterns(failedPairs);
    }
    output();
    // ========================================
    output("# Finalize");
    if (executorService != null)
        executorService.shutdown();
    output("done");
}
Also used : Candidate(core.action.candidate.Candidate) PatternGenerator(common.pattern.PatternGenerator) Stopwatch(lib.Stopwatch) EntryPoint(entry.EntryPoint) AnalyzeTree(common.tree.AnalyzeTree) Field(core.field.Field) LongPieces(common.datastore.blocks.LongPieces) NormalEnumeratePieces(entry.searching_pieces.NormalEnumeratePieces) ExecutorService(java.util.concurrent.ExecutorService) MinoFactory(core.mino.MinoFactory) List(java.util.List) Pair(common.datastore.Pair) Pieces(common.datastore.blocks.Pieces) LongPieces(common.datastore.blocks.LongPieces) NormalEnumeratePieces(entry.searching_pieces.NormalEnumeratePieces)

Example 5 with Pieces

use of common.datastore.blocks.Pieces in project solution-finder by knewjade.

the class PackSearcherComparingParityBasedTest method testAllSRSValidPacksHeight6.

// 高さ6: パリティベースとの探索結果を比較する (同一ミノは2つまで)
@Test
void testAllSRSValidPacksHeight6() throws Exception {
    int width = 2;
    int height = 6;
    String resultPath = ClassLoader.getSystemResource("perfects/pack_height6.txt").getPath();
    List<TestData> testCases = Files.lines(Paths.get(resultPath)).map(line -> line.split("//")[0]).map(String::trim).filter(line -> !line.isEmpty()).map(line -> line.split("=")).map(split -> {
        Stream<Piece> blocks = BlockInterpreter.parse(split[0]);
        LongPieces pieces = new LongPieces(blocks);
        int count = Integer.valueOf(split[1]);
        return new TestData(pieces, count);
    }).collect(Collectors.toList());
    compareCount(width, height, testCases);
}
Also used : java.util(java.util) Pieces(common.datastore.blocks.Pieces) RecursiveMinoFields(searcher.pack.mino_fields.RecursiveMinoFields) BasicSolutionsCalculator(searcher.pack.solutions.BasicSolutionsCalculator) LongPieces(common.datastore.blocks.LongPieces) ColumnField(core.column_field.ColumnField) PieceCounter(common.datastore.PieceCounter) SizedBit(searcher.pack.SizedBit) MinoFactory(core.mino.MinoFactory) SeparableMinos(searcher.pack.SeparableMinos) CombinationIterable(common.iterable.CombinationIterable) FieldFactory(core.field.FieldFactory) AssertionsForClassTypes.assertThat(org.assertj.core.api.AssertionsForClassTypes.assertThat) MinoShifter(core.mino.MinoShifter) MappedBasicSolutions(searcher.pack.solutions.MappedBasicSolutions) Piece(core.mino.Piece) Files(java.nio.file.Files) InOutPairField(searcher.pack.InOutPairField) BlockInterpreter(common.parser.BlockInterpreter) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) UsingBlockAndValidKeySolutionFilter(searcher.pack.memento.UsingBlockAndValidKeySolutionFilter) ExecutionException(java.util.concurrent.ExecutionException) SolutionFilter(searcher.pack.memento.SolutionFilter) Field(core.field.Field) BasicSolutions(searcher.pack.calculator.BasicSolutions) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) LockedReachableThreadLocal(concurrent.LockedReachableThreadLocal) LongPieces(common.datastore.blocks.LongPieces) Stream(java.util.stream.Stream) Test(org.junit.jupiter.api.Test)

Aggregations

Pieces (common.datastore.blocks.Pieces)25 Field (core.field.Field)16 LongPieces (common.datastore.blocks.LongPieces)13 MinoFactory (core.mino.MinoFactory)12 Piece (core.mino.Piece)12 PatternGenerator (common.pattern.PatternGenerator)10 MinoShifter (core.mino.MinoShifter)10 ExecutionException (java.util.concurrent.ExecutionException)9 Test (org.junit.jupiter.api.Test)9 ColumnField (core.column_field.ColumnField)8 Collectors (java.util.stream.Collectors)8 LongTest (module.LongTest)8 PieceCounter (common.datastore.PieceCounter)7 BlockInterpreter (common.parser.BlockInterpreter)7 LoadedPatternGenerator (common.pattern.LoadedPatternGenerator)7 FieldFactory (core.field.FieldFactory)7 Files (java.nio.file.Files)7 Paths (java.nio.file.Paths)7 Stream (java.util.stream.Stream)7 SizedBit (searcher.pack.SizedBit)7