Exercise 10

Added Exercise 10 to Repo
This commit is contained in:
2025-05-13 16:15:48 +02:00
parent 0a9a42efee
commit a20a6508da
6 changed files with 469 additions and 0 deletions

View File

@@ -0,0 +1,69 @@
#+title: Task 2: [Exam 2022.08 (ITET/MATH/PHYS/RW)] max difference
#+author: JirR02
* Task Description
:PROPERTIES:
:CUSTOM_ID: task-description
:END:
Given the iterators to a vector composed of integers between 0 and
2147483647 (included), return the highest absolute difference between
two neighbouring elements. You can assume that the given range always
includes at least two elements.
Note: The vector is propagated with values that are provided at the
beginning of the execution. The input accepts a sequence of numbers
terminated with -1.
** Function
:PROPERTIES:
:CUSTOM_ID: function
:END:
Implement the function largest_difference in functions.h according to
its pre- and postconditions.
*Rules*:
- The functions must satisfy their respective postconditions.
- You are not allowed to change the function signatures.
- You are not allowed to use additional libraries.
*Hints*:
- You do not need to check the pre- and postconditions (no asserts
necessary).
- The program must compile in order for the autograder to work.
- We recommend *strongly* to submit partial solutions as soon they are
successful.
* Solution
:PROPERTIES:
:CUSTOM_ID: solution
:END:
#+begin_src cpp
#pragma once
#include <vector>
using iterator = std::vector<int>::const_iterator;
// PRE: iterator pair [begin,end) specifies a valid range
// within a vector (begin is included, end is not) containing numbers
// in [0, 2147483647]. The range in the vector comprises at least two
// elements.
// POST: returns the largest absolute difference between two neighbouring
// numbers in the vector.
//
// Example:
// * [1, 5, 2, 5, 7, 6] ~~> 4
// * [2, 9, 1] ~~> 8
int largest_difference(iterator begin, iterator end) {
int max_dif = 0;
end = --end;
while (begin != end) {
int val1 = *begin;
int val2 = *++begin;
if (std::abs(val2 - val1) > max_dif)
max_dif = std::abs(val2 - val1);
}
return max_dif;
}
#+end_src