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

2 views (last 30 days)
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

Accepted Answer

Kirby Fears
Kirby Fears on 9 Feb 2016
Edited: Kirby Fears on 9 Feb 2016
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);
finalValue = value;
counterOut = counterIn;
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);
% solution found - assign output values
b = a;
counterOut = counterIn;
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)
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)


Find more on Sudoku in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by