将元素插入J中的数组
Inserting an element into an array in J
在 J 中的任意位置将元素插入数组的最佳做法是什么?
我想这是一个双重问题:我的主要问题是弄清楚如何为我要创建的动词提供三个参数。我要编写的代码的要点是
insert =. dyad : '(n {. y) , x , (n }. y)'
职位n
。我能想到的最好的解决方案是将两个长度的框数组作为右参数,将位置作为左参数,但这似乎有点笨拙
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)
)
编辑:此外,是否可以采用一组索引来插入项目,以及一组要插入这些索引的项目——即一次插入多个项目?在我看来,这是 J 擅长的事情,但我不确定它会如何完成。
装箱参数是一种常用的技术。您可以使用多重分配来获得更简洁的代码:
f =: 3 : 0
'arg1 arg2' =: y
)
f (i.5);(i.9) NB. arg1 is i.5, arg2 is i.9
要在 L
中的 n
位置插入数组 a
,可以更紧凑地写成:
n ({., a, }.) L
另一种将元素插入数组的方法是用#!.
填充。一些例子:
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
根据您的需要,您还可以使用许多其他技巧,例如移动 n n |.
然后使用 dual &.
:
撤消移动
a,&. (n |. ]) L
(回复太长的评论)
从可读性和性能的角度来看,这两种方法大致相同。我稍微倾向于第一个,因为它更具可读性,但可能会使用第二个。
您可以使用timespacex
动词来检查性能:例如
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
在 J 中的任意位置将元素插入数组的最佳做法是什么?
我想这是一个双重问题:我的主要问题是弄清楚如何为我要创建的动词提供三个参数。我要编写的代码的要点是
insert =. dyad : '(n {. y) , x , (n }. y)'
职位n
。我能想到的最好的解决方案是将两个长度的框数组作为右参数,将位置作为左参数,但这似乎有点笨拙
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)
)
编辑:此外,是否可以采用一组索引来插入项目,以及一组要插入这些索引的项目——即一次插入多个项目?在我看来,这是 J 擅长的事情,但我不确定它会如何完成。
装箱参数是一种常用的技术。您可以使用多重分配来获得更简洁的代码:
f =: 3 : 0
'arg1 arg2' =: y
)
f (i.5);(i.9) NB. arg1 is i.5, arg2 is i.9
要在 L
中的 n
位置插入数组 a
,可以更紧凑地写成:
n ({., a, }.) L
另一种将元素插入数组的方法是用#!.
填充。一些例子:
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
根据您的需要,您还可以使用许多其他技巧,例如移动 n n |.
然后使用 dual &.
:
a,&. (n |. ]) L
(回复太长的评论)
从可读性和性能的角度来看,这两种方法大致相同。我稍微倾向于第一个,因为它更具可读性,但可能会使用第二个。
您可以使用timespacex
动词来检查性能:例如
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