# Find longest line without any intersection

I want to find the longest line that can be drawn connecting the highs of any two bars that are within the given range. see the chart below So a brute force algorithm for this would look something like:

``````for i = start to end // i represents the first bar of the longest bar
for j = i to end // j represents the second bar of the longest bar
hi = H[i], hj = Hj[j]
length = distance(hi, hj) // using pythagoras you can find the length of the line
intersects = isLineIntersecting(i, j)
if (!intersects && length > longest)
longest = length, longestStart = i, longestEnd = j

function distance(a, b)
sqrt((bx-ax)^2 + (by-ay)^2) // normalise, absolute value, use pythagoras to get length

// to find whether a line intersects any bar inbetween, calculate for each bar, whether that bar's y value
// is lower than the candle's highest, if so, then the candle extends above the line and thus intersects.
function isLineIntersecting(startBar, endBar)
isLineBroken = 0;
for i from startBar to endBar
isLineBroken &= H[i] > m*i + b // work out what m, b is in y = mx + b

return isLineBroken
``````

Hope that puts you in the right direction.

Thanks. I have code that uses nested loops (two for loops from 1 to maxlengthofpattern). But it slows down my afl. I am looking for some clever stuff.

That's a completely different question though...

If you are hitting performance issues on a time consuming algorithm, you can either run it as a once off by storing it via a `StaticVarSet` or use `Status("first/lastvisiblebarindex")` to restrict the algo to only run on your visible bars.

eg, I only run my trade system when I click it or if I toggle the "realtime signals" to true.
When "realtime signals" is true, the chart lags in seconds as it goes over 100k bars. When I run it once and load via static var, there is no lag at all.

``````isRunSystem = ParamTrigger("Generate signals", "Start") || ParamToggle("Realtime generate signals", "No|Yes", 0);

if (isRunSystem)
{
}

// Otherwise, I just load it from the static vars

local nSignals;

g_3lh_signals = StaticVarGet("g_3lh_signals");
}
``````

If you want help to optimise your algo, you'd have a better chance of someone putting their time to helping you, if you showed your loops so readers can see what time complexity it's running in.

1 Like

@AlgoEnthusiast, if nested loops are the only way to do it, to achieve a much faster execution time, you should convert your AFL code to a DLL function using the free Amibroker Development Kit (ADK)

(It requires the knowledge to code and compile a DLL using Microsoft C++.)

See this kb article and/or search the forum for additional topics about its usage.

@AlgoEnthusiast - post the code. Discussion about code is pointless without the code.