I'm trying to solve a problem using APL, for which I have two vectors v1
and v2
, with relative length of at most +1
, depending on the input. That means that ((≢v1)-(≢v2))∊¯1 0 1
.
What would be the best way to interleave said vectors, so to create a third vector v3
such that v3=v1[0],v2[0],v1[1],v2[1],...
?
(If it's relevant, I'm using Dyalog APL version 16.0)
This should work in just about every APL.
(v0,v1)[⍋(⍳⍴v0),⍳⍴v1]
If you want to worry about either v0 or v1 being scalars, then
(v0,v1)[⍋(⍳⍴,v0),⍳⍴,v1]
If you don't mind getting a prototype fill element when the vectors have unequal length, then
Interleave←{,⍉↑⍵}
will do. Try it online!
Otherwise, you can interleave the matching parts, and then append the missing element(s — it works for length-differences greater than one too):
Interleave←{
lengths←⌊/≢¨⍵
main←,⍉↑lengths↑¨⍵
tail←⊃,/lengths↓¨⍵
main,tail
}
Try it online!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With