Files
cpp-course/modules/02_control_flow/src/loops.cpp
T

42 lines
1.0 KiB
C++
Raw Normal View History

2026-08-11 17:40:36 +03:00
#include "loops.hpp"
2026-08-12 14:47:10 +03:00
#include <algorithm>
#include <ranges>
2026-08-11 17:40:36 +03:00
namespace control_flow {
2026-08-12 14:47:10 +03:00
auto sum_range(const int from, const int to) -> int {
return std::ranges::fold_left(
std::views::iota(from, to + 1), // End-exclusive
0,
[](const int acc, const int x) { return acc + x; }
);
2026-08-11 17:40:36 +03:00
}
2026-08-12 14:47:10 +03:00
auto factorial(const int n) -> long long
pre(n >= 0)
{
if (n == 0 || n == 1) return 1;
return std::ranges::fold_left(
std::views::iota(2, n + 1), // End-exclusive
1LL,
[](const long long acc, const int x) { return acc * x; }
);
2026-08-11 17:40:36 +03:00
}
2026-08-12 14:47:10 +03:00
auto count_occurrences(const std::vector<int>& data, const int target) -> int {
int count = 0;
std::ranges::for_each(data, [target, &count](const int x) {
if (x == target) ++count;
});
return count;
2026-08-11 17:40:36 +03:00
}
2026-08-12 14:47:10 +03:00
auto first_index_of(const std::vector<int>& data, const int target) -> int {
const auto it = std::ranges::find(data, target);
if (it == data.end()) return -1;
return static_cast<int>(std::distance(data.begin(), it));
2026-08-11 17:40:36 +03:00
}
} // namespace control_flow