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 "rule-of-elimination" {@link Rule} implementation.  If a digit is
027 * the solution to a {@link Cell} then it cannot be the solution to any
028 * other {@link Cell} in the row, column, or 3x3 nonet.
029 *
030 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
031 */
032@ServiceProviderFor({ Rule.class })
033@NoArgsConstructor @ToString
034public class RuleOfElimination extends Rule {
035    @Override
036    public boolean applyTo(Puzzle puzzle) {
037        var modified = false;
038
039        for (;;) {
040            if (iterate(puzzle)) {
041                modified |= true;
042            } else {
043                break;
044            }
045        }
046
047        return modified;
048    }
049
050    private boolean iterate(Puzzle puzzle) {
051        var modified = false;
052
053        for (var cell : puzzle.values()) {
054            if (cell.isSolved()) {
055                for (var map : puzzle.subMapsOf(cell)) {
056                    for (var other : map.values()) {
057                        if (other != cell) {
058                            modified |= other.removeAll(cell);
059                        }
060                    }
061                }
062            }
063        }
064
065        return modified;
066    }
067}