function matches=lettersgame(letters,nletters)
% function matches=lettersgame(letters,[nletters])
% solves the countdown letters game
% e.g.a=lettersgame('cedeinter')
% the optional argument nletters gives smallest output word size (default is 4)
%
if nargin<2
nletters=4; % default smallest word length to return
end
letters=strrep(letters,' ',''); % remove any spaces
letters=sort(lower(letters(:)))'; % change to sorted lower case and make into row
N=length(letters);
allwords=textread('scrabblewords.txt','%s'); % read dictionary as a cell array
allwords=char(allwords); % convert to a matrix
allwords=allwords(allwords(:,1)>'Z',:); % remove proper nouns
allwords=allwords(allwords(:,N+1)==' ',1:N); % remove all words longer than N
for nletters=nletters:N;
matches{nletters}=[];
% get a smaller dictionary with just nletters letters in each word.
if nletters<N
wordsnl=allwords(allwords(:,nletters+1)==' ',1:nletters); % remove all words longer than nletters
else
wordsnl=allwords;
end
wordsnl=wordsnl(wordsnl(:,nletters-1)>' ',1:nletters); % remove all words shorter than nletters
sortnl=sort(wordsnl')';
hash=32.^(1:nletters)';
hashtable=(sortnl-'a')*hash;
allcombs=nchoosek(letters,nletters); % get all combinations of nletter letters from selection
allcombs=unique(allcombs,'rows');
for ii=1:size(allcombs,1); % for each letter combination
combo=allcombs(ii,:)-'a';
% now find the indices of the sorted dictionary that match this sorted combination of letters
match=find((combo*hash==hashtable));
matches{nletters}=[matches{nletters}; wordsnl(match,:)]; % store the results
end
if nargout==0
fprintf(' Found %i x %i letters\n',size(matches{nletters},1),nletters)
if (size(matches{nletters},1)<10) | (nletters>6)
disp('')
disp(matches{nletters});
disp('')
end
end
end