Measuring the perimeter of the von Koch Snowflake

Clear[p];
Manipulate[
Module[
{line,idx,measureLine,lineLength},
line=makeLine[iterations,initLine];
idx=Floor[p*(Length[line]-1)]+1;
measureLine=If[idx>1,traverseLineC[line[[;;idx]],length],{}];
lineLength=If[measureLine=={},0,lineLengthC[measureLine]];
Graphics[{Line[line],Thick,Red,Line[measureLine]},PlotRange->.6,PlotLabel->Style["Measured length  "<>ToString[lineLength],19],ImageSize->{350,410}]
],
{{iterations,5},0,8,1,ImageSize->Small,ControlType->SetterBar},
{{length,0.625,"segment length"},0.005,2.5,ControlType->Animator,AppearanceElements->{"PlayPauseButton","ProgressSlider"},AnimationRunning->False,ImageSize->Small},
{{p,1.0,"draw line"},0.0,1.0,ControlType->Animator,AppearanceElements->{"PlayPauseButton","ProgressSlider"},AnimationRunning->False,ImageSize->Small},
SaveDefinitions->True,ControlPlacement->Top,
Initialization:>(
initLine=N@Partition[Expand[RotationMatrix[Pi/2].#&/@{{-(1/(2 (Sqrt[3]))),-(1/2)},{-(1/(2 (Sqrt[3]))),(1/2)},{-(1/(2 (Sqrt[3])))+((Sqrt[3])/2),0}}],2,1,1];
fractalCL=Compile[{{line,_Real,2}},
Block[{partition=Partition[line,2,1]},
Table[Block[
{c=pts[[1,1]],d=pts[[1,2]],a=pts[[2,1]],b=pts[[2,2]]},
{{c,d},
{c+((a-c)/3),d+((b-d)/3)},
{(c+((a-c)/2))-(1/(2*Sqrt[3]))*(b-d),(d+((b-d)/2))+(1/(2*Sqrt[3]))*(a-c)},
{a-((a-c)/3),b-((b-d)/3)},{a,b}
}
],{pts,partition}]],
RuntimeOptions->"Speed",
Parallelization->True,
RuntimeAttributes->{Listable}
];
traverseLineC=Compile[{{line,_Real,2},{length,_Real}},
Block[{pts=Partition[line,2,1]},
Module[{acc=0.0,i=1,len=Length[pts],keep={pts[[1,1]]}},
While[i<len,
While[acc≤length&&i<len,
Block[{x1=pts[[i,1,1]],y1=pts[[i,1,2]],x2=pts[[i,2,1]],y2=pts[[i,2,2]]},
i++;
acc+=(Sqrt[(((x1-x2))^2)+(((y1-y2))^2)]);
];
];
acc=0.0;
PrependTo[keep,pts[[i,2]]];
];
Reverse[keep]
]],
RuntimeOptions->"Speed",Parallelization->True,RuntimeAttributes->{Listable}
];
lineLengthC=Compile[{{measureLine,_Real,2}},
Module[
{acc=0.0},
Do[acc+=Norm[measureLine[[i]]-measureLine[[i-1]]],{i,2,Length[measureLine]}
];
acc
],
RuntimeOptions->"Speed",Parallelization->True,RuntimeAttributes->{Listable}
];
clNest[n_,initLine_]:=Flatten[Nest[fractalCL,initLine,n],n+1];
makeLine[iterations_,initLine_]:=Block[{line0=clNest[iterations,initLine]},
Prepend[Delete[line0,{#}&/@Range[1,Length[line0]-1,5]],Last[line0]]];
)]

Credit: David Chan

Creation of this notebook was supported by IT Academy program of Information Technology Foundation for Education (HITSA).