Engee documentation
Notebook

The cantorial set

We are considering the implementation of an algorithm for generating a Cantor set, a fractal structure that is constructed by recursively removing the central parts of the segments.

Introduction

The Cantor set is a fractal obtained from a single segment by infinitely removing the middle third of each remaining segment. In practice, the algorithm can be limited to a certain level of recursion depth.

Why is it used?

The algorithm has educational value and is used in computer graphics to demonstrate recursion and fractal structures. It is also used as a simple example of a fractal and an unusual set in mathematics.

The main part

In [ ]:
# Определение размеров поля: ширина 81 и высота 5
const width = 81;
const height = 5;

Here, constants are set — the width and height of the field on which the image of the Cantor set will be built. The width is chosen as a power of three (), so that the division process is integer-based.

In [ ]:
# Рекурсивная функция построения множества Кантора
# Принимает:
# - lines — массив символов (поле для рисования)
# - start — начальная позиция (индекс) в строке
# - len — длина текущего сегмента
# - idx — номер строки (уровень рекурсии)
function cantor!(lines, start, len, idx)
    # Делим отрезок на три части
    seg = div(len, 3)

    # Если длина сегмента больше нуля, продолжаем рекурсию
    if seg > 0
        # Очищаем среднюю треть отрезка во всех строках ниже текущей
        for i in idx+1:height, j in start + seg + 1 : start + seg * 2
            lines[i, j] = ' '  # заменяем символ решётки на пробел
        end

        # Рекурсивный вызов для левой и правой трети
        cantor!(lines, start, seg, idx + 1)
        cantor!(lines, start + 2 * seg, seg, idx + 1)
    end
end
Out[0]:
cantor! (generic function with 1 method)

This is a key recursive function. cantor!, which builds a Cantor set. At each step, it divides the current segment into three parts and clears (replaces with a space) the middle third in the lines below the current recursion level. The process is repeated for the left and right thirds until the segment is less than 3 pixels.

In [ ]:
# Инициализируем весь массив символом '#'
lines = fill(UInt8('#'), height, width)

# Вызываем рекурсивную функцию, начинаем с самого верхнего уровня
cantor!(lines, 0, width, 1)

Creating a two-dimensional array lines, filled with the symbol # — this is the symbol that represents the remaining part of the set. Challenge cantor!(lines, 0, width, 1) begins the process of constructing the Cantor set from the beginning of the line (start=0), full width (len=width) and the first line (idx=1).

In [ ]:
# Печать результата построчно
for i in 1:height, j in 1:width
    print(Char(lines[i, j]), j == width ? "\n" : "")
end
#################################################################################
###########################                           ###########################
#########         #########                           #########         #########
###   ###         ###   ###                           ###   ###         ###   ###
# #   # #         # #   # #                           # #   # #         # #   # #

This is where the result is displayed. We go through each element of the array. lines, convert numeric values back to characters and print them. When the end of the line is reached (j == width) a transition to a new line is added.

Conclusion

We have reviewed the implementation of a classic fractal, the Cantor set, using the Julia programming language. We succeeded:

  • Build a fractal structure recursively.
  • Visualize the result in the form of text graphics.
  • Get acquainted with a simple example of using recursion and working with two-dimensional arrays in Julia.

This is a useful example for understanding recursion, fractals, and basic computer graphics. It can also be expanded to more complex visualizations or interactive applications.

The example was developed using materials from Rosetta Code