c++ - 如何缩放二进制数组以保持值

标签 c++ arrays algorithm

我希望将数组缩放到给定的长度。

第一个数组 [A] 仅包含 0 和 1 值,并且具有恒定大小,例如 8。

另一方面,我有一个可变长度的数组 [B],具体取决于程序的操作。我想按索引比较两个索引。数组 [A] 可以理解为模式,而 B 是随时间拉伸(stretch)的数据。结果是模式和数据之间的差异

A = [0 1 0 1 1 0 0 1]
B = [0 0 1 1 0 0 1 0 0 0 1]

情况: B.size % A.size == 0 很简单,但我不能假设。

我想到的第一个解决方案是找到最小的公倍数并将两个表缩放到它,但我担心这会非常低效。

我正在寻找一种解决方案,可以尽可能准确地将 [A] 缩放到 [B] 的大小。我用 C++ 编写程序,但我将不胜感激所有提示。

最佳答案

似乎有两个不同的问题,一个是拉伸(stretch) vector A 以匹配 vector B 的大小(不是 C++ 意义上的 vector ),然后找到一个比较函数来测试生成的 vector 是否足够相似以至于视为平等。对于第一部分,这是一种计算因子的方法,A 中的索引需要乘以该因子才能投影到 B 中的索引。

#include <iostream>

using namespace std;

int main()
{
    const int NumA = 8;
    const int NumB = 11;

    int a[NumA] = { 0, 1, 0, 1, 1, 0, 0, 1 };
    int b[NumB] = { 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1 };

    int a2b[NumB]; // a stretched to size of b

    // factor to calculate a 'stretched a' index in a2b
    double factor = NumB / (double)NumA;
    int lastIndex = 0;

    for (int i = 0; i < NumA; i++)
    {
        int index0 = (int)(i * factor); // where the next value is stored
        int index1 = (int)((i+1) * factor); // 'stretch' the value up to here
        for (int j = index0; j < index1; j++)
        {
            a2b[j] = a[i];
            lastIndex = j;
        }
    }
    for (++lastIndex; lastIndex < NumB; lastIndex++)
    {
        // fill last value gap, if any, due to float truncation
        a2b[lastIndex] = a[NumA - 1];
    }

    for (int i = 0; i < NumB; i++)
        std::cout << a2b[i] << " ";

    std::cout << endl;
}

输出是

0 1 0 0 1 1 0 0 0 1 1

如您所见,它不是 B 的精确匹配。对于 A = [0, 1] B = [0 ,0 ,0, 1, 1, 1],输出是

0 0 0 1 1 1

这并没有解决问题的第二部分,即确定相等性。为相等性测试选择的逻辑很可能会改变拉伸(stretch) vector 的方法。

关于c++ - 如何缩放二进制数组以保持值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55471379/

相关文章:

ruby-on-rails - Ruby 内置的#permutation 和#repeated_permutation 方法的时间复杂度是多少?

c++ - C++中 `std::sort`比较器的不同类型

arrays - Swift Array[UInt8] 使用按位运算符不起作用?

ios - JS 对象到 Swift 结构

php - 为我的 URL 缩短器添加自定义 URL 支持

algorithm - 在一系列图像中检测公共(public)区域的方法

c++ - 将 glbinding 与 cmake 链接起来

c++ - std::Threads of non-void functions (C++11)

c++ - 在 C++ 中捕获内存访问冲突

java - 如何拆分用户在java中输入时提供的字符串?