Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 将一个范围列表缩放到另一个范围列表的算法_Algorithm_List_Language Agnostic_Numbers - Fatal编程技术网

Algorithm 将一个范围列表缩放到另一个范围列表的算法

Algorithm 将一个范围列表缩放到另一个范围列表的算法,algorithm,list,language-agnostic,numbers,Algorithm,List,Language Agnostic,Numbers,我有一个固定的基本列表,如下所示: [50, 100, 150, 200, 500, 1000] for each i in input { calculate proximity to each number in base list get the closest number remove that number from the base list return the number } 该列表定义范围:0到50,50到100,继续执行直到1000到无

我有一个固定的基本列表,如下所示:

[50, 100, 150, 200, 500, 1000]
for each i in input
{
    calculate proximity to each number in base list
    get the closest number
    remove that number from the base list
    return the number
}
该列表定义范围:0到50,50到100,继续执行直到1000到无穷大

我想写一个函数,用于将任何数字列表转换为与上述内容兼容的列表。我所说的“兼容”是指它只有该列表中的数字,但这些数字尽可能接近原始值。因此,对于
[111255950]
的示例输入,我将得到
[1002001000]
。到目前为止,我有一个简单的代码如下:

[50, 100, 150, 200, 500, 1000]
for each i in input
{
    calculate proximity to each number in base list
    get the closest number
    remove that number from the base list
    return the number
}
这在大多数情况下都可以正常工作,但当输入规模失控时就会崩溃。当我有一个像
[1000,2000,3000]
这样的输入时,第一个数字得到基本列表中的最后一个数字,然后2000和3000分别得到500和200(因为已经取了1000和500)。这将导致一个向后的列表
[1000500200]

我该如何防范这种情况?

方法1 这可以通过使用其中n是max(len(列表),len(输入))在O(n^3)时间内解决

首先建立一个矩阵,给出将每个输入分配给列表中每个数字的成本

matrix[i,j] = abs(input[i]-list[j])
然后使用匈牙利算法找到输入与列表中数字的最小成本匹配

如果列表中的数字多于输入,则添加一些额外的虚拟输入,这些输入与列表中的任何数字匹配的成本为零

方法2 如果第一种方法太慢,那么可以使用动态规划来计算最佳拟合

其思想是计算一个函数a(a,b),该函数给出列表中前a个输入与前b个数字的最佳匹配

A(a,b) = min( A(a-1,b-1)+matrix[a,b], A(a,b-1) )

这将给出一个O(n^2)解,但需要更多的努力才能读回解。

有效地找到最接近的值-很容易。这样做使得每个数字最多只能使用一次,这有点困难[1000500200]有什么问题?差异之和与[2005001000]相同,因此我不认为它是次优的。请定义一个您想要优化的度量,如果我们按降序对输入进行排序并遵循您的流程,该怎么办。比如[300020001000]——很明显,你已经开始从基地的最后一个开始比较,以加快速度。@NiklasB。问题是数字定义了范围,我用倒排列表得到了负范围。好的,所以你想要非降序。您希望最小化什么措施?我认为对于DP,必须对列表进行排序。这种算法是否节省空间?似乎它需要mino(n*m)。@Mani您可以在O(n)中实现它,因为您可能需要两行DP表。运行时是二次的,但不确定这是否值得