Search in sources :

Example 6 with LongPieces

use of common.datastore.blocks.LongPieces 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 7 with LongPieces

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

the class UseCSVPathOutput method output.

@Override
public void output(List<PathPair> pathPairs, Field field, SizedBit sizedBit) throws FinderExecuteException {
    this.lastException = null;
    outputLog("Found path = " + pathPairs.size());
    AtomicInteger allCounter = new AtomicInteger();
    Map<PieceCounter, List<PathPair>> groupingByClockCounter = pathPairs.parallelStream().collect(Collectors.groupingBy(pathPair -> {
        List<OperationWithKey> operations = pathPair.getSampleOperations();
        return new PieceCounter(operations.stream().map(OperationWithKey::getPiece));
    }));
    List<PathPair> emptyValidList = Collections.emptyList();
    try (AsyncBufferedFileWriter writer = outputBaseFile.newAsyncWriter()) {
        writer.writeAndNewLine("使用ミノ,対応地形数,対応ツモ数 (対パターン),テト譜,ツモ (対パターン)");
        generator.blockCountersStream().parallel().map(blockCounter -> {
            // カウンターをインクリメント
            allCounter.incrementAndGet();
            // 組み合わせ名を取得
            String blockCounterName = blockCounter.getBlockStream().map(Piece::getName).collect(Collectors.joining());
            // パフェ可能な地形を抽出
            List<PathPair> valid = groupingByClockCounter.getOrDefault(blockCounter, emptyValidList);
            // パフェ可能な地形数
            int possibleSize = valid.size();
            // パフェ可能な地形のテト譜を連結
            String fumens = valid.stream().sorted(Comparator.comparing(PathPair::getPatternSize).reversed()).map(pathPair -> "v115@" + pathPair.getFumen()).collect(Collectors.joining(";"));
            // 対応できるパターンを重複なく抽出
            Set<LongPieces> possiblePatternSet = valid.stream().flatMap(PathPair::blocksStreamForPattern).collect(Collectors.toSet());
            // 対応できるパターン数
            int possiblePatternSize = possiblePatternSet.size();
            // パターンを連結
            String patterns = possiblePatternSet.stream().map(LongPieces::getPieces).map(blocks -> blocks.stream().map(Piece::getName).collect(Collectors.joining(""))).collect(Collectors.joining(";"));
            return String.format("%s,%d,%d,%s,%s", blockCounterName, possibleSize, possiblePatternSize, fumens, patterns);
        }).forEach(writer::writeAndNewLine);
        writer.flush();
    } catch (IOException e) {
        throw new FinderExecuteException("Failed to output file", e);
    }
    outputLog("Found piece combinations = " + allCounter.get());
    if (lastException != null)
        throw new FinderExecuteException("Error to output file", lastException);
}
Also used : OperationWithKey(common.datastore.OperationWithKey) Piece(core.mino.Piece) java.util(java.util) LongPieces(common.datastore.blocks.LongPieces) PatternGenerator(common.pattern.PatternGenerator) ReducePatternGenerator(entry.path.ReducePatternGenerator) IOException(java.io.IOException) FinderExecuteException(exceptions.FinderExecuteException) FinderInitializeException(exceptions.FinderInitializeException) Collectors(java.util.stream.Collectors) File(java.io.File) PieceCounter(common.datastore.PieceCounter) SizedBit(searcher.pack.SizedBit) Field(core.field.Field) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncBufferedFileWriter(lib.AsyncBufferedFileWriter) PathPair(entry.path.PathPair) PathEntryPoint(entry.path.PathEntryPoint) PathSettings(entry.path.PathSettings) OperationWithKey(common.datastore.OperationWithKey) 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) FinderExecuteException(exceptions.FinderExecuteException)

Example 8 with LongPieces

use of common.datastore.blocks.LongPieces 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 9 with LongPieces

use of common.datastore.blocks.LongPieces 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 10 with LongPieces

use of common.datastore.blocks.LongPieces 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

LongPieces (common.datastore.blocks.LongPieces)71 Test (org.junit.jupiter.api.Test)58 Piece (core.mino.Piece)42 PatternGenerator (common.pattern.PatternGenerator)38 LoadedPatternGenerator (common.pattern.LoadedPatternGenerator)36 Randoms (lib.Randoms)27 Collectors (java.util.stream.Collectors)22 Field (core.field.Field)19 Pieces (common.datastore.blocks.Pieces)16 LongTest (module.LongTest)16 List (java.util.List)14 Stream (java.util.stream.Stream)14 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)13 FieldFactory (core.field.FieldFactory)12 ArrayList (java.util.ArrayList)12 SizedBit (searcher.pack.SizedBit)12 MinoFactory (core.mino.MinoFactory)11 HashSet (java.util.HashSet)11 ExecutionException (java.util.concurrent.ExecutionException)10 BlockInterpreter (common.parser.BlockInterpreter)9