Part of Advent of Code Golf 2021 event. See the linked meta post for details.
Related to AoC2018 Day 8.
The license file for an imaginary software system is defined as follows:
- The entire file is a sequence of non-negative integers.
- The entire file defines a tree of nodes.
- Each node in the tree has the following fields in the order:
- Header, a single number indicating the number of child nodes.
- Zero or more child nodes, as specified in the header.
- Zero or more metadata entries (each being a single integer), as specified in the footer.
- Footer, a single number indicating the number of metadata entries.
Hmm, does it really work? It should, because it is your job to validate the given license file!
An example of a valid license file:
2 0 10 11 12 3 1 0 99 1 2 1 1 1 2 3
A----------------------------------
B----------- C-----------
D-----
A has two children (B, C) and three metadata entries. B has no children and three metadata entries. C has one child and one metadata entry, and so on. It is well-formed, so it is valid.
How about this?
2 1 0 0 1 1 0 0 1 1 0
The root node has 2 children and 0 metadata. Then we need to divide 1 0 0 1 1 0 0 1 1
into two nodes. But:
1 0 0
is not a valid node: it has 1 child and 0 metadata, but single 0 is not a valid node.1 0 0 1
is not valid either: it has 1 child and 1 metadata, but again we are left with single 0.1 0 0 1 1
is valid (1 child, 1 metadata,0 0
being the child), but the rest0 0 1 1
is not a valid node.1 0 0 1 1 0
is not a valid node because0 0 1 1
isn't.- The first child cannot be longer than that because the second must have 1 metadata.
Therefore, the second example is not a valid license file.
Given a license file as an array of non-negative integers, determine if it is valid. You can choose to
- output truthy/falsy using your language's convention (swapping is allowed), or
- use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
Standard code-golf rules apply. The shortest code in bytes wins.
Test cases
Truthy:
[0, 0]
[1, 0, 0, 0]
[0, 99, 99, 99, 3]
[2, 0, 10, 11, 12, 3, 1, 0, 99, 1, 2, 1, 1, 1, 2, 3]
Falsy:
[]
[0]
[0, 1]
[1, 1]
[0, 0, 0, 0]
[1, 0, 2, 3, 2]
[3, 0, 1, 0, 0, 1, 0, 0, 1, 2, 3, 2]
[2, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0]
[0, 0, 0, 0]
(cat of two valid license files). \$\endgroup\$[2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0]
->2{0(0 1 0 3);1{0(0)}(0)}(0)
and[3, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0]
->3{0(0);1{0(3 1)}(0);0(0)}(0)
are valid, and then[5, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0]
is ambiguous. So, although we can do validation on it, it still does not work. \$\endgroup\$3 0 ? 1 0 3 1 0 3 1 0 0 ? 1 0
can be0 ? 1 -- 0 3 1 0 3 -- 1 0 0 ? 1
or0 ? 1 0 3 -- 1 0 3 1 0 -- 0 ? 1
\$\endgroup\$