Code covered by the BSD License  

Highlights from
Fast Sudoku Solver

image thumbnail
from Fast Sudoku Solver by Yue Wu
An algorithm to mimic human solving procedure for Sudoku puzzles

scan_sq(stat_sum,candi)
function [list,nums] = scan_sq(stat_sum,candi)
% Function: scan_sq
%           used for a desired sequence for filling unfilled grids in a
%           half-done sudoku puzzle
% 
% Input: stat_sum = 9x9 matrix caluates the number of pieces of information
%                   each unfilled grid has
%        candi = possible numbers for each grid
%                 {[2,4,5,8],[2,4,5,9],[2,4,5,8],3,[2,6,8,9],1,7,[4,6],[4,6,8];
%                 1,[3,5,9],[3,5,7,8],[5,6,7,8,9],4,[8,9],[3,6,8,9],2,[3,6,8];
%                 [2,3,4,7,8],6,[2,3,4,7,8],[7,8,9],[2,7,8,9],[2,8,9],[3,8,9],5,[1,3,4,8];
%                 9,[1,2,3],[1,2,3,7,8],4,[1,3,7,8],5,[2,3,6],[3,6,7],[3,6,7];
%                 [2,3,4,5,7,8],[2,3,4,5],6,[7,8,9],[3,7,8,9],[3,8,9],1,[3,4,7],[3,4,5,7];
%                 [3,4,5,7],[1,3,4,5],[1,3,4,5,7],2,[1,3,7],6,[3,5],8,9;
%                 [2,3,5,6],7,[1,2,3,5],[1,6,8],[1,2,3,6,8],[2,3,8],4,9,[1,3,5,6,8];
%                 [3,4,6],8,[1,3,4],[1,6,9],5,[3,4,9],[3,6],[1,3,6,7],2;
%                 [2,3,4,5,6],[1,2,3,4,5],9,[1,6,8],[1,2,3,6,8],7,[3,5,6,8],[1,3,6],[1,3,5,6,8];}
% Output: list = indices of unfilled grid
%         nums = possible numbers for each grid
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This is a sub-function of the main function sudoku_yue
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% By Yue Wu
% 10/05/2009
% ECE Dept, Tufts Univ.
% MA, Medford 02155
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% the basic idea is always to fill in the grid with most number of pieces of
% informations
% when the number of piece of information equals for two grid, then compare
% the number of possible number for each grid

p_num = setdiff(unique(stat_sum),0);
list = [];
nums = [];
for i = 1:numel(p_num)
    clear c_num tmp_ind
    c_num = p_num(end-i+1);
    tmp_ind = find(stat_sum == c_num);
    if numel(tmp_ind)>1
        clear num_times sq ix
        for j = 1:numel(tmp_ind)
            [x,y] = ind2sub([9,9],tmp_ind(j));
            num_times(j) = numel(candi{x,y});
        end
        [sq,ix] = sort(num_times);
        nums = [nums,sq];
    else
        ix = 1;
        nums = [nums,numel(candi{tmp_ind})];
    end
    list = [list,tmp_ind(ix)'];
end

Contact us at files@mathworks.com