function board = solver(words, weights, n, penalty)
%Board size
bSize = n;
%penalty
%mean(weights)
numWrds = length(words);
wrdLen = zeros(1,numWrds);
for i=1:numWrds
wrdLen(i) = length(words{i});
end;
extra = 0;
if (penalty >= mean(weights)) && (mean(wrdLen) > bSize/2)
extra = 1;
end;
workboard = zeros(bSize);
%Lazy solver.
%Sort the words according to weight, then start filling the
%board from top to bottom (using only every second row) to place words.
[srt_weights,srt_indWght] = sort(weights,'descend');
%[srt_weights,srt_indWght] = sort(weights,'ascend');
%[srt_length,srt_indLen] = sort(wrdLen,'descend');
[srt_length,srt_indLen] = sort(wrdLen,'ascend');
indUSE = srt_indLen;%srt_indWght;%
%{
i = 1;
j = 1;
while (i <= bSize)
%nextInd = srt_indWght(j);
nextInd = srt_indLen(j);
wordLen = length(words{nextInd});
workboard(i,1:wordLen) = words{nextInd};
i = i+2;
j = j+1;
end
%}
i=1;
j=1;
offSet = 0;
while (i <= bSize) %Next line
nextInd = indUSE(j);
wordLen = length(words{nextInd});
spaceAvail = 1 + bSize - offSet;
if (spaceAvail > wordLen)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Place the first word
workboard(i,1+offSet:wordLen+offSet) = words{nextInd};
%remove the index from the index list
if (j > 1)
if (j < length(indUSE))
indUSE = [indUSE(1:(j-1)) indUSE((j+1):length(indUSE))];
else
indUSE = [indUSE(1:(j-1))];
end;
else
indUSE = [indUSE(2:length(indUSE))];
end
offSet = offSet + 1 + wordLen;
%Find the next longest word that can fit
spaceAvail = 1 + bSize - offSet;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while (j < length(indUSE)) && (spaceAvail >= 0)
% Next word
nextInd = indUSE(j);
wordLen = length(words{nextInd});
if (spaceAvail > wordLen)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Place the first word
workboard(i,1+offSet:wordLen+offSet) = words{nextInd};
%remove the index from the index list
if (j > 1)
if (j < length(indUSE))
indUSE = [indUSE(1:(j-1)) indUSE((j+1):length(indUSE))];
else
indUSE = [indUSE(1:(j-1))];
end;
else
indUSE = [indUSE(2:length(indUSE))];
end
offSet = offSet + 1 + wordLen;
%Find the next longest word that can fit
spaceAvail = 1 + bSize - offSet;
j = j - 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end;
j = j+1;
end;
end;
i = extra + i+1;%i+2; %
offSet = 0;
j = 1;
end;
%{
%while (i <= bSize) && (j <= length(indUSE))
while (i <= bSize)
nextInd = indUSE(j);
wordLen = length(words{nextInd});
%while ((offSet + wordLen + 1) <= bSize) && (j <= length(indUSE))
while ((offSet + wordLen + 1) <= bSize) && (j <= length(indUSE))
workboard(i,1+offSet:wordLen+offSet) = words{nextInd};
if (j > 1)
indUSE = [indUSE(1:(j-1)) indUSE((j+1):length(indUSE))];
else
indUSE = [indUSE(2:length(indUSE))];
end
offSet = offSet + 1 + wordLen;
j = j+1;
nextInd = indUSE(j);
wordLen = length(words{nextInd});
end;
j = 1;
i = i+1;%i=i+2; %
%j = j+1;
offSet = 0;
end
%}
%penalty
board = workboard;
end
|