我有一个将整数值返回到整数输入的函数。输出值相对稀疏;对于输入值 1....2^16,该函数仅返回大约 2^14 个唯一输出。我想创建一个数据集,让我快速找到产生任何给定输出的输入。
目前,我将数据集存储在列表映射中,每个输出值都用作输入值列表的键。这似乎很慢,并且似乎使用了整个堆栈空间。有没有更有效的方法来创建/存储/访问我的数据集?
补充: 事实证明我的备用数组()函数所花费的时间在输出值(即键)与输入值(存储在列表中的值)的比率上变化很大。这是需要许多列表的函数所花费的时间,每个列表只有几个值:
? sparsearray(2^16,x->x\7);
time = 126 ms.
这是一个只需要几个列表的函数所花费的时间,每个列表都有很多值:
? sparsearray(2^12,x->x%7);
time = 218 ms.
? sparsearray(2^13,x->x%7);
time = 892 ms.
? sparsearray(2^14,x->x%7);
time = 3,609 ms.
如您所见,时间呈指数增长!
这是我的代码:
\\ sparsearray takes two arguments, an integer "n" and a closure "myfun",
\\ and returns a Map() in which each key a number, and each key is associated
\\ with a List() of the input numbers for which the closure produces that output.
\\ E.g.:
\\ ? sparsearray(10,x->x%3)
\\ %1 = Map([0, List([3, 6, 9]); 1, List([1, 4, 7, 10]); 2, List([2, 5, 8])])
sparsearray(n,myfun=(x)->x)=
{
my(m=Map(),output,oldvalue=List());
for(loop=1,n,
output=myfun(loop);
if(!mapisdefined(m,output),
/* then */
oldvalue=List(),
/* else */
oldvalue=mapget(m,output));
listput(oldvalue,loop);
mapput(m,output,oldvalue));
m
}