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

1 回表示 (過去 30 日間)
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

採用された回答

Kirby Fears
Kirby Fears 2016 年 2 月 9 日
編集済み: Kirby Fears 2016 年 2 月 9 日
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 件のコメント
John BG
John BG 2016 年 2 月 10 日
it turns out that sudoku.m already has a counter implemented right above the GUI. sudoku.m needs sudoku_puzle.m to run but when I asked the question, after attaching sudoku.m I reached my 24h quota of up to 10 attachments. Still blocked.
I give you thumbs-up for good answer because your code may work in C, although not in MATLAB, is it ok for you to give me a thumbs-up for good question?
Kirby Fears
Kirby Fears 2016 年 2 月 11 日
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)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSudoku についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by