Visualize nested array

15

3

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.

Matthew Roh

Posted 2017-03-21T07:36:53.780

Reputation: 5 043

Does it have to have this exact visualisation? – penalosa – 2017-03-21T09:14:22.723

@mnbvc Yes, unless I force to do it people start to twist the I/O a lot. Believe me, I tried it. – Matthew Roh – 2017-03-21T09:21:47.920

I feel like retina will win this. – Magic Octopus Urn – 2017-03-21T13:23:17.683

1Are there any restrictions on what characters can appear in the strings? – Martin Ender – 2017-03-21T14:43:43.650

Additional related questions 1, 2

– AdmBorkBork – 2017-03-21T15:38:00.340

Do we have to handle inconsistent separators? If yes, will whitespace characters occur only after the comma? Will there be only 0 or 1 whitespace or can be even more? – manatwork – 2017-03-22T08:38:35.437

Answers

12

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

marinus

Posted 2017-03-21T07:36:53.780

Reputation: 30 224

5Wait, does it take input in that ascii-art form? – Rɪᴋᴇʀ – 2017-03-21T17:35:58.770

4@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')). – marinus – 2017-03-21T18:01:25.263

9Ah, okay. That clears it up. Somewhat dissapointed now though.... – Rɪᴋᴇʀ – 2017-03-21T18:04:24.190

1Try it online! – Adám – 2017-03-22T21:38:20.830

7

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}]&

Martin Ender

Posted 2017-03-21T07:36:53.780

Reputation: 184 808

47

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!

– Stewie Griffin – 2017-03-21T08:56:06.700

20@StewieGriffin Thanks for the warm welcome, I'll keep that in mind! – Martin Ender – 2017-03-21T09:06:40.283

6@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. – Mindwin – 2017-03-21T15:59:50.360

4

@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.

– None – 2017-03-21T16:12:09.187

When I run this, the final <> appears in the printout; but replacing it with , fixed it. – Greg Martin – 2017-03-21T17:16:28.750

@GregMartin I assume that the input is a list of strings, not numbers (as in the challenge). That's a nice byte-saving, though. :) – Martin Ender – 2017-03-21T17:17:14.980

Win-win situation! :) – Greg Martin – 2017-03-21T17:17:59.177

But I´d really love some explanation from You every now and then, so I can get to know Mathematica (and the other cryptic stuff You´re doing) a little. – Titus – 2017-03-21T18:48:49.810

You can save one byte by using Table instead of Array and changing "-"& to "-" – ngenisis – 2017-03-21T19:49:53.660

@ngenisis Oh right, I forgot that Table works without a list parameter now. Will change in a bit. – Martin Ender – 2017-03-21T19:50:36.853

8@Titus I'd love to add one but I don't want to invalidate Stewie's comment. :( – Martin Ender – 2017-03-21T19:50:55.137

6

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

Kevin Cruijssen

Posted 2017-03-21T07:36:53.780

Reputation: 67 575

1You 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. – barteks2x – 2017-03-22T17:29:09.207

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) – barteks2x – 2017-03-22T17:36:06.973

@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.

– Kevin Cruijssen – 2017-03-22T20:56:19.310

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;} – barteks2x – 2017-03-22T21:59:20.133

1I'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. – barteks2x – 2017-03-22T22:40:09.377

6

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

Titus

Posted 2017-03-21T07:36:53.780

Reputation: 13 814

175 bytes: function f($a,$p=""){foreach($a as$e)echo$p,is_array($e)?f($e,"-"):">$e\n";} – Ismael Miguel – 2017-03-21T13:56:09.353

@IsmaelMiguel Nice idea; but it fails if the sub-array has more than one element. – Titus – 2017-03-21T14:35:58.250

@Titus PHP recursion anyway fails to meet the second rule of 2^32-1 levels :P – Christoph – 2017-03-21T14:37:57.023

@Christoph not in PHP, if you don´t cripple your server. But ... possibly in the default config? Have to check! – Titus – 2017-03-21T14:41:44.177

@Titus at least it hits the default memory limit pretty fast. – Christoph – 2017-03-21T14:45:43.943

@Titus I think I found the relevant code here: It allocates a new node on a doubly linked list based stack for each call. So recursion is indeed not the problem for PHP but the memory limit is.

– Christoph – 2017-03-21T15:38:56.710

1if it werent for the required formatting, print_r($array) would be even smaller :) – ivanivan – 2017-03-21T16:40:52.527

@Christoph Check out my iterative solution; I got it down to 93 bytes now.

– Titus – 2017-03-21T17:27:20.797

1Did just a quick test, but seems that is_array($e) could be replaced with $e[-1]!=="". – manatwork – 2017-03-23T08:34:32.053

1@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! – Titus – 2017-03-23T10:56:30.280

1Maybe 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. – manatwork – 2017-03-25T11:18:40.953

@manatwork This should even work in PHP 3; and it still does in 7.1. – Titus – 2017-03-26T13:57:03.813

why print and not echo – ArtisticPhoenix – 2017-12-20T11:22:10.460

@ArtisticPhoenix because echo cannot be used as an expression – Titus – 2017-12-20T14:03:42.153

5

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.

Christoph

Posted 2017-03-21T07:36:53.780

Reputation: 1 489

Let us continue this discussion in chat.

– Titus – 2017-03-22T14:08:40.483

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. – Restioson – 2017-03-22T16:02:21.553

@Restioson int is signed and therefore only works until 2^31-1. – Christoph – 2017-03-22T16:32:31.513

@Christoph the challenge stated that you did not have to go any further than that. – Restioson – 2017-03-24T04:38:52.797

@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). – Christoph – 2017-03-24T06:59:51.973

4

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

orlp

Posted 2017-03-21T07:36:53.780

Reputation: 37 067

import sys, pprint; pprint.pprint(sys.argv) is 43 bytes but I do not know if it breaks code golf rules. – Carel – 2017-03-22T12:47:36.960

This saves one byte: f=lambda o,d=0:o<''and'\n'.join(f(e,d+1)for e in o)or'-'*d+'>'+o – Ben Frankel – 2017-03-22T15:21:39.530

@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) – cole – 2017-03-22T19:41:00.640

@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. – Carel – 2017-03-23T09:55:53.240

4

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.

Neil

Posted 2017-03-21T07:36:53.780

Reputation: 95 035

4

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 ].

Titus

Posted 2017-03-21T07:36:53.780

Reputation: 13 814

Good job again! – Christoph – 2017-03-21T18:35:27.200

3

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.

G B

Posted 2017-03-21T07:36:53.780

Reputation: 11 099

3

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.

Dada

Posted 2017-03-21T07:36:53.780

Reputation: 8 279

3

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 #.

nimi

Posted 2017-03-21T07:36:53.780

Reputation: 34 639

2

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

Steven

Posted 2017-03-21T07:36:53.780

Reputation: 141

2

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

Neil

Posted 2017-03-21T07:36:53.780

Reputation: 95 035

2

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.

Business Cat

Posted 2017-03-21T07:36:53.780

Reputation: 8 927

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. – Martin Ender – 2017-03-21T14:44:44.890

@MartinEnder Good catch, I'll keep an eye on it – Business Cat – 2017-03-21T14:45:42.243

1

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.

fergusq

Posted 2017-03-21T07:36:53.780

Reputation: 4 867

1

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.

Carel

Posted 2017-03-21T07:36:53.780

Reputation: 121

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. – Martin Ender – 2017-03-25T19:40:38.540

0

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")};

Magic Octopus Urn

Posted 2017-03-21T07:36:53.780

Reputation: 19 422

0

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.

Conor O'Brien

Posted 2017-03-21T07:36:53.780

Reputation: 36 228

0

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

manatwork

Posted 2017-03-21T07:36:53.780

Reputation: 17 865

0

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

manatwork

Posted 2017-03-21T07:36:53.780

Reputation: 17 865