Skip to content
Advertisement

How to support 256 values without null in array-tree pattern generator?

I love this answer to that question, it’s so creative and robust. I translated it to support 256 values without supporting null arrays, and the tree/array shape generation seems to work. However, I am stuck on how the encoding radix-like function works, and how to translate that given that now POSSIBLE_SHAPE_LIST is only 9 elements instead of 16 now. How do I get getPath to appropriate put the path to the value in the tree structure, given the index? Here is the full code:

JavaScript

It should not log (at the end) [21], it should log something like [14, 1] following the pattern laid out here. What am I doing wrong in the translation from the original answer?

Advertisement

Answer

There are two issues to fix:

  1. POSSIBLE_SHAPE_LIST = [1, 2, 4, 8, 16, 32, 64, 128, 256] is only listing the possible values that represent subarrays, but it does not list all possible values for the first element in a shape representation, i.e. the number of atomic values that are not in a nested array. This number does not have to be a power of 2. For instance, the shape for size 28 is [12, 4, 4, 4], which means that there are 3 subarrays of size 4, but also 12 top-level slots. That 12 is not a power of 2, but still needs to be encoded.

  2. code /= 9 will perform a floating point division (unlike in Java). And also, that 9 should not be hardcoded since you have a constant for it.

    So write: code = Math.floor(code / POSSIBLE_SHAPE_LIST.length)

For resolving the first issue, I would propose to split the collect functionality into steps:

  1. Collect all the shapes without encoding them
  2. Collect the distinct numbers that are used in those shapes and assign that to POSSIBLE_SHAPE_LIST
  3. Perform the encoding of those shapes.

So the script could start with this:

JavaScript

NB: I have the habit to terminate statements with semi-colons, as I don’t want to be dependent on the automatic semi-colon insertion algorithm.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement