%%********************************************************************************************
%  Author: Tim Chartier
%  Title:  coastline.m
%  Description:  This code creates 2D fractal coastlines.
%*********************************************************************************************
%*********************************************************************************************
%
%% Set input parameters
iterates = 8;      % set number of iterates

% Define the 0th (starting) iterate
xValues = [0 0];
yValues = [0 1];

%% Plot 0th iterate
axisEdges = [-.5 .5 0 1];
axes('Color',[102/255 145/255 210/255],'Xtick',[],'Ytick',[])  
hold on
fill([xValues, axisEdges(1), axisEdges(1)],[yValues,axisEdges(4),axisEdges(3)],[81/255 210/255 78/255]), 
axis(axisEdges)
hold off
pause

%% Perform iterates to create 2D coastline
for level=1:iterates
    scale = (1/2)^(level)/sqrt(2);  % adjust 0.05 and 0.9 for effect 
    xValuesTmp = [];
    yValuesTmp = [];
    for i=1:length(xValues)-1
        xValuesTmp = [xValuesTmp xValues(i)];
        yValuesTmp = [yValuesTmp yValues(i)];
        a = -1; b = 1;
        xRand = (a + (b-a)*rand);
        yRand = (a + (b-a)*rand);
        xValueNew = mean([xValues(i),xValues(i+1)])+ xRand*scale;
        yValueNew = mean([yValues(i),yValues(i+1)])+ yRand*scale     ;
        xValuesTmp = [xValuesTmp xValueNew];
        yValuesTmp = [yValuesTmp yValueNew];    
    end
    xValuesTmp = [xValuesTmp xValues(end)];
    yValuesTmp = [yValuesTmp yValues(end)];
    xValues = xValuesTmp;
    yValues = yValuesTmp;
    % Plot resulting coastline
    axisEdges = [-.5 .5 0 1];
    axes('Color',[102/255 145/255 210/255],'Xtick',[],'Ytick',[])
    hold on
    fill([xValues, axisEdges(1), axisEdges(1)],[yValues,axisEdges(4),axisEdges(3)],[81/255 210/255 78/255]), 
    axis(axisEdges)
    hold off
    pause(0.2)
end 


