function board = solver(words, weights, n, penalty)
board = zeros(n);
for k = 1:length(words),
wordlengths(k)=length(words{k});
end
nwords= numel(words);
[B,index] = sortrows([wordlengths' weights'],[1 -2]);
k=1;
c=1;
current_stop_index = min(nwords, n*k); % check that we haven't run out of words
while (c+B(current_stop_index,1)-1) <= n,
% maybe be off if the last word in a column is longer thatn all the
% others
current_col_points = sum(B(((k-1)*n)+1:current_stop_index,2)) - penalty*B(k*n,1);
if current_col_points > 0,
r=1;
words_left = current_stop_index - n*(k-1);
for r = 1:min(n,words_left),
board(c:(c+B(r+(k-1)*n,1)-1),r) = words{index(r+(k-1)*n)};
end
end
c=c+B(current_stop_index,1)+1;
k=k+1;
current_stop_index = min(nwords, n*k);
end
end
|