function board = solver(words, weights, n, penalty)
% Sample solver
% Copyright 2011 The MathWorks, Inc.
Lengths = cellfun('length',words);
if std(Lengths) == 0 && Lengths(1) == n
% disp('vertical or dot')
board = zeros(n);
[SW,index] = sort(weights,'descend');
if penalty*n < sum(SW(n+1:2*n))
for i = 1:n
board(i,:) = words{index(i)};
end
else
for i = 1:floor(n/2)
board(i*2,:) = words{index(i)};
end
end
else
[SortedL,index] = sort(Lengths);
SortedWords = words(index);
board = build_lines(SortedWords,SortedL,weights);
end
%--------------------------------------------------------------------------
function board = build_lines(SortedWords,SortedL,SW)
board = zeros(n);
WordsLeft = numel(words);
penalty_flag = penalty*n < sum(SW(n+1:2*n));
k = 1;
while WordsLeft > 0 && k <= n
L = cumsum(SortedL + 1);
L(1) = L(1) - 1;
OnOneLine = find(L<=n);
WordsLeft = WordsLeft - numel(OnOneLine);
LineWords = [];
for j = 1:numel(OnOneLine)
LineWords = [LineWords, SortedWords{j} 0];
end
board(k,1:numel(LineWords)) = LineWords;
SortedWords = SortedWords(OnOneLine(end)+1:end);
SortedL = SortedL(OnOneLine(end)+1:end);
if penalty_flag
k = k + 1;
else
k = k + 2;
end
end
end
% spy(board)
% drawnow
end
|