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 – 8 years ago
13You should post another challenge to compress a string back down to its shortest format – Jo King – 8 years ago
Is it worth stating explicitly that your string
sshould never contain other brackets? For example, attempting to solve[Foo[Bar]3]2by expanding the stringFoo[Bar3 times would result in an invalid stateFoo[BarFoo[BarFoo[Bar]2– BradC – 8 years ago@BradC that all depends on how you choose to implement the task. – MD XF – 8 years ago
Does that mean that there are two valid answers to
[a[b]2c[d]2e]2? You getabbcddeabbcddeby expandingbanddfirst, butababcdbcdedbabcdbcdedeby expandinga[bandd]2efirst. – BradC – 8 years ago@BradC Ah. Clarified that they should be matching brackets. – MD XF – 8 years ago
Simpler example:
[[a]2[b]2]2expands to eitheraabbaabboraababbaababbdepending 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 – 8 years agoSuggested test case:
[']3 => '''– caird coinheringaahing – 8 years ago