def generate_sequence(k, n):
    sequence = list(range(k))  # Initialize with the first k elements
    used_triplets = set()

    def is_valid_triplet(triplet):
        # Check for repeated symbols
        if len(set(triplet)) < n:
            return False
        # Check for rearrangements
        triplet_sorted = tuple(sorted(triplet))
        return triplet_sorted not in used_triplets

    def add_to_sequence(signal):
        if len(sequence) >= n:
            new_triplet = (sequence[-(n - 1)], sequence[-1], signal)
            if is_valid_triplet(new_triplet):
                used_triplets.add(tuple(sorted(new_triplet)))
                sequence.append(signal)
                return True
        else:
            sequence.append(signal)
            return True
        return False

    signals = list(range(k))

    while len(sequence) < 100:  # Arbitrarily chosen length limit to avoid infinite loop
        added = False
        for signal in signals:
            if add_to_sequence(signal):
                added = True
                break
        if not added:
            break

    return sequence


k = 9
n = 3
sequence = generate_sequence(k, n)
print(sequence)
