Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interleave two given vectors in APL

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)

like image 212
J. Sallé Avatar asked Jan 11 '18 13:01

J. Sallé


2 Answers

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]
like image 76
Lobachevsky Avatar answered Sep 21 '22 22:09

Lobachevsky


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!

like image 41
Adám Avatar answered Sep 19 '22 22:09

Adám