| Bytes | Lang | Time | Link |
|---|---|---|---|
| 087 | Python | 160903T225755Z | Jonathan |
| 074 | Python | 241027T110257Z | movatica |
| 057 | Zsh | 241026T180743Z | roblogic |
| 142 | Java | 240823T184925Z | Denis Lu |
| 092 | Clojure | 240903T150842Z | NikoNyrh |
| 059 | Arturo | 240822T095455Z | chunes |
| 078 | C gcc | 160905T142144Z | G. Sliep |
| 014 | K ngn/k | 240822T215526Z | coltim |
| 009 | Japt R | 240625T115534Z | Shaggy |
| 011 | Pyth | 240822T082536Z | int 21h |
| 006 | Thunno 2 N | 230719T143934Z | The Thon |
| 071 | R | 240625T082825Z | int 21h |
| 056 | Raku Perl 6 rakudo | 230720T073619Z | bb94 |
| 029 | Alice | 230720T023945Z | Julian |
| 5625 | Vyxal j | 230720T011026Z | lyxal |
| 008 | Canvas | 210519T033848Z | hakr14 |
| 007 | Husk | 210519T032818Z | Razetime |
| 076 | Python 2 | 190907T084400Z | Chas Bro |
| 092 | JavaScript Node.js | 181010T005831Z | ggorlen |
| 065 | Forth gforth | 181010T172053Z | reffu |
| 088 | Powershell | 181010T131111Z | mazzy |
| 115 | Gura | 170117T150410Z | Sygmei |
| 069 | Floroid | 160903T225716Z | Yytsi |
| 193 | Racket | 160904T070422Z | rnso |
| 129 | C# | 160905T131147Z | Omer Kah |
| 120 | C++ | 160905T141538Z | VolAnd |
| 100 | C | 160905T104910Z | VolAnd |
| 8892 | Python | 160903T234002Z | Teck-fre |
| 075 | JavaScript ES6 | 160909T185215Z | Rick Hit |
| 162 | brainfuck | 160909T215352Z | gtwebb |
| 063 | Ruby | 160909T202557Z | daniero |
| nan | 160908T143147Z | Magic Oc | |
| 013 | Dyalog APL | 160905T153303Z | Adá |
| nan | GNU sed | 160905T101523Z | seshouma |
| 111 | C | 160906T115031Z | UKMonkey |
| 099 | PowerShell v2+ | 160906T150747Z | AdmBorkB |
| 055 | Brainfuck | 160905T072514Z | Jeff |
| 109 | PHP | 160905T123335Z | Crypto |
| 018 | J | 160906T030311Z | Conor O& |
| 041 | Lambdabot Haskell | 160905T144718Z | BlackCap |
| 136 | Java | 160905T092057Z | Shaun Wi |
| 014 | Pyke | 160904T153905Z | Blue |
| 056 | TIBasic | 160904T180718Z | Timtech |
| 047 | Haskell | 160904T155808Z | nimi |
| 026 | Retina | 160904T021909Z | NinjaBea |
| 179 | Java | 160904T154100Z | Master_e |
| 142 | C | 160904T152558Z | Keyu Gan |
| 028 | Perl | 160904T145608Z | Ton Hosp |
| 009 | 05AB1E | 160904T144217Z | Emigna |
| 081 | Javascript | 160904T012420Z | Hedi |
| 092 | JavaScript ES6 | 160904T132515Z | Neil |
| 082 | Python 2 | 160904T011640Z | atlasolo |
| 032 | Brachylog | 160904T075222Z | Fatalize |
| 076 | Cheddar | 160904T042338Z | Downgoat |
| 109 | REPL/Javascript | 160903T234325Z | Vartan |
| 009 | Pyth | 160903T225701Z | TheBikin |
| 104 | Python 3 | 160903T224650Z | Beta Dec |
| 014 | V | 160903T223454Z | DJMcMayh |
Python, 93 90 87 bytes
lambda*s,d=1,j='\n'.join:j(j([x[:i+1]for i in range(d<0,len(x))][::(d:=-d)])for x in s)
An unnamed function that accepts the two strings and returns a string.
Note: Produces a trialling newline when the second input is length one.
Previous, recursive function
-3 thanks to movatica.
f=lambda a,b,r='',i=2:a and f(a[:-1],b,r+a+'\n')or(b[i-1:]and f(a,b,r+b[:i]+'\n',i+1)or r)
Starts with the empty string r, adds a and a newline and removes the last character from a until a is empty then adds the required portions of b and a newline by keeping a counter, i, which starts at 2 until the length of b is exceeded, then returns r. Has a trailing newline.
Python, 74 bytes
lambda a,b:'\n'.join(g(a)[:0:-1]+g(b))
g=lambda s,t='':[t:=t+u for u in s]
Java, 152 143 142 bytes
Starting with the initial java-solution by Master_ex i improved it by merging the two loops into one:
interface E{static void main(String[]a){for(int i=a[0].length();--i>-a[1].length();)System.out.println(a[i<0?1:0].substring(0,i>0?i+1:1-i));}}
and readable
interface E {
static void main(final String[] a) {
for (int i = a[0].length();--i>-a[1].length();)
System.out.println(a[i < 0 ? 1 : 0].substring(0, i > 0 ? i + 1 : 1 - i));
}
}
I am actually not sure, if the indexing is already optiomal, as some "- 1 / + 1" calculations are involved. Possible this can be writen better
Clojure, 92 bytes
#(let[g(fn[i](take-while some?(iterate butlast(seq i))))](concat(g %)(rest(reverse(g %2)))))
TIO. I suppose a list of chars is a valid string representation. If we replace (seq i) with i the output is a mix of strings and lists. These built-in functions are nice, but gosh their names are long for code-golf purposes.
C (gcc), 102 97 95 93 78 bytes
f(a,b)char*a;{for(;*a;)a[puts(a)-2]=0;for(a=b+1;*a++;)printf("%.*s\n",a-b,b);}
The first loop overwrites the string with 0 bytes starting from the end, using puts() to print the string as well as to get its current length. The second uses printf()'s support for variable field widths. The code also relies heavily on C's lack of type safety.
Thanks to @homersimpson and @ceilingcat for each shaving off 2 bytes, and @jdt for another whopping 15 bytes!
K (ngn/k), 14 bytes
{(|1_,\x),,\y}
,\ygenerate prefixes of second input(|1_,\x)generate prefixes of first input, ignoring the first, and then reverse them(...),...concatenate them (and implicitly return)
Japt -R, 9 bytes
Ëå+ÃvÔoÅc
Ëå+ÃvÔoÅc :Implicit input of string array
Ë :Map
å : Cumulatively reduce by
+ : Concatenation
à :End map
v :Modify first element
Ô : Reverse
o :Modify last element
Å : Remove first element
c :Flatten
:Implicit output joined with new lines
Pyth, 11 bytes
j+_thA._MQH
I think that there is a better way of solving this challenge in Pyth. For now, I am posting this 11 byte solution.
Commented:
._MQ # make prefices for each input item
A # assign two lists to G,H
h # take the first list
t # remove its first prefix
_ # reverse the order
+ H # append the second list
j # join with \n
Thunno 2 N, 6 bytes
ƒr$ƒḣḥ
Thanks to @Shaggy for pointing out a bug in the previous solution.
Explanation
ƒr$ƒḣḥ # Implicit input
ƒ # Prefixes of first input
r # Reverse the list
$ƒ # Prefixes of second input
ḣ # Remove first item
ḥ # Concatenate the two lists
# Implicit output,
# joined on newlines (N flag)
R, 71 bytes
\(a,b,`?`=\(x)substring(x,1,nchar(x):1))cat(c(?a,rev(?b)[-1]),sep="\n")
This works because substring is vectorized, i.e, the 2nd and 3rd arguments are vectors with the output being a vector of the same length as the argument.
An effort has been taken to handle the single-letter string cases since the removal of the only element from a size-one character vector would give character(0) which cat diligently outputs as an empty string. This is fixed by combining two vectors into one: character(0) does not exist as a vector element and disappears.
Raku (Perl 6) (rakudo), 56 bytes
{join "\n",reverse([\~] $^a.comb),([\~] $^b.comb)[1..*]}
Alice, 29 bytes
/OM!w@On;?$!?/
KMd!h.$t..wKh\
/MM!w.Ot;.$K?h!w?.n$@h!dOK Full program untangled
/MM Puts the two arguments as strings on the stack
! Pops the second string and save it on the tape
w .$K While the string still have characters
.O Print the string
t; Remove the last character from the string
First string done, now second one
As the first letter is the same:
? Get the string from the tape
h! Keep the first character on the stack, save the rest on the tape
w?.n$@ K While there are still characters to read on the tape
h! Get the first character, put the rest on the tape
dO Join the stack into a new string and print it
Vyxal j, 45 bitsv2, 5.625 bytes
¦Ṙ?¦ḢJ
Explained
¦Ṙ?¦ḢJ
¦Ṙ # [prefixes of the first string] reversed
?¦Ḣ # [prefixes of the second string] with the first prefix removed
J # Merged into a single list
# Joined on newlines by the j flag
💎
Created with the help of Luminespire.
Canvas, 8 bytes
[]↕k;[]∔
Explanation:
[]↕k;[]+ | Full program (characters replaced for clean formatting)
---------+--------------------------------------------------------
[] | Prefixes of first input
↕ | Reversed
k | Remove the last item
; | Swap (places the second input on top)
[] | Prefixes of second input
+ | Add vertically
Python 2, 76 bytes
lambda s,t:'\n'.join(g(s)[:-1]+g(t)[::-1])
g=lambda s:s and[s]+g(s[:-1])or[]
JavaScript (Node.js), 94 92 bytes
(x,y)=>[x,y].map(z=>[...z].map(e=>z.substr(0,Math.abs(i--)||--i)).join`
`,i=x.length).join``
Forth (gforth), 65 bytes
: f dup 1 do 2dup cr type 1- loop 2drop 1 do dup cr i type loop ;
Takes arguments in order on the stack (will look like reverse order in code)
Explanation
Loops from 1 to string1-length outputting the increasingly smaller string each time. Then loops from 1 to string2-length + 1, outputting the increasingly larger string each time
Code Explanation
: f \ begin word definition
dup 1 do \ duplicate the string length, then loop from 1 to string-length
2dup \ duplicate string address and length
cr type \ output a newline, then print the word to the given length
1- \ subtract 1 from string length
loop \ end the loop
2drop \ drop address and string length of first string
1 do \ loop from 1 to string2-length
dup \ duplicate string address
cr i type \ output a new line then print the first i characters of the string
loop \ end the loop
; \ end the string definition
Powershell, 88 bytes
param($a,$b)@()+($a.Length..1|%{-join$a[0..--$_]})+(2..$b.Length|%{-join$b[0..--$_]})|gu
Ungolfed test script:
$f = {
param($a,$b)
@()+
($a.Length..1|%{-join$a[0..--$_]})+
(1..$b.Length|%{-join$b[0..--$_]})|
gu
}
@(
,('O', 'O', 'O')
,('Test', 'Testing', 'Test Tes Te T Te Tes Test Testi Testin Testing')
,('Hello!', 'Hi.', 'Hello! Hello Hell Hel He H Hi Hi.')
,('z', 'zz', 'z zz')
,('.vimrc', '.minecraft', '.vimrc .vimr .vim .vi .v . .m .mi .min .mine .minec .minecr .minecra .minecraf .minecraft')
) | % {
$a, $b, $e = $_
$r = &$f $a $b
"$r"-eq"$e"
$r
''
}
Test script output:
True
O
True
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing
True
Hello!
Hello
Hell
Hel
He
H
Hi
Hi.
True
z
zz
True
.vimrc
.vimr
.vim
.vi
.v
.
.m
.mi
.min
.mine
.minec
.minecr
.minecra
.minecraf
.minecraft
Expalantion:
The sum of arrays puts by pipes to gu (alias for Get-Unique). The gu eliminates double strings.
Gura, 115 bytes
t(a,b)={c=a.len()-1;for(i in 0..c){print(a[0..(c-i)]);println();}for(i in 1..b.len()-1){print(b[0..i]);println();}}
Just discovered this language on Github, it's pretty good !
Floroid, 69 bytes
a,b=L.J
c=1
NZ(a)!=1:z(a);a=a[:-1]
z(a)
NZ(a)!=Z(b):c+=1;a=b[:c];z(a)
It's a start. Takes the input from STDIN.
Testcases
Input: Test Testing
Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing
Input: O O
Output: O
Racket 193 bytes
(define(f l)
(let*((s(list-ref l 0))
(x(string-length s)))
(for((n x))
(println(substring s 0(- x n))))
(set! s(list-ref l 1))
(for((n(range 1(string-length s))))
(println(substring s 0(add1 n))))))
Testing:
(f(list "Test" "Testing"))
"Test"
"Tes"
"Te"
"T"
"Te"
"Tes"
"Test"
"Testi"
"Testin"
"Testing"
(f(list "Hello!" "Hi."))
"Hello!"
"Hello"
"Hell"
"Hel"
"He"
"H"
"Hi"
"Hi."
C#, 129 bytes
void f(string i, string j){for(int k=i.Length,l=0;i!=j;){Console.Write(i+'\n');i=k>1?i.Remove(--k):i+j[k+l++];}Console.Write(i);}
Ungolfed
void f(string i, string j)
{
for (int k = i.Length, l = 0; i != j; )
{
Console.Write(i+'\n');
i = k > 1 ? i.Remove(--k) : i + j[k + l++];
}
Console.Write(i);
}
C++, 120 bytes
[](string s,string t){int n=s.length(),k=t.length(),l=n,j=0;s+=t;while(n?n:++j<k)cout<<s.substr(n?0:l,n?n--:1+j)<<endl;}
Ungolfed test
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
string s1 = "Test";
string s2 = "Testing";
auto f = [](string s, string t)
{
int n = s.length(),
k = t.length(),
l = n,
j = 0;
s += t;
while (n?n:++j<k)
cout << s.substr( n?0:l, n?n--:1+j) << endl;
};
f(s1, s2);
return 0;
}
C, 100 bytes
n;f(char*c,char*s){n=strlen(c);while(n)printf("%.*s\n",n--,c);for(n=1;s[n++];)printf("%.*s\n",n,s);}
Ungolfed test
#include <stdio.h>
#include <string.h>
n;
f(char*c,char*s)
{
n=strlen(c);
while(n)
printf("%.*s\n",n--,c);
for(n=1;s[n++];)
printf("%.*s\n",n,s);
}
int main(void)
{
char * s1 = "Test";
char * s2 = "Testing";
f(s1, s2);
return 0;
}
Python, 88 bytes (function) (92 for lambda) (beginner)
As lambda-function (92 bytes):
f=lambda A,B:"\n".join([(A+" ")[:-i]for i in range(len(A))]+[B[:i+1]for i in range(len(B))])
As function:
def f(a,b,c=""):
while a!=b[0]and a:print(a);a=a[:-1]
while b:c+=b[0];b=b[1:];print(c)
In code: or 72 bytes (from 93 bytes) Shall 'a' be the word to decrease an 'b' be the word to raise up to, this should do:
for i in range(len(a)+(a[0]!=b[0])):print((a+"_")[:-i])
for k in range(len(b)):print(b[:k+1])
or with 72 chars
c=""
while a!=b[0]and a:print(a);a=a[:-1]
while b:c+=b[0];b=b[1:];print(c)
Apart from the lambda-version my solutions will work even with the strings starting differently (overread that part o.0 )
JavaScript (ES6), 75 bytes
f=(x,y,n=1)=>x||n++<y.length?(x||y.slice(0,n))+`
`+f(x.slice(0,-1),y,n):''
Explanation
f=(x,y,n=1)=> //Take 2 inputs, initialize n to 1.
x||n++<y.length? //Increment n only if x doesn't have a value (short circuit).
(x||y.slice(0,n))+` //If x has a value, return it; otherwise, return y sliced.
`+f(x.slice(0,-1),y,n):'' //Recurse, removing last char of x. No problem if x is empty.
Snippet
f=(x,y,n=1)=>x||n++<y.length?(x||y.slice(0,n))+`
`+f(x.slice(0,-1),y,n):''
console.log(f('Test','Testing'));
console.log(f('O','O'));
console.log(f('z','zz'));
console.log(f("0123456789", "02468"));
brainfuck, 162 bytes
,[>,]++++++++++[[-<]>[->]<]++++++++++[<[+<]<[+<]>[+>]>[+>]<---]<[<]<[<]>[[.>]++++++++++.----------<[-]<[[->+<]<]>>]>[<+>-]>[[<+>-]<[<]>[.>]++++++++++.---------->]
Input takes the two strings separated by a linefeed.
First program with brianfuck and first code golf so I'm sure there is plenty of optimization to be done. Had fun doing it though.
Ungolfed
,[>,] Read all input
++++++++++ Flag for 10
[ Subtract 10 from each cell to flag space for blank
[-<]
>
[->]
<
]
++++++++++ Flag for 10
[ Add 10 back to each cell with value in it
<[+<]<[+<]
>[+>]>[+>]<---
]
<[<]<[<]> goto first cell in first string string
[ Print first word subtracting one each time
[.>] Print first string
++++++++++.---------- Print new line
<[-] Kill last letter of first string
< Back one
[ Move each first string character up one
[->+<]
<
]>>
]
>[<+>-]> Move to first letter of scond string back one goto second letter
[
[<+>-] Move next letter back
<[<]> Move to start of string
[.>] Print string
++++++++++.---------- Print new line
>
]
Ruby, 63 bytes
->a,b{f=->s{(1..s.size).map{|l|s[0,l]}};puts f[a].reverse+f[b]}
It's an anonymous function taking two strings:
$ irb
2.3.0 :001 > ->a,b{f=->s{(1..s.size).map{|l|s[0,l]}};puts f[a].reverse+f[b]}["hey","you"]
hey
he
h
y
yo
you
I guess I can beat a few with Groovy here...
Groovy (96 Bytes)
def x(a,b,c){(a..b).each{println c.substring(0,it)}};{y,z->x(y.length(),1,y);x(1,z.length(),z);}
Try it: https://groovyconsole.appspot.com/script/5190971159478272
Explanation:
- X is a closure to print the substring from 0 to x from (a to b) for all integers from a to b.
- The second closure passes the first word from it's length to 1 then does the second word in reverse order.
Dyalog APL, 20 13 bytes
↑(⌽,\⍞),1↓,\⍞
↑ matrify
(⌽,\⍞) reversed (⌽) cumulative concatenation (,\) of character input (⍞)
, prepended to
1↓ one element dropped from
,\⍞ cumulative concatenation of character input
GNU sed, 57 45 + 2(rn flags) = 47 bytes
:;1{/../p};2G;2h;s/.(\n.*)?$//;/./t;g;s/.$//p
Run:
echo -e "Test\nTesting" | sed -rnf morphing_string.sed
The input should be the two strings separated by a newline. The code is run by sed for each line.
The loop : deletes one character from the end of the string iteratively. The output related to the first string is printed directly, except the first character: 1{/../p}. The output for the second string is stored in hold space in reverse order (2G;2h) during deletion and printed at the end.
C, 111 bytes
f(char*a, char*b){int l=strlen(a),k=1;while(*a){printf("%s\n",a);a[--l]=0;}while(b[k]) printf("%.*s\n",++k,b);}
Ungolfed test
#include <stdio.h>
#include <string.h>
f(char*a, char*b) {
int l=strlen(a), k=1;
while(*a) {
printf("%s\n",a);
a[--l]=0;
}
while(b[k])
printf("%.*s\n",++k,b);
}
int main() {
char a[10] = {0};
char b[10] = {0};
for (int i=0; i<5; ++i) {
a[i] = 'a' + i;
b[i] = 'a' + i*2;
}
f(&(a[0]), &(b[0]));
}
PowerShell v2+, 99 bytes
param($a,$b)if($a-eq$b){$a;exit}$a.length..1|%{-join$a[0..--$_]};1..($b.length-1)|%{-join$b[0..$_]}
Straightforward. Loops downward through the first string $a, then loops upward through the second string $b. Has some additional logic at the start where if the strings are equal, so that it only outputs once then exits. The loop indices are off from each other to account for fenceposting.
Brainfuck, 38 55 bytes
>++++++++++>,[>,]<[<]>>[[.>]<[-]<[<]>.>],.[[<]>.>[.>],]
Edit: included newlines in output
PHP, 117 109 bytes
for($i=strlen($a=$argv[1]);$i>1;)echo" ".substr($a,0,$i--);
for(;$j<strlen($b=$argv[2]);)echo" ".$c.=$b[$j++];
for($i=strlen($a=$argv[1]);$i>1;)echo substr($a,0,$i--)." ";
for(;$i<=strlen($b=$argv[2]);)echo substr($b,0,$i++)." ";
PHP, 107 bytes (not working with strings containing 0)
for($a=$argv[1];$a[$i];)echo substr($a.a,0,-++$i)." ";
for($b=$argv[2];$b[$j];)echo substr($b,0,++$j+1)." ";
J, 18 bytes
]\@],~[:}:[:|.]\@[
Ungolfed:
]\@] ,~ [: }: [: |. ]\@[
This is a 7-train:
]\@] ,~ ([: }: ([: |. ]\@[))
The innermost train [: |. ]\@[ consists of a cap [: on the left, so we apply |. (reverse) to the result of ]\@[, which is ]\ (prefixes) over [ (left argument).
Here's what that looks like on the testing, test input:
'testing' ([: |. ]\@]) 'test'
test
tes
te
t
This gives us the first portion, almost. The 5-train outside of that is ([: }: ([: |. ]\@[)), which applies }: (betail, remove last element) to the above expression:
'testing' ([: }: [: |. ]\@]) 'test'
test
tes
te
(This is because we can't have a duplicate midpoint.)
The outer part is finally:
]\@] ,~ ([: }: ([: |. ]\@[))
This is composed of ]\@] (prefixes of left argument) and ,~ (append what's to the left with what's to the right), leaving us with the desired result:
'testing' (]\@] ,~ ([: }: ([: |. ]\@[))) 'test'
testing
testin
testi
test
tes
te
t
te
tes
test
Test cases
k =: ]\@] ,~ ([: }: ([: |. ]\@[))
'o' k 'o'
o
k~ 'o'
o
'test' k 'test'
test
tes
te
t
te
tes
test
k~ 'test'
test
tes
te
t
te
tes
test
'. . .' k '...'
. . .
. .
. .
.
.
..
...
'z' k 'zz'
z
zz
(Lambdabot) Haskell - 41 bytes
f=(.drop 2.inits).(++).reverse.tail.inits
More readable, but two bytes longer:
a!b=(reverse.tail$inits a)++drop 2(inits b)
Output:
f "Hello" "Hi!"
["Hello","Hell","Hel","He","H","Hi","Hi!"]
Java, 168 136 bytes
(s,d)->{int i=s.length()+1;while(i-->1)System.out.println(s.substring(0,i));while(i++<d.length())System.out.println(d.substring(0,i));};
Ungolfed test program
public static void main(String[] args) {
BiConsumer<String, String> biconsumer = (s, d) -> {
int i = s.length() + 1;
while (i-- > 1) {
System.out.println(s.substring(0, i));
}
while (i++ < d.length()) {
System.out.println(d.substring(0, i));
}
};
biconsumer.accept("Test", "Testing123");
}
Pyke, 14 bytes
VDO)KKQlFh<)_X
And 17 bytes just because it's an awesome solution:
mVDO)Fto!I_O(RKsX
TI-Basic, 56 bytes
Prompt Str1,Str2
Str1
While 1<length(Ans
Disp Ans
sub(Ans,1,length(Ans)-1
End
For(I,1,length(Str2
Disp sub(Str2,1,I
End
Example usage
Str1=?Test
Str2=?Testing
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing
Str1=?O
Str2=?O
O
Str1=?z
Str2=?zz
z
zz
Haskell, 54 53 47 bytes
t[]=[]
t x=x:t(init x)
(.reverse.t).(++).init.t
Usage example: ((.reverse.t).(++).init.t) "Hello" "Hi!" -> ["Hello","Hell","Hel","He","H","Hi","Hi!"].
Some pointfree magic. It's the same as f x y = (init(t x))++reverse (t y) where t makes a list of all initial substrings e.g. t "HI!" -> ["H","HI","HI!"].
Retina, 50 41 26 bytes
Thanks to Martin Ender for saving 15(!) bytes.
M&!r`.+
Om`^.¶[^·]+|.+
A1`
Takes input with the two strings separated by a newline:
Test
Testing
Explanation
M&!r`.+
The first line generates the "steps" of both words:
Testing
Testin
Testi
Test
Tes
Te
T
Test
Tes
Te
T
M is for match mode, & considers overlapping matches, and ! prints the matches instead of the number of them. The reason it's reversed is the right-to-left option: the engine starts looking for matches at the end of the string and continues toward the beginning.
Om`^.¶[^·]+|.+
This gets everything in the right order: it sOrts all matches of the subsequent regex: A character on its own line and every character (including newlines) after it, which matches the whole second half as one chunk, or otherwise a line of characters, which matches each individual line. These matches are then sorted by code point, so the T followed by the newline goes first, followed by the lines, ascending by length.
A1`
Now we just have that first character line on top so we use Antigrep mode to discard the first match of the default regex .+.
Old version
M&!r`.+
O`\G..+¶
s`(.*)¶.¶(.*)
$2¶$1
¶.$
Explanation
The first line is the same, so see the explanation for that above.
O`\G..+¶
This reverses the lines of the first half (second input word). It actually sOrts the lines, and the regex limits the matches: it must be a line of two or more characters (..+) followed by a newline (¶) that begins where the last one left off (\G). In the above example, the single T in the middle doesn't match, so nothing after it can.
Te
Tes
Test
Testi
Testin
Testing
T
Test
Tes
Te
T
Now we have the right two components, but in the wrong order.
s`(.*)¶.¶(.*)
$2¶$1
¶.¶ matches the lone T in the middle, which we don't need but separates the two parts. The two (.*) capture everything before and after, including newlines thanks to single-line mode. The two captures are substituted in the right order with a newline in between.
Now we're done, unless the input strings are one character long, in which case the input hasn't changed. To get rid of the duplicate, we replace ¶.$ (when the last line of the string a single character) with nothing.
Java, 188 179 bytes
interface E{static void main(String[]a){int i=a[0].length();while(i>1)System.out.println(a[0].substring(0,i--));while(i<=a[1].length())System.out.println(a[1].substring(0,i++));}}
Update
- Removed s variable, saved 9 bytes
Ungolfed:
interface E {
static void main(String[] a) {
int i = a[0].length();
while (i > 1) {
System.out.println(a[0].substring(0, i--));
}
while (i <= a[1].length()) {
System.out.println(a[1].substring(0, i++));
}
}
}
Usage:
$ java E 'test' 'testing'
test
tes
te
t
te
tes
test
testi
testin
testing
C, 142 bytes
#define _(x,y) while(y)printf("%.*s\n",d,x-c);
f(char*a,char*b){int c=1,d=strlen(a)+1;while(*++a==*++b)c++;_(a,--d>=c)d++;_(b,d++<strlen(b-c))}
Provide f(char* str1, char* str2).
Perl, 34 28 bytes
Includes +2 for -0n
Run with the strings on separate lines on STDIN:
perl -M5.010 -0n slow.pl
Test
Testing
^D
slow.pl:
/(^..+|
\K.+?)(?{say$&})^/
Let regex backtracking do the work...
05AB1E, 9 bytes
.pRI.p¦«»
Explanation
.pR # prefixes of first word
I.p # prefixes of second word
¦ # remove first prefix
« # concatenate
» # join with newlines
Javascript, 103 81 bytes
f=(x,y,n=1)=>x?`
`+x+f(x.slice(0,-1),y):n++<y.length?`
`+y.slice(0,n)+f(x,y,n):''
Example: f("Test", "Testing")
Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing
Original answer
f=(x,y,n=1)=>x?(console.log(x),f(x.slice(0,-1),y)):n++<y.length?(console.log(y.slice(0,n)),f(x,y,n)):''
JavaScript (ES6), 92 bytes
(s,t)=>s.replace(/./g,`
$\`$&`).split`
`.slice(2).reverse().join`
`+t.replace(/./g,`
$\`$&`)
The replace statements build up a triangle of strings, which is exactly what's required for the second half of the output, however the first half needs to be reversed and the duplicate single-character line removed. Note: outputs a leading newline if the first string is a single character. If this is undesirable then for an extra byte this version always outputs a trailing newline:
(s,t)=>s.replace(/./g,`
$\`$&\n`).split(/^/m).slice(1).reverse().join``+t.replace(/./g,`
$\`$&\n`)
Python 2, 88 82 bytes
x,y=input(),input()
for i in x:print x;x=x[:-1]
s=y[0]
for i in y[1:]:s+=i;print s
Takes two inputs, each surrounded by quotes.
Thanks @JonathanAllan for saving some bytes and pointing out a bug.
Brachylog, 32 bytes
:1aLtT,Lhbr:Tc~@nw
:2fb
~c[A:B]h
Explanation
Brachylog has no prefix built-in, therefore we will get the prefixes by using concatenate (See predicate 2): a prefix of S is P if P concatenated to Q (whatever it is) results in S.
Main predicate:
:1aL L is all prefixes of both elements of the input (see predicate 1) LtT, T is the second element of L Lhbr Remove the first prefix of the first list of L and reverse it :Tc Concatenate with T ~@n Join with newlines w Write to STDOUTPredicate 1:
:2f Find all prefixes of the input string (see predicate 2) b Remove the first one (empty string)Predicate 2:
~c[A:B] Input is the result of concatenating A to B h Output is A
Cheddar, 76 bytes
(a,b,q=s->(|>s.len).map((_,i)->s.head(i+1)))->(q(a).rev+q(b).slice(1)).vfuse
A bit longer than I'd liked. I'll add an explanation soon
REPL/Javascript, 109 Bytes
Uses false string to whittle down the original string
Abuses substring with larger numbers to grow the second one, stops when its about to print the same word as last time.
(a,b)=>{l=console.log;z='substring';for(c=a.length;d=a[z](0,c--);){l(d)}for(c=2;d!=(n=b[z](0,c++));){l(d=n)}}
Demo:
> ((a,b)=>{l=console.log;z='substring';for(c=a.length;d=a[z](0,c--);){l(d)}for(c=2;d!=(n=b[z](0,c++));){l(d=n)}})("asdf","abcd")
[Log] asdf
[Log] asd
[Log] as
[Log] a
[Log] ab
[Log] abc
[Log] abcd
Pyth, 9 bytes
j+_._Et._
A program that takes the second string, and then the first string, as quoted strings on STDIN and prints the result.
How it works
j+_._Et._ Program. Inputs: Q, E
._E Yield prefixes of E as a list
_ Reverse the above
._ Yield prefixes of Q as a list (implicit input fill)
t All but the first element of above
+ Merge the two lists
j Join on newlines
Implicitly print
Python 3, 104 bytes
Meh.
n='\n';lambda x,y:x+n+n.join(x[:-i]for i in range(1,len(x)-1))+n+n.join(y[:i]for i in range(1,len(y)+1))
Thanks to @DJMcMayhem for golfing 21 bytes off.
V, 14 bytes
òYp$xhòjòÄ$xhh
Explanation:
ò ò "Recursively:
Yp " Yank the current line and paste it
$ " Move to the end of the current line
x " Delete one character
h " Move One character to the right.
" Because of the way loops work in V, this will throw an error if there
" Is only one character on the current line.
Now, the buffer looks like this:
0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0
We just need to do the same thing in reverse for the next line:
j "Move down one line
ò ò "Recursively (The second ò is implicit)
Ä " Duplicate this line up
$ " Move to the end of the current line
x " Delete one character
hh " Move two characters to the right.
" Because of the way loops work in V, this will throw an error if there
" Is only two characters on the current line.
More interesting alternate solution:
òÄ$xhòç^/:m0
ddGp@qd