Winner GUO (asdf1)

Finish 2004-11-10 09:00:00 UTC

DELIRIOUS 2

by Edward Brian Welch

Status: Failed
Results:

Comments
Please login or create a profile.
Code
function mv = solver(ai,af,w)

rand('seed',2004);

nBlocks = max(ai(:));
[m,n] = size(ai);

% Make increment tables
% N=1, E=2, S=3, W=4
I = [0  1  0 -1];
J = [1  0 -1  0];

a = ai;
mv = [];

z = 1;
aStack = zeros(m,n,1000);
aStack(:,:,1) = ai;

while ~isequal(af,a)

    % Pick a random block
    bid = ceil(rand*nBlocks);
    [i,j] = find(a==bid);
    
    % Move it in a random direction
    r = ceil(rand*4);
    ni = i + I(r);
    nj = j + J(r);

    % Is it a legal move? Check edges
    if (ni<1) || (ni>m) || (nj<1) || (nj>n)
        continue
    end

    % Is it a legal move? Check for collision
    if a(ni,nj)>0
        continue
    end

    % Check distance
    % Get the target location
    [ti,tj] = find(af==bid);
    d = (ti-i)^2 + (tj-j)^2;
    dn = (ti-ni)^2 + (tj-nj)^2;
    % Have we moved closer to the target location?
    if (d<dn) && (rand>0.05)
        continue
    end
    
    % Move the block
    a(ni,nj) = bid;
    a(i,j) = 0;

    % Record the move
    mv(end+1,[1 2]) = [bid r];

    
    if z<1000,
        aStack(:,:,z) = a;
        z=z+1;
    end

end

% Delete Circuitous Moves
if 1,
    aStack(:,:,(z-1):end) = [];
    nCheck = size(aStack,3);
    n=1;
    while n<= (size(aStack,3)-2),
        tmp = sum( sum( abs( aStack - repmat(aStack(:,:,n), [1 1 size(aStack,3)]) ) ) );
        same = find(tmp==0);
        if length(same)>1,
            deletedMoves = [( same(1)+1 ):( same(end) )];
            mv(deletedMoves,:)=[];
            aStack(:,:,deletedMoves)=[];
            nCheck = nCheck - length(deletedMoves);
            %disp( sprintf('%d moves deleted', length(deletedMoves) ) );
        end
        n=n+1;
    end
end