36
2
Your challenge is to expand some brackets in a program's input as shown:
- Find a string s between two matching brackets
[
and]
, with a single digit n after the closing bracket. - Remove the brackets.
- Replace s with itself repeated n times. (If n is 0, simply remove s.)
- Go to step 1 until there are no more matching brackets in the input.
Additional rules and clarifications:
- You will take input and give output via any allowed means.
- A trailing newline in the output is allowed.
- You only need to handle printable ASCII in the input.
- You may assume that all brackets match, i.e. you will never receive the input
[]]]]
or[[[[]
. - You may assume that each closing bracket
]
has a digit after it.
Test cases:
Input -> Output
[Foo[Bar]3]2 -> FooBarBarBarFooBarBarBar
[one]1[two]2[three]3 -> onetwotwothreethreethree
[three[two[one]1]2]3 -> threetwoonetwoonethreetwoonetwoonethreetwoonetwoone
[!@#[$%^[&*(]2]2]2 -> !@#$%^&*(&*($%^&*(&*(!@#$%^&*(&*($%^&*(&*(
[[foo bar baz]1]1 -> foo bar baz
[only once]12 -> only once2
[only twice]23456789 -> only twiceonly twice3456789
[remove me!]0 ->
before [in ]2after -> before in in after
As this is code-golf, the shortest answer in each language wins. Good luck!
Sandboxed post. – MD XF – 2018-01-30T02:24:04.867
13You should post another challenge to compress a string back down to its shortest format – Jo King – 2018-01-30T09:11:31.360
Is it worth stating explicitly that your string
s
should never contain other brackets? For example, attempting to solve[Foo[Bar]3]2
by expanding the stringFoo[Bar
3 times would result in an invalid stateFoo[BarFoo[BarFoo[Bar]2
– BradC – 2018-01-30T20:17:44.513@BradC that all depends on how you choose to implement the task. – MD XF – 2018-01-30T21:59:43.090
Does that mean that there are two valid answers to
[a[b]2c[d]2e]2
? You getabbcddeabbcdde
by expandingb
andd
first, butababcdbcdedbabcdbcdede
by expandinga[b
andd]2e
first. – BradC – 2018-01-30T22:23:00.567@BradC Ah. Clarified that they should be matching brackets. – MD XF – 2018-01-30T22:27:36.383
Simpler example:
[[a]2[b]2]2
expands to eitheraabbaabb
oraababbaababb
depending on how exactly you pair up the brackets. This is an anomaly, though, for most other test cases, you end up with mismatched pairs. Not sure that "matching" entirely conveys the distinction here, but I get the point. Thanks. – BradC – 2018-01-30T22:36:20.497Suggested test case:
[']3 => '''
– caird coinheringaahing – 2018-02-02T16:35:46.387