Home > Enterprise >  function that returns the sum of the longest arithmetic sequence(without using arrays)
function that returns the sum of the longest arithmetic sequence(without using arrays)

Time:11-25

So I have this problem I'm trying to solve for a couple of days now, and I just feel lost. The function basically needs to get the size(n) of a sequence. The user inputs the size, and then the function will ask him to put the numbers of the sequence one after the other. Once he puts all the numbers, the function needs to return the sum of the longest sequence. For example, n=8, and the user put [1,3,5,7,11,13,15,16]. The result will be 16 because [1,3,5,7] is the longest sequence. If n=8 and the user put [1,3,5,7,11,15,19,20], the result will be 52, because although there are 2 sequences with the length of 4, the sum of [7,11,15,19] is bigger then [1,3,5,7]. The sequence doesn't necessarily needs to be increasing, it can be decreasing too. The function can't be recursive, and arrays can't be used. I hope it's clear enough what the problem is, and if not, please let me know so I'll try to explain better.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main()
{
    int i, size, num, nextNum, diff, prevDiff, currSeqLength = 0, currSum, prevSum = 0;
    printf("Please enter the arithmetic list size: ");
    scanf_s("%d", &size);
    for (i = 1; i <= size; i  )
    {
        printf("Please enter num: ");
        scanf_s("%d", &num);
        while (i == 1)
        {
            prevSum = num;
            nextNum = num;
            currSeqLength  ;
            break;
        }
        while (i == 2)
        {
            currSum = prevSum   num;
            diff = num - nextNum;
            nextNum = num;
            currSeqLength  ;
            break;
        }
        while (i >= 3)
        {
            prevDiff = diff;
            diff = num - nextNum;
            nextNum = num;
            if (prevDiff == diff)
            {
                currSum  = num;
                currSeqLength  ;
                break;
            }
            else
            {
                prevDiff = diff;
                                // diff now should be the latest num - previous one
            }
        }
    }
}

This is basically what I've managed so far. I know some things here aren't working as intended, and I know the code is only half complete, but I've tried so many things and I can't seem to put my finger on what's the problem, and would really love some guidance, I'm really lost.

A few problems I encountered. When I enter a loop in which the difference between the new number and the old one is different than the previous loops(for instance, [4,8,11]), I can't seem to manage to save the old number(in this case 8) to calculate the next difference(which is 3). Not to mention the first 2 while loops are probably not efficient and can be merged together.

P.S I know that the code is not a function, but I wrote it this way so I can keep track on each step, and once the code works as intended I convert it into a function.

CodePudding user response:

I tried out your code, but as noted in the comments, needed to keep track at various stages in the sequence checks which sequence had the longest consistent difference value. With that I added in some additional arrays to perform that function. Following is a prototype of how that might be accomplished.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int len, diff, longest;
    printf("Enter the size of your sequence: ");
    scanf("%d", &len);

    int num[len], seq[len], sum[len];

    for (int i = 0; i < len; i  )
    {
        printf("Enter value #%d: ", i   1);
        scanf("%d", &num[i]);

        seq[i] = 0;                         /* Initialize these arrays as the values are entered */
        sum[i] = 0;
    }

    for (int i = 0; i < len - 1; i  )
    {
        seq[i] = 1;                         /* The sequence length will always start at "1" */
        sum[i] = num[i];
        diff = num[i   1] - num[i];
        for (int j = i; j < len - 1; j  )
        {
            if (diff == num[j   1] - num[j])
            {
                sum[i]  = num[j   1];       /* Accumulate the sum for this sequence */
                seq[i]  = 1;                /* Increment the sequence length for this sequence portion */
            }
            else
            {
                break;
            }
        }
    }

    longest = 0;                            /* Now, determine which point in the lise of numbers has the longest sequence and sum total */

    for (int i = 1; i < len; i  )
    {
        if ((seq[i] > seq[longest]) || ((seq[i] == seq[longest]) && (sum[i] > sum[longest])))
        {
            longest = i;
        }
    }

    printf("The sequence with the longest sequence and largest sum is: [%d ", num[longest]);

    diff = num[longest    1] - num[longest];

    for (int i = longest   1; i < len; i  )
    {
        if ((num[i] - num[i - 1]) == diff)
        {
            printf("%d ", num[i]);
        }
        else
        {
            break;
        }
    }

    printf("]\n");

    return 0;
}

Some points to note.

  • Additional arrays are defined to track sequence length and sequence summary values.
  • A brute force method is utilized reading through the entered value list starting with the first value to determine its longest sequence length and continuing on to the sequence starting with the second value in the list and continuing on through the list.
  • Once all possible starting points are evaluated for length and total, a check is then made for the starting point that has the longest sequence or the longest sequence and largest sum value.

Following is a some sample terminal output utilizing the list values in your initial query.

@Dev:~/C_Programs/Console/Longest/bin/Release$ ./Longest 
Enter the size of your sequence: 8
Enter value #1: 1
Enter value #2: 3
Enter value #3: 5
Enter value #4: 7
Enter value #5: 11
Enter value #6: 13
Enter value #7: 15
Enter value #8: 16
The sequence with the longest sequence and largest sum is: [1 3 5 7 ]
@Dev:~/C_Programs/Console/Longest/bin/Release$ ./Longest 
Enter the size of your sequence: 8
Enter value #1: 1
Enter value #2: 3
Enter value #3: 5
Enter value #4: 7
Enter value #5: 11
Enter value #6: 15
Enter value #7: 19
Enter value #8: 20
The sequence with the longest sequence and largest sum is: [7 11 15 19 ]

No doubt this code snippet could use some polish, but give it a try and see if it meets the spirit of your project.

CodePudding user response:

I know code-only answers are frowned upon, but this is the simplest I can come up with and its logic seems easy to follow:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main()
{
    int i, size;
    int currNum, currDiff;
    int prevNum = 0, prevDiff = 0;
    int currSum = 0, currSeqLen = 0;
    int bestSum = 0, bestSeqLen = 0;

    printf("Please enter the arithmetic list size: ");
    scanf_s("%d", &size);
    for (i = 0; i < size; i  )
    {
        printf("Please enter num: ");
        scanf_s("%d", &currNum);
        if (currSeqLen > 0)
        {
            currDiff = currNum - prevNum;
            if (currSeqLen > 1 && currDiff != prevDiff)
            {
                /* New arithmetic sequence. */
                currSeqLen = 1;
                currSum = prevNum;
            }
            prevDiff = currDiff;
        }
        currSum  = currNum;
        prevNum = currNum;
        currSeqLen  ;
        if (currSeqLen > bestSeqLen ||
            currSeqLen == bestSeqLen && currSum > bestSum)
        {
            /* This is the best sequence so far. */
            bestSeqLen = currSeqLen;
            bestSum = currSum;
        }
    }
    printf("\nbest sequence length=%d, sum=%d\n", bestSeqLen, bestSum);
    return 0;
}

I have omitted error checking for the scanf_s calls. They can be changed to scanf for non-Windows platforms.

  • Related