Inserting an element into an array in J

What's the best practice for inserting an element into an array at an arbitrary position in J?

I think this is kind of a double question: my main problem is how to represent the three arguments in the verb I want to create. The gist of the code I want to write is

insert =. dyad : '(n {. y) , x , (n }. y)'

      

for position n

. The best solution for this I can think of is to use a 2D array of boxes as the correct argument and position as left, but that seems a little awkward

insert =. dyad : 0
       NB. the array to be inserted is the first argument
       i =. > {. y
       NB. the original array is the second argument
       a =. > {: y
       (x {. a) , i , (x }. a)
)

      

EDIT: Also, is it possible to take an array of indices to insert an at element and an array of elements to be inserted at those indices, i.e. insert multiple elements at once? It looks like something good to me, but I'm not sure how it will be done.

+3


source to share


1 answer


Boxing is a commonly used technique. You can use multiple assignment for cleaner code:

f =: 3 : 0
'arg1 arg2' =: y
)
f (i.5);(i.9)    NB. arg1 is i.5, arg2 is i.9

      

To insert an array a

at a position n

in L

, you can write more compactly:

n ({., a, }.) L

      

Another way to insert an element into an array is to fill with #!.

. Some examples:

1 1 1j2 1 (#!.999) 1 2 3 4
  1 2 3 999 999 4

1j1 1 1j1 1 (#!.999) 1 2 3 4
  1 999 2 3 999 4

1 1 0j1 1 (#!.999) 1 2 3 4
  1 2 999 4

      



There are many other tricks you can use depending on your needs, such as offset by n n |.

and then undo the offset with a double &.

:

 a,&. (n |. ]) L

      

(answer to too long comment)

Both in terms of readability and performance, the two methods are roughly the same. I would favor the former slightly as being more readable, but would probably use the latter.

You can use a timespacex

performance test verb : eg.

NB. define the different methods
f1 =: 4 :'x ({., a, }.) y
f2 =: 4 :' a,&. (x |. ]) y'

NB. set some parameters
a =: 1000 $ 9
L =: 1e6 $ 5
n =: 333456

NB. check if the too methods give identical results
(n f1 L) -: (n f2 L)
1

NB. iterate 100 times to get performance averages
100 timespacex'n f1 L'
0.00775349 2.09733e7

100 timespacex'n f2 L'
0.00796431 1.67886e7

      

+3


source







All Articles