Finding values within an array that have the same distance to each other

Hi!

I am looking for a way (In Pine Script actually, but any other language would help to get the principle) to find values within an array that have the same “distance” to each other.

So for example within the arraw [1,2,3,5,7,8,9,10]

Those continous subarrays can be found:

Distance 1 = [1,2,3] + [7,8,9,10]

Distance 2 = [1,3,5,7,9] + [8, 10]

Distance 3 = [1,4,7,10] + [2,5,8]

Distance 4 = [1,5,9]

Distance 5 = [2,7] + [3,8] + [5,10]

Distance 6 = [1,7] + [2,8] + [3,9]

Distance 7 = [1,8] + [2,9] + [3,10]

Distance 8 = [1,9] + [2,10]

Distance 9 = [1,10]

How do I generate those subarrays with pinescript or any other language so I can later “filter” them further by restricting for example the distance min-max-range or the subarray min-max-count?

Thanks!

Sascha

Hi @skoeth, I don’t know pine script so I thought I’d just give it a go in python (aka pseudo code)… assuming the input list is a monotonically increasing sequence, this should do the trick:

def is_seen(sequences, value):
    for sequence in sequences:
        if value in sequence:
            return True

    return False


def get_distances(values):
    max_distance = max(values) - min(values)
    result = {}

    for distance in range(1, max_distance + 1):
        sequences = []

        for start_value in values:
            if is_seen(sequences, start_value):
                continue

            value = start_value

            while value + distance in values:
                if value == start_value:
                    sequences.append([start_value])

                value = value + distance
                sequences[-1].append(value)

        if sequences:
            result[distance] = sequences

    return result


values = [1, 2, 3, 5, 7, 8, 9, 10]
print(get_distances(values))

""" Output:
{ 1: [[1, 2, 3], [7, 8, 9, 10]],
  2: [[1, 3, 5, 7, 9], [8, 10]],
  3: [[2, 5, 8], [7, 10]],
  4: [[1, 5, 9], [3, 7]],
  5: [[2, 7], [3, 8], [5, 10]],
  6: [[1, 7], [2, 8], [3, 9]],
  7: [[1, 8], [2, 9], [3, 10]],
  8: [[1, 9], [2, 10]],
  9: [[1, 10]]}
"""
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.