|
1 | 1 | /* |
2 | | - * Copyright (c) 2015-2023 Morwenn |
| 2 | + * Copyright (c) 2015-2024 Morwenn |
3 | 3 | * SPDX-License-Identifier: MIT |
4 | 4 | */ |
5 | 5 | #include <algorithm> |
|
13 | 13 | #include <cpp-sort/detail/type_traits.h> |
14 | 14 | #include <cpp-sort/utility/as_function.h> |
15 | 15 | #include <cpp-sort/utility/functional.h> |
16 | | -#include <cpp-sort/utility/functional.h> |
17 | 16 |
|
18 | 17 | // Pseudo-random number generator, used by some distributions |
19 | 18 | thread_local std::mt19937_64 distributions_prng(std::time(nullptr)); |
@@ -422,6 +421,53 @@ namespace dist |
422 | 421 | static constexpr const char* name = "inv"; |
423 | 422 | }; |
424 | 423 |
|
| 424 | + struct runs: |
| 425 | + base_distribution<runs> |
| 426 | + { |
| 427 | + double factor; |
| 428 | + |
| 429 | + constexpr explicit runs(double factor) noexcept: |
| 430 | + factor(factor) |
| 431 | + {} |
| 432 | + |
| 433 | + template<typename OutputIterator, typename Projection=cppsort::utility::identity> |
| 434 | + auto operator()(OutputIterator out, long long int size, Projection projection={}) const |
| 435 | + -> void |
| 436 | + { |
| 437 | + auto&& proj = cppsort::utility::as_function(projection); |
| 438 | + |
| 439 | + if (size == 0) return; |
| 440 | + if (size == 1) { |
| 441 | + *out++ = proj(1); |
| 442 | + return; |
| 443 | + } |
| 444 | + |
| 445 | + // Runs(X) actually computes the number of step-downs in a collection: |
| 446 | + // the number of elements smaller than the previous one |
| 447 | + auto step_downs = static_cast<long long int>(factor * (size - 1)); |
| 448 | + // Average number of elements between two step-downs |
| 449 | + auto delta = step_downs == 0 ? 0.0 : |
| 450 | + static_cast<double>(size - 1) / static_cast<double>(step_downs); |
| 451 | + |
| 452 | + // Generate increasing values, except when encountering a "step-down" |
| 453 | + // boundary, in which case we decrease by one: this way of generating |
| 454 | + // runs gives evenly sized runs no matter the factor |
| 455 | + long long int value = 0; |
| 456 | + long long int next_step = 1; |
| 457 | + for (long long int idx = 0; idx < size;) { |
| 458 | + if (++idx == static_cast<long long int>(next_step * delta)) { |
| 459 | + --value; |
| 460 | + ++next_step; |
| 461 | + } else { |
| 462 | + ++value; |
| 463 | + } |
| 464 | + *out++ = proj(value); |
| 465 | + } |
| 466 | + } |
| 467 | + |
| 468 | + static constexpr const char* name = "runs"; |
| 469 | + }; |
| 470 | + |
425 | 471 | //////////////////////////////////////////////////////////// |
426 | 472 | // Miscellaneous related tools |
427 | 473 |
|
|
0 commit comments