Is there a way for matlab to rule out 'tried' computations?

So I'm not sure if there is anything "wrong" with your code, I could imagine that randomly assigning N values of 1 to N2 possible positions and then hoping that it will fit into your constraints might take a lot of random guesses, though. And it might have to try every single possible combination before it got it, which is a lot.

Instead of randomly trying to solve it, how would you solve it by hand? Personally, I would go column by column, choosing a row to be assigned a 1 randomly, as long as it doesn't violate any of your conditions. Or in step by step directions...

  1. Set the board to zeros
  2. Start with column 1 and randomly choose a row from a list of available rows to assign a 1, let's call this row_1. Remove row_1 from the list of available rows.
  3. Move onto column 2 and randomly choose from this available list again.
  4. Repeat steps 2 and 3, increasing the column counter by one each time until we're done.
  5. If placing a 1 into our randomly chosen row violates are diagonal constraint, simply switch the current column with the column you previously assigned a 1 in the diagonal.

For N = 3, this might go something like this...

board = 0 0 0 % Initialize board
        0 0 0
        0 0 0
board = 1 0 0 % Randomly choose a row for column 1 to assign a 1
        0 0 0
        0 0 0
board = 1 0 0 % Randomly choose a row for column 2 to assign a 1
        0 1 0
        0 0 0
board = 1 0 0 % Oops, we violated our diagonal constraint, let's fix it 
        0 1 0 % by switching column 2 with column 1 (the other column with a 1 in the diagonal)
        0 0 0
board = 0 1 0
        1 0 0
        0 0 0
 board = 0 1 0 % Now our only possible location is in the (3,3) position... and we're done!
         1 0 0
         0 0 1

Hopefully, that makes sense. It's not really my best psuedocode ever. You should be able to use the code I provided previously, but add in the diagonal check and column switching to ensure your diagonal constraint isn't violated.

/r/matlab Thread Parent