Baig
Baig

Reputation: 5005

Algorithm to find out level

Let's say I have following hierarchy of levels:

How can I find the level number programmatically if I know the stage number, as stage 5 has level 2?

Upvotes: 0

Views: 109

Answers (3)

ifixthat
ifixthat

Reputation: 6295

Well

If you are using python it is very easy.

>>> d = { 'level 1' : [ 'stage 1', 'stage 2', 'stage 3' ], 
...       'level 2' : [ 'stage 4', 'stage 5', 'stage 6' ],
...       'level 3' : [ 'stage 7', 'stage 7', 'stage 9' ],
...     }
>>> for key, val in d.items():
...     if 'stage 5' in val:
...             print key

Thank You

Upvotes: 0

Dan W
Dan W

Reputation: 5782

You could use the following formula to find what level you're on based on a given stage:

level = ceil(stage / 3)

Examples:

ceil(5 / 3) = 2
ceil(9 / 3) = 3
ceil(1 / 3) = 1

Though, this answer only works if each level has exactly 3 stages.

Upvotes: 1

Eric J.
Eric J.

Reputation: 150138

Hopefully you have a pointer up to the parent node.

Keep following that pointer up until there is no parent node. You have found the root node. Count how many times you have to follow a pointer up to the parent to get your depth.

Upvotes: 2

Related Questions