How to alternate two given vectors in APL

I am trying to solve a problem using APL, for which I have two vectors v1and v2with a relative length of no more +1, depending on the input. This means that ((≢v1)-(≢v2))∊¯1 0 1.

What would be the best way to alternate these vectors in order to create a third vector v3such that v3=v1[0],v2[0],v1[1],v2[1],...?

(If relevant, I am using Dyalog APL version 16.0)

+5
source share
6 answers

This should work in almost all APLs.

(v0,v1)[⍋(⍳⍴v0),⍳⍴v1]

If you want to worry about v0 or v1 being scalars, then

(v0,v1)[⍋(⍳⍴,v0),⍳⍴,v1]
+9
source

, , ,

Interleave←{,⍉↑⍵}

. !

, (s - ):

Interleave←{
    lengths←⌊/≢¨⍵
    main←,⍉↑lengths↑¨⍵
    tail←⊃,/lengths↓¨⍵
    main,tail
}

!

+6

Dyalog dfn:

zip ← {
    mix ← ,⍉↑ ⍺ ⍵
    mask ← ,⍉↑ 1⊣¨¨ ⍺ ⍵
    mask / mix
}

, , , , (mix).

1 s, (mask), , mix.

, .

!

+6

Dyalog APL, ISO APL 1970- :
(v1,v2)[⍋((0.5×(⍴v1)<⍴v2)+⍳⍴v1),((0.5×(⍴v2)<⍴v1)+⍳⍴v2]

, , v1.

+5
source

Here is how I would solve the original question in APL2:

LEN←∊⌊/⍴¨V1 V2 
V3←∊((LEN↑V1),¨LEN↑V2),LEN↓¨V1 V2
+4
source

With vectors of the same length, use the inner product:

 1 2 3,.,40 50 60

┌──────────────┐
│1 40 2 50 3 60│
└──────────────┘

Building on top of this spawns this dfn:

{r←(⍴⍺)⌊⍴⍵⋄(∊(r⍴⍺),.,r⍴⍵),(r↓⍺),r↓⍵}

alternatively, we can laminate (keeping the general logic):

{r←(⍴⍺)⌊⍴⍵⋄(,(r⍴⍺),⍪r⍴⍵),(r↓⍺),r↓⍵}
-1
source

Source: https://habr.com/ru/post/1692044/


All Articles