Everybody loves nested lists! However, sometimes it's hard to make a nested list. You have to decide if you want to nest it deeper, or if you need to nest it shallower. So for your challenge, you must "Autonest" a list. To autonest a list, compare every pair of items in the list.
If the second item is smaller, separate the two elements by inserting closing and opening brackets between them, like this:
} { {2 , 1}
For example,
{2, 1}
becomes{2}, {1}
, and{3, 2, 1}
becomes{3}, {2}, {1}
If the second item is the same, then change nothing. For example,
{1, 1, 1}
stays the same, and{2, 1, 1, 1}
would become{2}, {1, 1, 1}
.If the second item is larger, then nest every following item one level deeper. For example,
{1, 2}
would become{1, {2}}
and{1, 2, 3}
would become{1, {2, {3}}}
The Challenge
You must write a program or function that takes in a list of numbers, and returns the same list after being autonested. Take this input in your languages native list format (or the closest alternative) or as a string. You do not have to use curly braces like I did in my examples. You can use whichever type of brackets are most natural in your language, as long as this is consistent. You can safely assume the list will only contain integers. You can also assume the list will have at least 2 numbers in it. Here is some sample IO:
{1, 3, 2} --> {1, {3}, {2}}
{1, 2, 3, 4, 5, 6} --> {1, {2, {3, {4, {5, {6}}}}}}
{6, 5, 4, 3, 2, 1} --> {6}, {5}, {4}, {3}, {2}, {1}
{7, 3, 3, 2, 6, 4} --> {7}, {3, 3}, {2, {6}, {4}}
{7, 3, 1, -8, 4, 8, 2, -9, 2, 8} --> {7}, {3}, {1}, {-8, {4, {8}, {2}, {-9, {2, {8}}}}}
Standard loopholes apply, and the shortest answer in bytes wins!
[-100, 100]
but I'm not planning on giving gigantic inputs. \$\endgroup\${2, 1}
becomes{2}, {1}
" How is that one level higher? One level higher would be{2}, 1
. What you have is the same level. \$\endgroup\$