Finish 2011-04-20 12:00:00 UTC

Simple 2

by Andreas Bonelli

Status: Passed
Results: 8425805 (cyc: 8, node: 328)
CPU Time: 4.796
Score: 21064.8
Submitted at: 2011-04-14 08:07:41 UTC
Scored at: 2011-04-14 08:10:48 UTC

Current Rank: 1507th (Highest: 34th )

Comments
Please login or create a profile.
Code
function board = solver(words, weights, n, penalty)
    
    words = words(:);
    weights = weights(:);
    
    nwords = numel(words);
    wlens = cellfun(@(x) length(x), words);
 
    toolong = wlens > n;
    if any(toolong);
        picks = ~toolong;
        words = words(picks);
        weights = weights(picks);
        wlens = wlens(picks);
    end
        
    [maxwlen,~] = max(wlens);
    ws = zeros(nwords, maxwlen);
    
    for i = 1:nwords
        ws(i,1:wlens(i)) = words{i};
    end
 
    %     letters = unique(words(:));
    %     letters = letters(2:end);
    
    scores = weights ./ (wlens + 0.5);
    
    [~,six] = sort(scores, 1, 'descend');
    
    ws_filter(six);
    
    rowpos = ones(ceil(n/2),1);
    rowspace = n * rowpos;    
    
    board = zeros(n);
    
    for wix = 1:nwords
        wlen = wlens(wix);
        w = ws(wix, 1:wlen);
        
        % check if word fits exactly into some row
        
        rowspaceleft = rowspace - wlen;
        
        zeroedrows = rowspaceleft==0;
        if any(zeroedrows);
            myrow = find(zeroedrows, 1, 'first');
        else
            myrow = find(rowspaceleft > min(wlens(wix:end)), 1, 'first');
            if isempty(myrow)
                myrow = find(rowspaceleft > 0, 1, 'first');
            end
            if isempty(myrow);
                break;
            end;
        end
        
        
        board(myrow*2-1, rowpos(myrow):rowpos(myrow)+wlen-1) = w;
        
        if numel(board) > 51*51; 
            disp('buh');
        end
        
        rowpos(myrow) = rowpos(myrow) + wlen + 1;
        rowspace(myrow) = n - rowpos(myrow) + 1;
        
        
    end
    
            
    function ws_filter(f)
        ws = ws(f,:);
        scores = scores(f,:);
        wlens = wlens(f,:);
        weights = weights(f,:);
    end
end