MATLAB Answers

is it possible to modify sudoku.m so that it counts how many times has called itself?

1 view (last 30 days)
John BG
John BG on 9 Feb 2016
Commented: Kirby Fears on 11 Feb 2016
Hi
I am reading Mr Cleve Moler's book about Matrix Experiments,
in chapter 18 there is sudoku.m
that automates 9x9 sudokus. Just starting the exercises, one of the questions is to count how long does it take to solve different sudokus.
I would like to count the amount of times that sudoku.m calls itself, I have tried to modify
X=sudoku(X,..) to [X,counter2]=sudoku(X,..,counter1)
but all my attempts return errors like counter2 not updated or too many inputs.
The attached function completes solving the sudoku but I don't know how to implement a counter of the times sudoku.m recurs.
Thanks for time and attention
John

Accepted Answer

Kirby Fears
Kirby Fears on 9 Feb 2016
Edited: Kirby Fears on 9 Feb 2016
John,
I'm not going to download the book or the sudoku.m file. Instead, here's an example called john_sudoku() with a recursive sub-function called minusOne(). I've implemented a counter for the number of times minusOne recurses. You can use this approach in your problem.
function [finalValue,counterOut] = john_sudoku(value)
% This function subtracts 1 from value repeatedly until 0 or
% negative value is reached. The final value is returned along with
% the recursion count.
counterIn = 0;
if value>0,
[finalValue,counterOut] = minusOne(value,counterIn);
else
finalValue = value;
counterOut = counterIn;
end
function [b,counterOut] = minusOne(a,counterIn)
a = a-1; % perform function operation
counterIn = counterIn+1; % increment counter
% test if recursion is needed
if a>0,
% recurse
[b,counterOut] = minusOne(a,counterIn);
else
% solution found - assign output values
b = a;
counterOut = counterIn;
end
Calling the function with an initial value of 10 returns a final value of 0 and a counter value of 10, since 1 was subtracted 10 times to reach 0.
[finalValue,counterOut] = john_sudoku(10)
  2 Comments
Kirby Fears
Kirby Fears on 11 Feb 2016
The code I gave is a Matlab function, not C. I specifically coded it as an example you can follow to change sudoku from:
X=sudoku(X,..) to [X,counter2]=sudoku(X,..,counter1)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!