Algorithm - Numbering for TOC (Table of Contents)

I want to implement a VBA function for Excel row numbers based on the depth of row grouping.

But I think the general TOC generation algorithm is more interesting.

The problem is this:

Given a list of "indentation" such as

One
 Two
  Three
   Four
 Five
Six

(the "indent level" can be considered well-known and part of the input data)

To create the following output:

1.    One
1.1    Two
1.1.1   Three
1.1.1.1  Four
1.2    Five
2.    Six

Of course, my code works and works ... and is also hidden under THWoS (The Heavy Weight of Shame)

+3
source share
2 answers

Use the stack for numbers. Scroll through each line and check the level of indentation for each line, while not a single indent will be level 1.

  • , , , ( , , - 3 1, )
  • , , , .
  • ,

- , a. .

, .

, , JavaScript :

const toc = `
One
 Two
  Three
   Four
 Five
  Six
  Seven
 Eight
Nine
Ten
`;

let stack = [];

toc.trim().split(/\n/g).forEach(line => {
  // Gets the identitation level with 1 being no indentation and so forth
  let level = line.match(/^\s*/)[0].length + 1;

  if (level > stack.length) {
    while (level > stack.length)
      stack.push(1);
  } else {
    while (level < stack.length)
      stack.pop();

    stack[stack.length - 1]++;
  }
  
  let title = stack.join(".") + ". " + line.trim();

  document.body.appendChild(document.createElement("div")).innerText = title;
});
Hide result
+8

, 1 . , "" 1.

#use a vector instead, if your language supports it
numbering = {0, 0, 0, 0, 0, 0, 0}

for line in lines:
    level = indentLevel(line) #starting from 0

    numbering[level] = numbering[level] + 1
    numbering[level + 1] = 0 #create it if it doesn't exist
    for n = 0 to level - 1
        print numbering[n], ".",
    print numbering[level], " ", line
+2

Source: https://habr.com/ru/post/1747903/