# MATLAB – Sudoku Solver: solvedUpdate

Wow. So apparently my Sudoku Solver from my previous post got linked on someone’s Facebook. My tiny little blog normally gets 1-2 hits a day with spikes of about 15 or so. Yesterday, I apparently got 850 (!!) hits and today I’m at 217 and counting. Crazy thing, the internet.

So rather than sitting here in awe, mouth agape, I figure I’ll actually talk about my code some, as promised. The majority of it is commented to my liking, but the two functions at the end, `solvedUpdate` and `subsetUpdate`, could use a little attention. Today, I’ll comment on `solvedUpdate`.

### solvedUpdate

```% Solved Update
%
%   This generic function is used to update rows, columns, or squares. All
%   the current values of the puzzle matrix are removed from the
%   possibilities matrix.
function poss_out = solvedUpdate(puzz_in, poss_in)
[num_rows num_cols] = size(puzz_in);
puz = reshape(puzz_in, 9, 1);
pos = reshape(poss_in, 9, 1);

ind_filled = 1:9;
ind_filled = ind_filled(puz ~= 0);
for ii = 1:numel(ind_filled)
pos{ind_filled(ii)} = [];
end

curr_vals = sort(puz(puz ~= 0));

for ii = 1:numel(curr_vals)
for jj = 1:9
po = pos{jj};
if isempty(po)
continue
end
pos{jj} = po(po ~= curr_vals(ii));
end
end

poss_out = reshape(pos, num_rows, num_cols);
end```

Here’s the complete function. As you can read from the first comment block, the purpose of this function is to update the possibilities cell matrix with all the values found in the puzzle matrix. That is, once a number is placed, this function is used to get rid of that number from the possibilities. Let’s break it down into chunks.

```function poss_out = solvedUpdate(puzz_in, poss_in)
[num_rows num_cols] = size(puzz_in);
puz = reshape(puzz_in, 9, 1);
pos = reshape(poss_in, 9, 1);

...

poss_out = reshape(pos, num_rows, num_cols);
end```

So this function is pretty simple. To make sure it’s usable against rows, columns, and squares, the first thing I do is find the number of rows and columns of the input puzzle, and then reshape the puzzle and possible; at the end of the code, I reshape the output to its original form.

```    ind_filled = 1:9;
ind_filled = ind_filled(puz ~= 0);
for ii = 1:numel(ind_filled)
pos{ind_filled(ii)} = [];
end```

At this point, we simply find which indices in the puzzle matrix are filled. Each filled puzzle location then has its subsequent possible location set to an empty set.

```    curr_vals = sort(puz(puz ~= 0));

for ii = 1:numel(curr_vals)
for jj = 1:9
po = pos{jj};
if isempty(po)
continue
end
pos{jj} = po(po ~= curr_vals(ii));
end
end```

Next, we find the solved values (which are stored in `curr_vals`) and then we remove each of the current values from the possibilities matrix.

And that’s it for this function! Tomorrow, I’ll break down `subsetUpdate`.