Stuart’s MATLAB Videos

Watch and Learn

Puzzler: Cleverness needed

I have been working on a side project and I found I needed the following algorithm:

MATLAB puzzler

Given a binary five by five matrix, I need to find the ‘1’ value that is in the position that has the lowest value in the spiral map above. I call that the target square. Once that target is found, then I need to return adelta xanddelta ythat will get me closer to that target.Delta xanddelta ymust be taken relative to the center square, and can only be from the set [-1, 0, 1].

As an example, given the matrix:

MATLAB puzzler

The ‘1’ in the (2,2) position in the matrix is the target because it maps to 9, and the other two ‘1’ values map to larger values, 11 and 18. From here, thedelta xis -1 anddelta yis 1.

If the target was 18, then the values would have beendelta xof 0 anddelta yof -1.

A final edge case, if the input matrix were all zeros, thendelta xanddelta yshould be chosen randomly, but still pulled from the set [-1, 0, 1].


This is not a particularly difficult algorithm to program if you use 25if, elseifstatements. However, I am looking to be a bit more clever with this. Please post your solution in the comments, make it a function of this form:

[deltaX, deltaY] = puzzler(inMatrix)


As always with these puzzlers, be sure to use the proper tags in the comments.

 [deltaX, deltaY] = puzzler(inMatrix)%% All the code so someone can just copy and paste it from the comments.  
|
  • print
  • send email

Comments

To leave a comment, please clickhereto sign in to your MathWorks Account or create a new one.