Skip to the task
Layout
Back to classic view

You are looking at: Practice test 1. Your place is still lesson 9, task 1: Strings.

HOMEWORKTask 16 of 17 · step 5: Task 2: the longest rising run

Task 2: the longest rising run

test/1/rising.c: the longest stretch where each number is greater than the one before; of several the same length, the first wins.

Checklist

  • Every task is one commit with a clear message.
  • Zero compiler warnings: the code builds with -Werror.
  • Once per topic you step through your code in the debugger (CLion, gdb).
  • Every function has preconditions and postconditions, and assert tests check them.

The file test/1/rising.c, the program test1_rising.

The task

The program asks how many numbers (1 to 30), reads them into an array and finds the longest rising run: neighbouring numbers where each is greater than the one before.

How many numbers? 8
1. Number: 5
2. Number: 1
3. Number: 3
4. Number: 4
5. Number: 2
6. Number: 6
7. Number: 7
8. Number: 8
Longest rising run: 2 6 7 8
Length: 4, starts at place 5

The runs here are 5, 1 3 4 and 2 6 7 8. The longest is the last one, and it starts at place 5 (places are numbered from 1).

  • Equal doesn't rise. 3 3 is two separate runs of one number each.
  • Several of the same length: the first one wins.
  • All falling: every number is a run of one, so the answer is the first number, length 1.
  • Ask again for an invalid count: There must be 1 to 30 numbers.

How to think about it

First write a function that says how many numbers rise from place from: it starts at 1 and grows while the next number is greater than the one before and the array hasn't ended. Then a second function goes over every start and remembers the best one: the same search as warmest in topic 6, only comparing lengths. Both with contracts and assert.

Mind the bounds: when you check a[i + 1], i + 1 must be less than n.

Tests

The first test is the example above. The second is an invalid count, 31, then 9 7 3 5 1 4: two runs of two numbers (3 5 and 1 4), and the first one wins:

Longest rising run: 3 5
Length: 2, starts at place 3

When ctest --preset debug -L test1 shows 100% tests passed, commit: Solve test 1: longest rising run.