A
A
Alexander Sinitsyn2018-09-12 16:44:46
Algorithms
Alexander Sinitsyn, 2018-09-12 16:44:46

How to sort an array with elements depending on each other?

View array

[
  [
    "name1" => ["value" => "v", "depends" => ["name3, name 5"]
  ],
  [
    "name2" => ["value" => "v", "depends" => ["name1"]
  ],
  [
    "name3" => ["value" => "v", "depends" => ["name5"]
  ],
  [
    "name4" => ["value" => "v", "depends" => ["name1, name 2"]
  ],
  [
    "name5" => ["value" => "v", "depends" => []
  ],
]

Bring to mind
[
  [
    "name5" => ["value" => "v", "depends" => []
  ],
  [
    "name3" => ["value" => "v", "depends" => ["name5"]
  ],
  [
    "name1" => ["value" => "v", "depends" => ["name3, name 5"]
  ],
  [
    "name2" => ["value" => "v", "depends" => ["name1"]
  ],
  [
    "name4" => ["value" => "v", "depends" => ["name1, name 2"]
  ],
]

How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2018-09-12
@a_u_sinitsin

This is the so-called "topological sort". It is done through sequential depth-first search, starting with all possible elements.

алг recurse(поссылке x : элемент, поссылке результат : список)
  если x.метка = чёрный
    возврат
  если x.метка = серый
    стоп ("найдена циклическая зависимость")
  x.метка := серый
  для всех y : зависимых от x
    recurse(y)
  x.метка := чёрный
  результат.добавить(x)

алг main()
  для всех x : массив
    x.метка := белый
  result := []
  для всех x : массив
    recurse(x, result)

In short: we perform a standard depth-first search, starting with all elements, and on exit, we add the element to the list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question