function [ indices board ] = NTowersPuzzle( varargin )
% [Indices] = NTowersPuzzle( [entry]);
% [Indices Board] = NTowersPuzzle( [entry]);
%
% Input formats:
% NTowersPuzzle( [empty] or [invalid] ) => default
% NTowersPuzzle( P ) => startposition is (P, P)
% NTowersPuzzle( L, C) => startposition is (L, C)
% NTowersPuzzle( L, C, N) => startposition is (L, C) on N-by-N board
%
% This is my very limited version of the Eight Queens Puzzle (chess).
% It produces a N-number Towers on a N-by-N chess board, ence the name.
% The board is considered to be a N-by-N matrix.
% The pieces positions are signed by ONEs and the positions without pieces
% are signed by ZEROs.
% The user is allowed to decide the position of the starting piece.
% If not empty or invalid input, the default board size is 8-by-8.
% If starting piece position is invalid, it produces random position.
% The function itself may return two different arguments:
% the first is a vector with the coordinates of the pieces;
% the second is the matrix with signed position of the pieces.
% It prints the coordinates and the board.
%
% @ ACx // Janeiro 2013
[startL startC nLC] = treatEntry( varargin );
indices = zeros(1,nLC);
indices(1,startL) = startC;
valid = true;
while valid
[indices valid] = newplacement( indices, nLC, valid );
end
board = renderboard(indices, nLC);
printpos(indices, nLC);
disp(board)
disp('Thank you for stopping by...')
end
%%
function [a b nLC] = treatEntry( varargin )
a = 0; b = 0; t = 0; cc = 0; nLC = 0;
if nargin == 1
[~, cc] = size(varargin{1,1});
if cc == 3
nLC = varargin{1,1}{1,3}(1);
end
end
if cc > 0
a = varargin{1,1}{1,1}(1);
b = a;
if cc > 1
b = varargin{1,1}{1,2}(1);
end
end
if ~isnumeric(nLC) || nLC < 1 || nLC ~= round(nLC)
if isnumeric(nLC) && nLC < 1
nLC = abs(nLC);
end
if ~isnumeric(nLC) || nLC < 0 || nLC ~= round(nLC)
nLC = 8;
end
end
if ~isnumeric(a) || a < 1 || a > nLC || a ~= round(a)
t = a;
a = randi(nLC);
if cc == 1
b = a;
end
end
if ~isnumeric(b) || b < 1 || b > nLC || b ~= round(b)
if b == t
b = a;
else
b = randi(nLC);
end
end
end
%%
function [indEks valid] = newplacement( indEks, nLC, valid )
npieces = sum(indEks ~= 0);
if npieces == nLC
valid = false;
else
newindc = randi(nLC);
while any(newindc == indEks)
newindc = randi(nLC);
end
[~, newindl] = min(indEks);
indEks(newindl) = newindc;
end
end
%%
function [board] = renderboard(indeks, nLC)
board = zeros(nLC);
for i = 1:nLC
board(i,indeks(i)) = 1;
end
end
%%
function printpos(indEks, nLC)
for i = 1:nLC
fprintf(' L => ( %i , %i ) <= C \n', i, indEks(1,i))
end
end