32
\$\begingroup\$

In this challenge, your task is to create a program which takes in a nested array and returns a single-dimensional flattened array. For Example [10,20,[30,[40]],50] should output [10,20,30,40,50].


Input

The input will be a nested array (eg. [10,20,[[[10]]]]). It will contain only Integers (both negative and positive), Strings and Arrays. You can take the input as function argument, STDIN or whatever suits your language. You can assume that the input array won't have an empty array.


Output

The output will be a flatted single-dimensional array with the same elements of same type as in the nested array and in the SAME order.


Test Cases

[10,20,30] -> [10,20,30]
[[10]] -> [10]
[["Hi"],[[10]]] -> ["Hi",10]
[[[20],["Hi"],"Hi",20]] -> [20,"Hi","Hi",20]
[[["[]"],"[]"]] -> ["[]","[]"]


Feel free to ask for any clarification by using comments. This is , so the shortest code in bytes wins!

Note: If your language contains a built-in for this, then you must NOT use it.


Edit

Please also include a link to a website where your code can be executed.

\$\endgroup\$
17
  • 7
    \$\begingroup\$ Some languages treat strings as arrays, is [["Hi"],[[10]]] -> ["H","i",10] ok? \$\endgroup\$
    – Adám
    May 18 '16 at 5:30
  • 4
    \$\begingroup\$ @Mego I was surprised too to find out that there was an unflatten question but no flatten question on PPCG. \$\endgroup\$
    – Arjun
    May 18 '16 at 6:13
  • 3
    \$\begingroup\$ What if your language only supports subarrays of the same size? (E.g. Java?) What if the type of each element must be the same? (E.g. Java, C++ etc.?) Also, please add e.g. ["[",[["[",],'[',"['['"]] as a test case. \$\endgroup\$
    – flawr
    May 18 '16 at 11:30
  • 4
    \$\begingroup\$ @flawr That test case only makes sense for languages that support bot ' and " as delimiters. (But I agree that a test case involving [, ], " and \ inside a string would be useful.) \$\endgroup\$ May 18 '16 at 11:40
  • 5
    \$\begingroup\$ The test cases also exclude languages which do not support these kinds of arrays with multiple types, or with another notation for array literals. \$\endgroup\$
    – flawr
    May 18 '16 at 11:42

36 Answers 36

1
2
1
\$\begingroup\$

Brachylog, 6 bytes

ċ↰ᵐc|g

Try it online!

ċ         The input is a list,
    |     and the output is
   c      the concatenation of
 ↰ᵐ       the results of this predicate on the list's elements.
    |     If the input is not a list, then it
     g    wrapped in a list is the output.
\$\endgroup\$
0
\$\begingroup\$

Lua, 123 bytes

function f(a)o,t={},function(s)for _,v in next,s do if type(v)=="table"then t(v)else o[#o+1]=v end end end t(a)return o end

I'm sure this is not the best answer, but I thought I'd post it since nobody has given a Lua solution yet. Suggestions welcome!

Try it online!

\$\endgroup\$
0
\$\begingroup\$

PowerShell, 35 bytes

filter f{if($_.Rank){$_|f}else{$_}}

Try it online!

Rank - Returns the number of dimensions in the array. Rank = 0 if an object is not array.

\$\endgroup\$
0
\$\begingroup\$

C# (Visual C# Interactive Compiler), 72 bytes

T[]f<T>(T[]a)=>a.SelectMany(x=>x is T[]?f(x as T[]):new[]{x}).ToArray();

Try it online!

Recursive function that takes an object[] as input. Yes, there is a type parameter, so you could pass an array of any type... But it only works correctly if all nested arrays are of the same type. That is a requirement that I have added :)

It would be more flexible to get this to work with an input of type IList or Array.

\$\endgroup\$
0
\$\begingroup\$

Nial, 27 bytes

DOWN[simple,pass,pass,link]

Try it online!

strangely interesting in nial since it doesn't have fixpoint.

\$\endgroup\$
0
\$\begingroup\$

05AB1E, 13 bytes

ΔvyD1«Āië`}})

Try it online or verify all test cases

Not the easiest challenge in 05AB1E, since the merge builtin for lists is also used for strings, so reducing by concatenation like most other golfing languages are using isn't possible. Also, flattening one level down with €` will also flatten down strings to a list of characters (and push them in reversed order), otherwise Δí€` would have been a 4 byter:
Try it online or see the incorrect output of all test cases.

Δ          # Loop until the result no longer changes:
           # (which will use the implicit input-list in the first iteration)
 vy        #  Foreach over the items:
   D       #   Duplicate the current item
    1«     #   Append a "1" to each inner-most string/integer
      Ā    #   Truthify each inner-most string
           #   (we use the appended "1" so every string/integer - even "", "00",
           #   0, 000, etc. - becomes truthy)
       i   #   If this is truthy (will be falsey for lists of truthy values):
           #    (use the duplicated item as is)
       ë   #   Else (it's a list instead):
        `  #    Pop the list, and push all its items to the stack
       }   #   Close the if-statement
 }         #  After the foreach-loop:
  )        #  Wrap all values on the stack into a list
           # (after which the resulting flattened list is output implicitly)

With builtins, we could of course have used the single byte flatten builtin ˜:
Try it online or verify all test cases.

Interesting enough, the incorrect result of the 4-byter could have been 1 byte as well with the flattened characters builtin S:
Try it online or see all test cases.

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.