001package ball.game.sudoku;
002/*-
003 * ##########################################################################
004 * Game Applications and Utilities
005 * %%
006 * Copyright (C) 2010 - 2022 Allen D. Ball
007 * %%
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *      http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 * ##########################################################################
020 */
021import ball.annotation.ServiceProviderFor;
022import lombok.NoArgsConstructor;
023import lombok.ToString;
024
025/**
026 * Sudoku simple "rule-of-sums" {@link Rule} implementation.  Calculates the
027 * minimum maximum possible value for any cell and removes any greater
028 * numbers from consideration.
029 *
030 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
031 */
032@ServiceProviderFor({ Rule.class })
033@NoArgsConstructor @ToString
034public class RuleOfSums extends RuleOfElimination {
035    @Override
036    public boolean applyTo(Puzzle puzzle) {
037        var modified = false;
038
039        for (;;) {
040            if (iterate(puzzle)) {
041                modified |= true;
042                super.applyTo(puzzle);
043            } else {
044                break;
045            }
046        }
047
048        return modified;
049    }
050
051    private boolean iterate(Puzzle puzzle) {
052        var modified = false;
053
054        for (var cell : puzzle.values()) {
055            if (! cell.isSolved()) {
056                var max = cell.last();
057
058                for (var map : puzzle.subMapsOf(cell)) {
059                    max = Math.min(max, max(map.values()));
060                }
061
062                var set = cell.tailSet(max, false);
063
064                modified |= (! set.isEmpty());
065                set.clear();
066            }
067        }
068
069        return modified;
070    }
071
072    protected int max(Iterable<Cell> iterable) {
073        return ((Digits.SUM - sum(iterable)) - (Digits.ALL.size() - (count(iterable) + 1)));
074    }
075}