15
\$\begingroup\$

You will be given a nested array. Your program has to visualize the array.


But.. How?

For example, let's assume we have a nested array, like [["1","2"],[["1","2"],"3"],"4",[[[["5"]]]],"6"].

This nested array can be visualised as:

->1
->2
-->1
-->2
->3
>4
---->5
>6

Examples

Input 1:
["Atom",["Proton",["Up Quark", "Up Quark", "Down Quark"], "Neutron", ["Up Quark", "Down Quark", "Down Quark"], "Electron"]]
Output 1:
>Atom
->Proton
-->Up Quark
-->Up Quark
-->Down Quark
->Neutron
-->Up Quark
-->Down Quark
-->Down Quark
->Electron

Input 2:
[["1","2"],["3","4"]]
Output 2:
->1
->2
->3
->4

Rules

  • You may use string (or other types which work like a nested array) as input.
  • The maximum level of "layers" is 2^32-1.
\$\endgroup\$
  • \$\begingroup\$ Does it have to have this exact visualisation? \$\endgroup\$ – penalosa Mar 21 '17 at 9:14
  • \$\begingroup\$ @mnbvc Yes, unless I force to do it people start to twist the I/O a lot. Believe me, I tried it. \$\endgroup\$ – Matthew Roh Mar 21 '17 at 9:21
  • \$\begingroup\$ I feel like retina will win this. \$\endgroup\$ – Magic Octopus Urn Mar 21 '17 at 13:23
  • 1
    \$\begingroup\$ Are there any restrictions on what characters can appear in the strings? \$\endgroup\$ – Martin Ender Mar 21 '17 at 14:43
  • \$\begingroup\$ Additional related questions 1, 2 \$\endgroup\$ – AdmBorkBork Mar 21 '17 at 15:38

20 Answers 20

12
\$\begingroup\$

APL, 32 bytes

{1=≡⍺:⎕←⍺,⍨⍵↑1↓⍵/'->'⋄⍺∇¨⍵+1}∘0

Test:

      r
┌────┬─────────────────────────────────────────────────────────────────────────────────────────┐
│Atom│┌──────┬──────────────────────────────┬───────┬────────────────────────────────┬────────┐│
│    ││Proton│┌────────┬────────┬──────────┐│Neutron│┌────────┬──────────┬──────────┐│Electron││
│    ││      ││Up Quark│Up Quark│Down Quark││       ││Up Quark│Down Quark│Down Quark││        ││
│    ││      │└────────┴────────┴──────────┘│       │└────────┴──────────┴──────────┘│        ││
│    │└──────┴──────────────────────────────┴───────┴────────────────────────────────┴────────┘│
└────┴─────────────────────────────────────────────────────────────────────────────────────────┘
      {1=≡⍺:⎕←⍺,⍨⍵↑1↓⍵/'->'⋄⍺∇¨⍵+1}∘0 ⊢ r 
>Atom
->Proton
-->Up Quark
-->Up Quark
-->Down Quark
->Neutron
-->Up Quark
-->Down Quark
-->Down Quark
->Electron

Explanation:

  • {...}∘0: run the following function with 0 bound to :
    • 1=≡⍺:: if the input has depth 1 (i.e. an array that does not contain other arrays):
      • ⍵/'->': create a string containing -s and >s,
      • 1↓: drop the first element,
      • ⍵↑: and take the first elements. This results in a string containing ⍵-1 dashes and one >.
      • ⍺,⍨: append the input to it,
      • ⎕←: and output that to the screen
    • : otherwise,
      • ⍺∇¨⍵+1: add 1 to and apply the function to each nested array
\$\endgroup\$
  • 5
    \$\begingroup\$ Wait, does it take input in that ascii-art form? \$\endgroup\$ – Rɪᴋᴇʀ Mar 21 '17 at 17:35
  • 4
    \$\begingroup\$ @Riker: No, it takes a normal nested array, however this is how Dyalog APL displays a nested array, and (I thought) it makes it obvious what is going on. You could construct it by writing e.g. ('Atom' ('Proton' ('Up Quark' 'Up Quark' 'Down Quark') 'Neutron' ('Up Quark' 'Down Quark' 'Down Quark') 'Electron')). \$\endgroup\$ – marinus Mar 21 '17 at 18:01
  • 9
    \$\begingroup\$ Ah, okay. That clears it up. Somewhat dissapointed now though.... \$\endgroup\$ – Rɪᴋᴇʀ Mar 21 '17 at 18:04
  • 1
    \$\begingroup\$ Try it online! \$\endgroup\$ – Adám Mar 22 '17 at 21:38
7
\$\begingroup\$

Mathematica, 58 57 56 bytes

Thanks to Greg Martin for saving 1 byte.

Thanks to ngenisis for saving 1 byte.

MapIndexed[Print[Table["-",Tr[1^#2]-1]<>">",#]&,#,{-1}]&
\$\endgroup\$
  • 47
    \$\begingroup\$ Welcome to PPCG! You should know that answers that provide little or no explanation get automatically flagged by the system and end up in the Low Quality Review Queue. That might get your answer deleted. Note that if you have several deleted answers you might get a temporary suspension. Just a little heads up! \$\endgroup\$ – Stewie Griffin Mar 21 '17 at 8:56
  • 20
    \$\begingroup\$ @StewieGriffin Thanks for the warm welcome, I'll keep that in mind! \$\endgroup\$ – Martin Ender Mar 21 '17 at 9:06
  • 6
    \$\begingroup\$ @StewieGriffin are you welcoming a sitemod? What is going on here? Is this an inner joke? #confused And good spring for you guys if you are on the north. \$\endgroup\$ – Mindwin Mar 21 '17 at 15:59
  • 4
    \$\begingroup\$ @Mindwin: Stack Exchange has a filter designed to catch answers that are unlikely to be helpful. This sort of post (title + short code sample, no commentary) is highly likely to cause false positives on it, because it looks a lot like a low effort post to a computer (and Stewie Griffin's comment contains a link to a screenshot that indicates that a false positive did in fact happen; it's making fun of the situation). Here's an example of another post that got caught in the filter. \$\endgroup\$ – user62131 Mar 21 '17 at 16:12
  • 8
    \$\begingroup\$ @Titus I'd love to add one but I don't want to invalidate Stewie's comment. :( \$\endgroup\$ – Martin Ender Mar 21 '17 at 19:50
6
\$\begingroup\$

Java 7, 153 141 114 bytes

String r="";<T,S>S c(S s,T o){for(T x:(T[])o)if(x instanceof Object[])c("-"+s,x);else r+=s+">"+x+"\n";return(S)r;}

-39 bytes thanks to @Barteks2x

Explanation:

String r="";                         // Result String outside the method / on class-level
<T,S> S c(S s, T o){                 // Recursive Method with generic String and Object parameters and String return-type
  for(T x : (T[])o)                  //  Loop over the input-array
    if(x instanceof Object[])        //   If the current item is an array itself:
      c("-"+s, x);                   //    Recursive method-call with this array
    else                             //   Else:
      r += s+">"+x+"\n";             //    Append return-String with stripes String-input, ">", current item, and a new-line
                                     //  End of loop (implicit / single-line body)
  return (S)r;                       //  Return the result-String
}                                    // End of method

Test code:

Try it here.

class M{
  String r="";<T,S>S c(S s,T o){for(T x:(T[])o)if(x instanceof Object[])c("-"+s,x);else r+=s+">"+x+"\n";return(S)r;}

  public static void main(String[] a){
    M m = new M();
    System.out.println(m.c("", new Object[]{new Object[]{1,2},new Object[]{new Object[]{1,2},3},4,new Object[]{new Object[]{new Object[]{new Object[]{5}}}},6}));
    m.r = "";
    System.out.println(m.c("", new Object[]{"Atom",new Object[]{"Proton",new Object[]{"Up Quark","Up Quark","Down Quark"}},new Object[]{"Neutron",new Object[]{"Up Quark","Up Quark","Down Quark"}},"Electron"}));
  }
}

Output:

->1
->2
-->1
-->2
->3
>4
---->5
>6

>Atom
->Proton
-->Up Quark
-->Up Quark
-->Down Quark
->Neutron
-->Up Quark
-->Up Quark
-->Down Quark
>Electron
\$\endgroup\$
  • 1
    \$\begingroup\$ You can get it slightly shorter (143 or even 142) by using ternary operator in for(int j=i;j-->0;r+="-"); to also do what the next line does, and using generic argument instead of Object[]: String r="";<T>String c(int i,T[] o){for(T x:o)if(x instanceof Object[])c(i+1,(T[])x);else for(int j=i;j-->=0;r+=j<0?">"+x+"\n":"-");return r;} And even 1 character less if passing 1 instead of 0 as the first argument is ok. \$\endgroup\$ – barteks2x Mar 22 '17 at 17:29
  • \$\begingroup\$ I found a way to make it even shorter by removing the [] from generic argument, it saves additional 2 characters (but can't edit the comment after >5 minutes) \$\endgroup\$ – barteks2x Mar 22 '17 at 17:36
  • \$\begingroup\$ @Barteks2x Thanks! -12 bytes thanks to you. :) Btw, removing the [] from the parameter to save 1 additional byte gives an error. See the error here at >Debug after running. \$\endgroup\$ – Kevin Cruijssen Mar 22 '17 at 20:56
  • \$\begingroup\$ String r="";<T>String c(int i,T a){for(T x:(T[])a)if(x instanceof Object[])c(i+1,x);else for(int j=i;j-->0;r+=j<1?">"+x+"\n":"-");return r;} this works. Also you can do similar generic trick with string to save additiona byte but requires either storing the result in variable before printing it, or an explicit cast (ambigous method call): String r="";<T,S>S c(int i,T a){for(T x:(T[])a)if(x instanceof Object[])c(i+1,x);else for(int j=i;j-->0;r+=j<1?">"+x+"\n":"-");return(S)r;} \$\endgroup\$ – barteks2x Mar 22 '17 at 21:59
  • 1
    \$\begingroup\$ I'm not sure if this is considered allowed, but 114 bytes here, with empty string as argument instead of zero (can be 1 character less if ">" is allowed as argument) String r="";<T,S>S c(S p,T a){for(T x:(T[])a)if(x instanceof Object[])c("-"+p,x);else r+=p+">"+x+"\n";return(S)r;} And the requirement for string cast on return type when calling it is gone. \$\endgroup\$ – barteks2x Mar 22 '17 at 22:40
6
\$\begingroup\$

PHP, 77 74 73 bytes

4 bytes saved thanks @manatwork.

function f($a,$p=">"){foreach($a as$e)"$e"!=$e?f($e,"-$p"):print"$p$e
";}

recursive function, requires PHP 7.1 or newer for the negative string index.
"$e" is Array for arrays; so "$e"!=$e is the same as is_array($e).

  • start with prefix >
  • prepend a - to the prefix for each level
  • print prefix+element+newline for atoms
\$\endgroup\$
  • 1
    \$\begingroup\$ 75 bytes: function f($a,$p=""){foreach($a as$e)echo$p,is_array($e)?f($e,"-"):">$e\n";} \$\endgroup\$ – Ismael Miguel Mar 21 '17 at 13:56
  • 1
    \$\begingroup\$ if it werent for the required formatting, print_r($array) would be even smaller :) \$\endgroup\$ – ivanivan Mar 21 '17 at 16:40
  • 1
    \$\begingroup\$ Did just a quick test, but seems that is_array($e) could be replaced with $e[-1]!=="". \$\endgroup\$ – manatwork Mar 23 '17 at 8:34
  • 1
    \$\begingroup\$ @manatwork That´s PHP<7.1 ... in PHP 7.1, it can be done with $e[-]=="" ... and with the condition reversed $e[-1]>"". Nice find! \$\endgroup\$ – Titus Mar 23 '17 at 10:56
  • 1
    \$\begingroup\$ Maybe I miss some corner cases, but for now looks like $e[-1]>"" can be replaced with "$e"==$e. At least in the ancient PHP 5.6 I use. \$\endgroup\$ – manatwork Mar 25 '17 at 11:18
5
\$\begingroup\$

C99 (GCC), 201 187 140 112 109

f(char*a){for(long d=1,j;j=d+=*++a>90?92-*a:0;)if(*a<35){for(;j||*++a^34;)putchar(j?"->"[!--j]:*a);puts("");}}

expanded form:

f(char*a){
    for(long d=1,j;j=d+=*++a>90?92-*a:0;)
        if(*a<35){
            for(;j||*++a^34;)putchar(j?--j?45:62:*a);
            puts("");
        }
}

This takes a string in the correct format and terminates when finding the last matching ].

It doesn't use recursion and uses long types to actually achieve the second rule: 2^32-1 levels. Most scripting languages have a limited recursion depth or simply crash on stack overflow.

I'm not used to golf in C any help is appreciated :)

Thanks at bolov for his tips ! Specially thanks to Titus who's always up for a good round of golfing (even in C) !

Another two bytes saved by the fact that we can finish once we match the last ] and don't need to match a null char.

It can be tested at Wandbox.

\$\endgroup\$
  • \$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$ – Titus Mar 22 '17 at 14:08
  • \$\begingroup\$ Could you not shorten the second line to for(int d=1 ...? long has 4 characters while int only has 3, and there is no reason that you need to make it go above the 2^32 - 1 for your submission to be valid, saving you a single byte. \$\endgroup\$ – Restioson Mar 22 '17 at 16:02
  • \$\begingroup\$ @Restioson int is signed and therefore only works until 2^31-1. \$\endgroup\$ – Christoph Mar 22 '17 at 16:32
  • \$\begingroup\$ @Christoph the challenge stated that you did not have to go any further than that. \$\endgroup\$ – Restioson Mar 24 '17 at 4:38
  • \$\begingroup\$ @Restioson The challenge states as rule The maximum level of "layers" is 2^32-1.. 2^31-1 is a lot less than 2^32-1. 2^32-1 doesn't fit an int while it fits an unsigned or long (that is on most systems/compilers of course). Therefore int wouldn't make a correct answer (like most answers here fail to be). \$\endgroup\$ – Christoph Mar 24 '17 at 6:59
4
\$\begingroup\$

JavaScript (ES6), 58 51 bytes

f=(a,s='>')=>a.map(e=>e.map?f(e,'-'+s):s+e).join`
`

Edit: Saved 7 bytes when @Arnauld pointed out that I could combine my two approaches.

\$\endgroup\$
4
\$\begingroup\$

PHP, 129 123 112 109 95 93 91 bytes

for(;a&$c=$argn[++$i];)$c<A?$c<"-"?a&$s?$s=!print"$p>$s
":0:$s.=$c:$p=substr("---$p",$c^i);

iterative solution takes string from STDIN:
Run with echo '<input>' | php -nR '<code>' or test it online.

breakdown

for(;a&$c=$argn[++$i];)     // loop $c through input characters
    $c<A                        // not brackets?
        ?$c<"-"                     // comma or quote?
            ?a&$s?$s=!print"$p>$s\n":0  // if $s not empty, print and clear $s
            :$s.=$c                     // digit: append to $s
        :$p=substr("---$p",$c^i)    // prefix plus or minus one "-"
;

Happy that the numbers are in quotes; so I only need one action at a time.

ASCII fiddling

char    ascii   binary/comment
 "       34
 ,       44
 [       91     0101 1011
 ]       93     0101 1101

 A       65     $c<A    true for comma, quote and digits
 -       45     $c<"-"  true for comma and quote

                =0011 1010 -> 50 -> "2"
i^"["   105^91  ^0101 1011
 i      105      0110 1001
i^"]"   105^93  ^0101 1101
                =0011 0100 -> 52 -> "4"

Adding 3 dashes to $p and removing 2 for [, 4 for ] adds one for [ and removes one for ].

\$\endgroup\$
  • \$\begingroup\$ Good job again! \$\endgroup\$ – Christoph Mar 21 '17 at 18:35
4
\$\begingroup\$

Python 2, 65 64 bytes

f=lambda o,d=0:o<''and'\n'.join(f(e,d+1)for e in o)or'-'*d+'>'+o

Right now my answer consistently starts with no dashes, so ["foo", "bar"] is:

>foo
>bar
\$\endgroup\$
  • \$\begingroup\$ import sys, pprint; pprint.pprint(sys.argv) is 43 bytes but I do not know if it breaks code golf rules. \$\endgroup\$ – Carel Mar 22 '17 at 12:47
  • \$\begingroup\$ This saves one byte: f=lambda o,d=0:o<''and'\n'.join(f(e,d+1)for e in o)or'-'*d+'>'+o \$\endgroup\$ – Ben Frankel Mar 22 '17 at 15:21
  • \$\begingroup\$ @Carel can't you do 'import pprint as p' or maybe (not sure if this works) 'import pprint.pprint as p' (goodness I can't seem to find the back tick on my phone keyboard) \$\endgroup\$ – cole Mar 22 '17 at 19:41
  • \$\begingroup\$ @Cole Hmm.. import sys, pprint.pprint as p; p(sys.argv) is still 43 but a good suggestion none the less ;D Trying import sys.argv as v actually lengthens it somewhat ~48 bytes. If one could eliminate sys.argv they'd save alot but the program becomes quite useless then. A recursive approach is quite long, def p(L,d=0): [p(i,d+1) if isinstance(i,list) else print(">"*d + i) for i in L], ~80 bytes. \$\endgroup\$ – Carel Mar 23 '17 at 9:55
3
\$\begingroup\$

Perl 5, 55 bytes

53 bytes of code + -nl flags.

/"/?print"-"x~-$v.">$_":/]/?$v--:$v++for/]|\[|".*?"/g

Try it online!

Not optimal for regex because of some edgy cases that could potentially occur (in particular, if an element of the array contains brackets inside).
A recursive anonymous function would be barely longer though (61 bytes):

sub f{my$v=pop;map{ref?f(@$_,$v+1):"-"x$v.">$_"}@_}sub{f@_,0}

Try it online!

But the way Perl deals with parameters isn't optimal for golfing functions: no optional parameters means I have to do a second function (anonymous) calling the first one, and I have to explicitly get the last parameter with that long my$v=pop.

\$\endgroup\$
3
\$\begingroup\$

Ruby, 49 45 46 bytes

f=->c,p=?>{c.map{|x|x==[*x]?f[x,?-+p]:p+x}*$/}

Example:

puts f[["Atom",["Proton",["Up Quark", "Up Quark", "Down Quark"], "Neutron", ["Up Quark", "Down Quark", "Down Quark"], "Electron"]]]

>Atom
->Proton
-->Up Quark
-->Up Quark
-->Down Quark
->Neutron
-->Up Quark
-->Down Quark
-->Down Quark
->Electron

Explanation:

Recursive function: if x==[*x] then x is an array, and we iterate over it. If not, indent it.

\$\endgroup\$
3
\$\begingroup\$

Haskell, 104 bytes

l@(x:y)#(a:m)|[(h,t)]<-reads$a:m=y++h++l#t|a<'#'=l#m|a<'-'='\n':l#m|a>'['=y#m|q<-'-':l=q#m
l#_=""
(">"#)

Haskell doesn't have nested lists with different depths, so I have to parse the input string on my own. Luckily the library function reads can parse Strings (i.e. "-enclosed char sequence), so I have a little help here.

Usage example:

*Main> putStrLn $ (">"#) "[[\"1\",\"2\"],[\"3\",\"4\"]]" 
->1
->2
->3
->4

Try it online!.

How it works:

The function # goes through the string char by char and keeps the nesting level (the first parameter l) as a string of - with a final >. If the head of the list can be parsed as a String, take l and the String followed by recursive call with the String removed. If the first char is a Space, skip it. If it's a ,, take a newline and go on, if it's ], lower the nesting level and go on and else (only [ left) raise the nesting level and go on. Recursion ends with the empty input string. The main function (">"#) sets the nesting level to ">" and calls #.

\$\endgroup\$
2
\$\begingroup\$

SWI-Prolog, 115 bytes

p(L):-p(L,[>]).
p([],_):-!.
p([H|T],F):-p(H,[-|F]),p(T,F),!.
p(E,[_|F]):-w(F),w([E]),nl.
w([]).
w([H|T]):-write(H),w(T).

Line breaks added for readability only, not included in byte count.

p predicate recursively traverses the arrays, adding a '-' to the prefix F when moving a level deeper. w is used to write the prefix array as well as the actual element to the output.

Example:

?- p(["Atom",["Proton",["Up Quark", "Up Quark", "Down Quark"], "Neutron", ["Up Quark", "Down Quark", "Down Quark"], "Electron"]]).
>Atom
->Proton
-->Up Quark
-->Up Quark
-->Down Quark
->Neutron
-->Up Quark
-->Down Quark
-->Down Quark
->Electron
\$\endgroup\$
2
\$\begingroup\$

Batch, 249 bytes

@echo off
set/ps=
set i=
:t
set t=
:l
set c=%s:~,1%
set s=%s:~1%
if "%c%"=="[" set i=-%i%&goto l
if not "%c%"=="]" if not "%c%"=="," set t=%t%%c%&goto l
if not "%t%"=="" echo %i:~1%^>%t%
if "%c%"=="]" set i=%i:~1%
if not "%s%"=="" goto t

Annoyingly Batch has trouble comparing commas. Sample run:

[Atom,[Proton,[Up Quark,Up Quark,Down Quark],Neutron,[Up Quark,Down Quark,Down Quark],Electron]]
>Atom
->Proton
-->Up Quark
-->Up Quark
-->Down Quark
->Neutron
-->Up Quark
-->Down Quark
-->Down Quark
->Electron
\$\endgroup\$
2
\$\begingroup\$

Retina, 63 54 52 bytes

Saved 2 bytes thanks to Martin Ender

.*?".*?"
$`$&¶
T`[] -~`-]_`.(?=.*".*")
-]

-"
>
T`]"

Try it online!

Explanation

.*?".*?"
$`$&¶

First, the array is broken up by replacing each quoted string with everything that came before it, plus itself, plus a newline. By breaking it up like this, it's possible to find the unmatched opening brackets before each string.

T`[] -~`-]_`.(?=.*".*")

This transliteration will replace [ with -, leave ] unchanged, and delete every other character ( -~ is all printable ASCII). However, it only replaces characters appearing before the final string on each line.

-]

Next all instances of -] are removed. These correspond to matching bracket pairs, and we only want unmatched brackets. After these are removed, each line has a number of -s equal to how many unmatched opening brackets came before it.

-"
>

The last - before a " is replaced with >, to form the arrows.

T`]"

Finally, all remaining ]s and "s are deleted.

\$\endgroup\$
  • \$\begingroup\$ This looks like it assumes that there won't be (escaped) quotes inside the strings. I'm not sure whether that's legitimate but I've asked for clarification. \$\endgroup\$ – Martin Ender Mar 21 '17 at 14:44
  • \$\begingroup\$ @MartinEnder Good catch, I'll keep an eye on it \$\endgroup\$ – Business Cat Mar 21 '17 at 14:45
1
\$\begingroup\$

Röda, 54 bytes

f d=""{{|n|{n|f d=`$d-`}if[n is list]else[`$d>$n
`]}_}

Try it online!

It's a function that reads the input array from the stream. For each item, it either calls itself recursively or prints the item.

\$\endgroup\$
1
\$\begingroup\$

Python 3, 80 Bytes

Python's lambdas support recursion it seems, who knew ?

p=lambda l,d=1:[p(i,d+1)if isinstance(i,list)else print("-"*d+">"+i)for i in l]

This is a counter/compliment to orlp's answer.

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! It seems you've counted a trailing linefeed or something (because I only count 80 bytes) and you don't need the spaces around the =. I also suspect you can drop all the spaces after the three ), but I'm not very familiar with golfing in Python. \$\endgroup\$ – Martin Ender Mar 25 '17 at 19:40
0
\$\begingroup\$

Groovy, 92 bytes

x={a,b->if(a instanceof List){a.each{x(it,b+1)}}else{y(a,b)}};y={a,b->println("-"*b+">$a")};
\$\endgroup\$
0
\$\begingroup\$

Stacked, 27 bytes

[@.1-'-'*\'>'\,,out]deepmap

Try it online!

Takes input from the top of the stack and leaves output on STDOUT. This is simple as doing a depth map, repeating - d times, concatenating with '>' and the element itself.

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

Gema, 63 characters

\A=@set{i;-1}
[=@incr{i}
]=@decr{i}
"*"=@repeat{$i;-}>*\n
,<s>=

Like the other parsing solutions, assumes there will be no escaped double quotes in the strings.

Sample run:

bash-4.3$ gema '\A=@set{i;-1};[=@incr{i};]=@decr{i};"*"=@repeat{$i;-}>*\n;,<s>=' <<< '[["1","2"],[["1","2"],"3"],"4",[[[["5"]]]],"6"]'
->1
->2
-->1
-->2
->3
>4
---->5
>6
\$\endgroup\$
0
\$\begingroup\$

jq, 70 67 characters

(67 64 characters code + 3 characters command line option)

def f(i):if type=="array"then.[]|f("-"+i)else i+. end;.[]|f(">")

Sample run:

bash-4.3$ jq -r 'def f(i):if type=="array"then.[]|f("-"+i)else i+. end;.[]|f(">")' <<< '[["1","2"],[["1","2"],"3"],"4",[[[["5"]]]],"6"]'
->1
->2
-->1
-->2
->3
>4
---->5
>6

On-line test

\$\endgroup\$

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.