Winner GUO (asdf1)

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

iter then rand but still lazy

by Tom

Status: Passed
Results: 6410449
CPU Time: 135.037
Score: 7325.61
Submitted at: 2004-11-03 14:41:54 UTC
Scored at: 2004-11-04 04:22:52 UTC

Current Rank: 1253rd

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

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 = [];

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];


end