In Vim, you can repeat a command by preceding it with a number, like
3dd is equivalent to
dd dd dd. Well, this repeating pattern is not restricted to Vim commands. String can be replicated in this way, too.
Given a string, consisting of only digits, alphabetical characters (both upper-case and lower-case) and spaces, with an optional trailing newline, as input, write a program that does the following job:
Each "word" consists of digits and alphabets. If a letter is preceded with a number (there may be more than one digit in a number, or the number is zero), repeat that letter for the given times. For example:
a2bc -> abbc 3xx1yz -> xxxxyz 10ab0c0d0e -> aaaaaaaaaab # No 'cde' because there's a zero 2A2a2A2a -> AAaaAAaa
Words are separated by spaces. There's a maximum of one space between every two adjacent words.
Easy, right? Here's the additional stuff:
If there's a number before the space, repeat the next word for the given times. The number will always be attached to the end of the previous word, or at the start of the string. Example:
a2bc3 2d -> abbc dd dd dd 3 3a -> aaa aaa aaa 33a -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 0 abcd0 efgh3 2x -> xx xx xx a3 0xc b -> a c c c b
If an empty word ought to be repeated, don't output multiple spaces in a row. Squash them:
a3 0x2 b -> a b b # NOT 'a b b'
In other words, your program should never output two spaces together.
Input is never empty, but it's not necessary for the output to be non-empty:
0 3x -> (empty)
Input and output can be taken in any preferred ways. A function taking input from arguments and giving output via return values is acceptable as well.
If it's a program, it must not exit with error (i.e. return value is zero).
Numbers are always decimal, and never starts with a zero, unless the number itself is zero, in which case there's only one zero. I.e. you don't need to consider
000agiven as input.
All numbers are under 2^31 (2,147,483,648). Maximum output length is under 2^32 (4,294,967,296) bytes.
The program may optionally output one trailing space and/or one trailing newline. Those space and newline do not affect the validity of output. Even if the correct output should be empty, an output of a space followed by a newline will qualify.
In short, a valid input matches this regular expression:
([0-9]+ )?([0-9A-Za-z]*[A-Za-z])([0-9]* [0-9A-Za-z]*[A-Za-z])*( ?\n?)
And for a valid output:
([A-Za-z]+)( [A-Za-z]+)*( ?\n?)
Sample test cases:
abcdefg -> abcdefg a3bcd -> abbbcd a3bbbc -> abbbbbc 3a0b -> aaa abc 3d -> abc ddd abc3 d -> abc d d d 5 1x5 1y0 z -> x x x x x y y y y y a999 0x b -> a b 999 0s -> (empty) 0 999s -> (empty) 0 999s4 t -> t t t t a3 0xc b -> a c c c b ABC3 abc -> ABC abc abc abc
This is a code-golf, so the shortest program in bytes in each language wins!