A function to shows the changes in array

closed account (SwqGNwbp)
This is a tricking problem that couldn't figure out how write the program, any body can help me please:



unsigned changes( const unsigned a[], unsigned elements );
changes’s job is to go through the array from beginning to end, counting how many times the data changes its direction between increasing and decreasing. For instance, if the data is increasing, then decreasing, then increasing, then decreasing, changes will return 3. That is,
changes( {3, 5, 10, 9, 50, 100, 1000, 14}, 8 )
returns 3 because
3 5 10 is increasing
10 9 is decreasing
9 50 100 1000 is increasing
1000 14 is decreasing
When the data is the same from one element to the next, that doesn’t count as a change in direction.
changes( {9, 9, 9, 9, 5, 5, 5, 5, 3, 4, 7, 7, 7, 10, 10, 11, 11, 8, 8, 8}, 20 )
returns 2 because the sequence changes direction at the 3 (from decreasing to increasing), and then changes direction at the 11’s (from increasing to decreasing).
I'd just have a boolean or something that indicates whether you are current increasing or decreasing, and change it whenever you hit a new value that is strictly less or strictly greater than the previous and increment a counter for the number of times you've switched.
closed account (SwqGNwbp)
I still cannot write this program!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
unsigned changes(const unsigned a[], unsigned elements)
{
    bool isIncreasing;

    if (a[0] < a[1])
    {
        isIncreasing = true;
    }
    else
    {
        isIncreasing = false;
    }

    unsigned count = 0;

    for (int i = 1; i < elements - 1; i++)
    {
        if (a[i] > a[i + 1] && isIncreasing)
        {
            count++;
            // Missing Code
        }

        if (a[i] < a[i + 1] && !isIncreasing)
        {
            count++;
            // Missing Code
        }
    }

    return count;
}

Can you finish it?
closed account (SwqGNwbp)
Thank you,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
unsigned changes(const unsigned a[], unsigned elements)
{
    bool isIncrease;

    if (a[0] < a[1])
    {
        isIncrease = true;
    }
    else
    {
        isIncrease = false;
    }

    unsigned count = 0;

    for (unsigned i = 1; i < elements - 1; i++)
    {
        if (a[i] > a[i + 1] && isIncrease)
        {
            count++;
            isIncrease = false;
        }

        if (a[i] < a[i + 1] && !isIncrease)
        {
            count++;
            isIncrease = true;
        }
    }

    return count;
}
Topic archived. No new replies allowed.