从数组中找出最长的算术级数

时间:2017-06-06 05:16:55

标签: c

我有一个数组[5,1,2,4,6,8,12],我想找到序列中最长算术级数的长度并打印出来。最长的算术级数意味着具有共同差异的递增序列,在这种情况下为[2,4,6,8]。

#include <stdio.h>

void main()
{
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }

    printf("\n Numbers in a.p: ");

    for (i = 0; i < num; i++) {
        diff = array[i+1]-array[i];
        if (array[i]-diff == array[i+1]-diff);
        {
            printf("%d, ", array[i]);
        }
    }
    printf("\n Common difference:%d", diff);
}

4 个答案:

答案 0 :(得分:1)

像这样

#include <stdio.h>

int main(void){
#if DEBUG
    int array[] = {5,1,2,4,6,8,12};
    int num = sizeof(array)/sizeof(*array);
    int i, diff;
#else
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }
#endif
    int j, len, longest_len = 2, longest_i = 0;

    for (i = 0; i < num - longest_len; i += len-1) {
        diff = array[i+1]-array[i];
        for(j = i+2; j < num && array[j-1]+diff == array[j]; ++j);
        len = j - i;
        if(longest_len < len){
            longest_len = len;
            longest_i = i;
        }
    }
    printf("\n Numbers in a.p: ");
    diff = array[longest_i+1] - array[longest_i];
    printf("[ ");
    for(i = 0; i < longest_len; ++i){
        printf("%d", array[longest_i + i]);
        if(i == longest_len-1)
            printf(" ]\n");
        else
            printf(", ");
    }
    printf("\n Common difference:%d", diff);
}

答案 1 :(得分:0)

由于这似乎是一项功课或挑战,我只会通过解决由非常奇怪的代码引起的直接问题来提供帮助。
这是在leat正确检测进度的代码。 您可以自己计算长度,存储最长的长度及其索引,然后在解析所有数组后打印该序列。 这里有两个假设,您可能希望避免挑战/家庭作业:

  • 没有输入相同的数字
  • 没有重叠的进展,
    即没有数字是最后一个和下一个进展的第一个

输出中多个序列的表示有点紧张(缺少&#34;)&#34;),但这与查找和排出最长的序列无关。 我没有打扰你的比率输出,不知道应该是什么。

代码:

#include <stdio.h>

// avoid a warning
int main() {
    int array[100], i, num, diff=0, lastdiff=0, first=1;

    printf("Enter the size of an array \n");

    // for good code, this should check the result
    scanf("%d", &num);
    // in case of scaf-failure, cleanup here for good code

    // asking for the number of elements
    // and then relying on that number to be entered
    // is less elegant than checking for and end condition
    // like EOF or negative input

    printf("Enter the elements of the array \n");
    for (i = 0; i < num; i++) {
        // for good code, this should check the result
        scanf("%d", &array[i]);
        // in case of scaf-failure, cleanup here for good code
    }
    printf("\n Numbers in a.p: ");
    for (i = 1; i < num; i++) {

        lastdiff=diff;
        diff = array[i]-array[i-1];
        if (diff==lastdiff)
        {   if(first==1)
            { first=0;
                printf("(%d, %d",array[i-2], array[i-1]);
            }
            printf(", %d", array[i]);
        } else
        {   first=1;
        }
    }
    printf(")\n Ratio:%d", diff);

    // avoid a warning
    return 0;
}

答案 2 :(得分:0)

有很多方法可以应对这一挑战。您可以针对数组中的每个值检查每个差异,也可以反过来使用。鉴于您没有对值进行排序,您可以通过将循环中的值的检查嵌套在所有可能的diffs上来获益。类似于以下工作的东西:

#include <stdio.h>

int main (void) {

    int a[] = {5, 1, 2, 4, 6, 8, 12},
        n = sizeof a / sizeof *a,
        startidx = 0,
        maxlen = 0;

    for (int d = 1; d < n; d++) {       /* loop over diffs */
        int idx = -1,
            len = 1;
        for (int i = 1; i < n; i++)     /* loop over values */
            if (a[i - 1] + d == a[i]) {
                if (idx < 0)            /* if index not set */
                    idx = i - 1;        /* set to 1st index */
                len++;                  /* increment length */
            }
        if (idx >= 0 && len > maxlen) { /* if progression found */
            maxlen = len;               /* save length */
            startidx = idx;             /* save start index */
        }
    }

    printf ("longest progression: '%d' elements.\n", maxlen);
    for (int i = 0; i < maxlen; i++)
        printf (i ? ", %d" : "%d", a[startidx + i]);
    putchar ('\n');

    return 0;
}

示例使用/输出

$ ./bin/maxprogression
longest progression: '4' elements.
2, 4, 6, 8

研究几种接近它的方法,最后选择对你最有意义的方法。您可以稍后进行优化。

就您发布的代码而言,总是验证所有用户输入,至少要检查是否发生了预期的类型转换次数,例如

if (scanf("%d", &num) != 1) {
    fprintf (stderr, "error: input conversion failed for 'num'.\n");
    return 1;
}

您可以在值循环中执行相同的操作。如果您有任何疑问,请告诉我。祝你的编码好运。

答案 3 :(得分:-1)

以下是完整的工作代码。您可以看到它正常工作here

     #include <stdio.h>

 int main()
 {
     int array[100], i, num,diff, resDiff, startIndx, resStartIndx, countCur, countPre;
     printf("Enter the size of an array \n");
     scanf("%d", &num);

     printf("Enter the elements of the array \n");
     for (i = 0; i < num; i++) {
         scanf("%d", &array[i]);
     }

     //Now code changes
     startIndx =0, resStartIndx=0, countPre=0, resDiff=0;
     for (i = 0; i < num; /*No increment required here*/) {
         countCur =0;
         startIndx=i;
         countCur++;

         if(++i < num)
         {
             diff = array[i] - array[startIndx];
             countCur++;
             i++;
             while((i < num) && (diff == (array[i] - array[i-1])))
             {
                 countCur++;
                 i++;
             }

             if(countCur > countPre)
             {
                 resStartIndx = startIndx;
                 countPre = countCur;
                 resDiff = diff;
             }
         }
     }

     countPre += resStartIndx;
     printf("\n Numbers in a.p: ");
     for (i = resStartIndx; i < countPre; i++) {
         printf("%d, ", array[i]);
     }
     printf("\n Common difference:%d", resDiff);
     return 0;
 }