如何将数组的每n个元素合并为一个元素

时间:2019-09-30 00:22:13

标签: c++ arrays

我有一个元素为0和1的int数组a [intPART + 1]。 我想通过合并数组的每n个元素来将该数组的大小减小为b [rightSIZE + 1],其中

int rightSIZE=    -1              if (intPART+1)/n=0
                  intPART         if n=1
                   0              if (intPART+1)/n=1
                 (intPART+1)/n    if (intPART+1)modn=0
                 (intPART+1)/n-1  if (intPART+1)modn!=0

(我为rightSIZE编写了这些条件,我认为它们应该适用于任何   (intPART + 1)和n)

n can be any number that we want

For example, if we have k = intPART+1 = 8 and if array a=[1,1,1,1,1,0,1,0,0]
     for n=1 we'll have b=[1,1,1,1,1,0,1,0,0]
     for n=2 we'll have b=[1,11,11,01,00]
     for n=3 we'll have b=[111,110,100]
     for n=4 we'll have b=[1,1111,0100]
   for n=200 we'll have b=[111110100] and so on

不幸的是,我并没有真正想到如何完成此任务,并且该任务是我其他任务的一部分,所以我将要添加此解决方案的代码的最后一部分附加到了上面(这是一个问题对我来说)。希望你能帮助我

我正在用C ++编写

#include <iostream>
#include <math.h>       /* log2(dec) and fmod()*/ 
using namespace std;
int main()
{
int dec=500;//let be
//Decimal to binary
int intPART = log2(dec);
cout << "Int part of log2 (" << dec << ") is " << intPART << endl;
int dec1 = dec;
int *a=new int[intPART+1];
for (int i = 0; i<=intPART; i++)
{
    a[i] = dec1 % 2;
    dec1 = dec1 / 2;
}
cout <<dec<<" in a binary system: ";
for (int i = intPART; i >= 0; i--)
{
    cout << a[i];
}
    int n=2^16;//let be
    int rightSIZE;
    if ((intPART+1)/n==0)       rightSIZE=-1;
    if (n==1)                   rightSIZE=intPART;
    if ((intPART+1)/n==1)       rightSIZE=0;
    if (fmod((intPART+1),n)==0) rightSIZE=(intPART+1)/n;
    if (fmod((intPART+1),n)!=0) rightSIZE=(intPART+1)/n-1;
    int *b=new int[rightSIZE+1];
    //what to do next? I don't know:(

}

1 个答案:

答案 0 :(得分:1)

据我了解,您想要这样的东西:

template <std::size_t K, std::size_t N>
std::array<int, (N + K - 1) / K>
combine(const std::array<int, N>& a)
{
    std::array<int, (N + K - 1) / K> res{};

    for (std::size_t i = 0; i != N; ++i) {
        res[(N + K - 1) / K - 1 - i / K] += a[N - 1 - i] * pow(10, i % K);
    }
    return res;
}

Demo

相关问题