14
1
Input
A nonnegative integer n
, and a nonempty string s
containing only alphanumeric characters and underscores _
.
The first character of s
is not _
.
The underscores of s
are interpreted as blank spaces that can be filled with other characters.
We define an infinite sequence of "infinite strings" as follows.
The string s1 = s s s...
is just s
repeated infinitely many times.
For all k > 1
, the string sk+1
is obtained from sk
by filling its blank spaces with the characters of s1
, so that the first _
of sk
is replaced with s1[0]
, the second with s1[1]
, and so on.
Since the first letter of s
is not _
, every blank space gets filled eventually, and we denote by s∞
the infinite string where every _
has been replaced by its eventual value.
Output
The first n
characters of s∞
as a string.
Example
Consider the inputs n = 30
and s = ab_c_
.
We have
s1 = ab_c_ab_c_ab_c_ab_c_ab_c_ab_c_ab_c_...
Substituting s1
to the blanks of s1
, we have
s2 = abacbab_ccab_caabbc_abcc_abacbab_cc...
We again substitute s1
to the blanks, which results in
s3 = abacbabaccabbcaabbc_abcccabacbab_cc...
One more substitution:
s4 = abacbabaccabbcaabbcaabcccabacbabbcc...
From this we can already deduce the first 30 characters of s∞
, which are
abacbabaccabbcaabbcaabcccabacb
This is the correct output.
Rules
You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. Crashing on incorrect input is acceptable.
Test Cases
0 "ab__" -> ""
1 "ab__" -> "a"
3 "ab__" -> "aba"
20 "ab" -> "abababababababababab"
20 "ab__" -> "abababababababababab"
20 "ab_" -> "abaabbabaabaabbabbab"
30 "ab_c_" -> "abacbabaccabbcaabbcaabcccabacb"
50 "ab_a_cc" -> "abaabccabaaaccabbacccabcaaccabbaaccabaaaccabcaccca"
50 "abc____" -> "abcabcaabcbcaaabcbcbcabcaaababccbcbabccabcabcaaaba"
Can we take input in the opposite order (in languages where the order matters)? – Martin Ender – 2015-02-02T14:41:10.387
@MartinBüttner Sure, I'll allow that. – Zgarb – 2015-02-02T14:41:41.857