Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ah-comb.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
38# include <gtest/gtest.h>
39
40# include <ah-comb.H>
41# include <ahFunctional.H>
42
43# include <algorithm>
44# include <array>
45# include <set>
46# include <sstream>
47# include <vector>
48
49using namespace Aleph;
50
51namespace
52{
53std::string list_to_string(const DynList<int> & l)
54{
55 std::ostringstream oss;
56 bool first = true;
57 l.for_each([&](int v)
58 {
59 if (not first)
60 oss << ',';
61 first = false;
62 oss << v;
63 });
64 return oss.str();
65}
66
67template <class Seq>
68std::string seq_to_string(const Seq & s)
69{
70 std::ostringstream oss;
71 for (size_t i = 0; i < s.size(); ++i)
72 {
73 if (i > 0)
74 oss << ',';
75 oss << s(i);
76 }
77 return oss.str();
78}
79
80std::string vector_to_string(const std::vector<int> & v)
81{
82 std::ostringstream oss;
83 for (size_t i = 0; i < v.size(); ++i)
84 {
85 if (i > 0)
86 oss << ',';
87 oss << v[i];
88 }
89 return oss.str();
90}
91}
92
93TEST(AhComb, TransposeEmpty)
94{
96 EXPECT_TRUE(transpose(m).is_empty());
97
99 EXPECT_TRUE(m.is_empty());
100}
101
102TEST(AhComb, TransposeRectangular)
103{
104 DynList<int> r1 = {1, 2, 3};
105 DynList<int> r2 = {4, 5, 6};
106 DynList<DynList<int>> m = {r1, r2};
107
108 DynList<int> c1 = {1, 4};
109 DynList<int> c2 = {2, 5};
110 DynList<int> c3 = {3, 6};
111 DynList<DynList<int>> expected = {c1, c2, c3};
112
113 EXPECT_EQ(transpose(m), expected);
114
115 auto m2 = m;
117 EXPECT_EQ(m2, expected);
118
119 // the rows take the nodes of the columns, and count them
120 ASSERT_EQ(m2.size(), 3u);
121 m2.for_each([](const DynList<int> &row) { EXPECT_EQ(row.size(), 2u); });
122}
123
124TEST(AhComb, InPlaceTransposeDynArray)
125{
127
128 DynArray<int> r1;
129 r1.reserve(3);
130 r1(0) = 1;
131 r1(1) = 2;
132 r1(2) = 3;
133
134 DynArray<int> r2;
135 r2.reserve(3);
136 r2(0) = 4;
137 r2(1) = 5;
138 r2(2) = 6;
139
140 m.reserve(2);
141 m(0) = r1;
142 m(1) = r2;
143
145
146 ASSERT_EQ(m.size(), 3u);
147 ASSERT_EQ(m(0).size(), 2u);
148 EXPECT_EQ(m(0)(0), 1);
149 EXPECT_EQ(m(0)(1), 4);
150 EXPECT_EQ(m(1)(0), 2);
151 EXPECT_EQ(m(1)(1), 5);
152 EXPECT_EQ(m(2)(0), 3);
153 EXPECT_EQ(m(2)(1), 6);
154}
155
156TEST(AhComb, TraversePermEnumeratesAll)
157{
158 DynList<int> l1 = {1, 2};
159 DynList<int> l2 = {10, 20};
161
162 std::set<std::string> perms;
163 bool ok = traverse_perm(l, [&](const DynList<int> & p)
164 {
165 perms.insert(list_to_string(p));
166 return true;
167 });
168
169 EXPECT_TRUE(ok);
170 EXPECT_EQ(perms.size(), 4u);
171 EXPECT_TRUE(perms.contains("1,10"));
172 EXPECT_TRUE(perms.contains("2,10"));
173 EXPECT_TRUE(perms.contains("1,20"));
174 EXPECT_TRUE(perms.contains("2,20"));
175}
176
177TEST(AhComb, TraversePermEarlyStop)
178{
179 DynList<int> l1 = {1, 2, 3};
180 DynList<int> l2 = {10, 20};
182
183 size_t seen = 0;
184 bool ok = traverse_perm(l, [&](const DynList<int> &)
185 {
186 ++seen;
187 return seen < 3; // stop on third call
188 });
189
190 EXPECT_FALSE(ok);
191 EXPECT_EQ(seen, 3u);
192}
193
194TEST(AhComb, BuildPerms)
195{
196 DynList<int> l1 = {1, 2};
197 DynList<int> l2 = {10};
199
200 auto perms = build_perms(l);
201 EXPECT_EQ(perms.size(), 2u);
202
203 std::set<std::string> s;
204 perms.for_each([&](const DynList<int> & p) { s.insert(list_to_string(p)); });
205 EXPECT_TRUE(s.contains("1,10"));
206 EXPECT_TRUE(s.contains("2,10"));
207}
208
209TEST(AhComb, BuildCombsDeduplicates)
210{
211 DynList<int> l1 = {1, 2};
212 DynList<int> l2 = {2, 1};
214
215 auto combs = build_combs(l);
216
217 // Possible permutations are (1,2), (1,1), (2,2), (2,1).
218 // After sorting: (1,2), (1,1), (2,2), (1,2) => unique: 3
219 EXPECT_EQ(combs.size(), 3u);
220
221 std::set<std::string> s;
222 combs.for_each([&](const DynList<int> & c) { s.insert(list_to_string(c)); });
223 EXPECT_TRUE(s.contains("1,1"));
224 EXPECT_TRUE(s.contains("1,2"));
225 EXPECT_TRUE(s.contains("2,2"));
226}
227
228TEST(AhComb, FoldPermAccumulates)
229{
230 DynList<int> l1 = {1, 2};
231 DynList<int> l2 = {10, 20};
233
234 // Sum of first elements across permutations:
235 // (1,10), (2,10), (1,20), (2,20) => sum = 6
236 auto sum = fold_perm<size_t, int>(0u, l, [](size_t a, const DynList<int> & p)
237 {
238 return a + p.get_first();
239 });
240
241 EXPECT_EQ(sum, 6u);
242}
243
244TEST(AhComb, TraversePermEmptyInputCallsOnce)
245{
247 size_t calls = 0;
248 bool ok = traverse_perm(l, [&](const DynList<int> & p)
249 {
250 ++calls;
251 EXPECT_TRUE(p.is_empty());
252 return true;
253 });
254 EXPECT_TRUE(ok);
255 EXPECT_EQ(calls, 1u);
256}
257
258TEST(AhComb, BuildPermsEmptyInputReturnsOneEmptyPermutation)
259{
261 auto perms = build_perms(l);
262 ASSERT_EQ(perms.size(), 1u);
263 EXPECT_TRUE(perms.get_first().is_empty());
264}
265
266TEST(AhComb, BuildCombsEmptyInputReturnsOneEmptyCombination)
267{
269 auto combs = build_combs(l);
270 ASSERT_EQ(combs.size(), 1u);
271 EXPECT_TRUE(combs.get_first().is_empty());
272}
273
274TEST(AhComb, TransposeWithZeroColumns)
275{
276 DynList<int> r1;
277 DynList<int> r2;
278 DynList<DynList<int>> m = {r1, r2};
279
280 EXPECT_TRUE(transpose(m).is_empty());
281
282 auto m2 = m;
284 EXPECT_TRUE(m2.is_empty());
285}
286
287#ifndef NDEBUG
288TEST(AhComb, NonRectangularTransposeDies)
289{
290 DynList<int> r1 = {1, 2};
291 DynList<int> r2 = {3};
292 DynList<DynList<int>> m = {r1, r2};
293
294 EXPECT_DEATH((void)transpose(m), "");
295
296 auto m2 = m;
297 EXPECT_DEATH(in_place_transpose(m2), "");
298}
299#endif
300
301// ==== New tests for additional functions ====
302
303TEST(AhComb, PermCountBasic)
304{
305 DynList<int> l1 = {1, 2};
306 DynList<int> l2 = {10, 20, 30};
308
309 EXPECT_EQ(perm_count(l), 6u); // 2 * 3
310}
311
312TEST(AhComb, PermCountEmpty)
313{
315 EXPECT_EQ(perm_count(l), 1u); // One empty permutation
316}
317
318TEST(AhComb, PermCountWithEmptyList)
319{
320 DynList<int> l1 = {1, 2};
321 DynList<int> l2; // empty
323
324 EXPECT_EQ(perm_count(l), 0u); // Any empty list = 0 permutations
325}
326
327TEST(AhComb, PermCountSingleList)
328{
329 DynList<int> l1 = {1, 2, 3, 4, 5};
331
332 EXPECT_EQ(perm_count(l), 5u);
333}
334
335TEST(AhComb, ExistsPermFindsMatch)
336{
337 DynList<int> l1 = {1, 2, 3};
338 DynList<int> l2 = {10, 20};
340
341 bool found = exists_perm(l, [](const DynList<int> & p)
342 {
343 return p.get_first() == 2 && p.get_last() == 20;
344 });
345
346 EXPECT_TRUE(found);
347}
348
349TEST(AhComb, ExistsPermNoMatch)
350{
351 DynList<int> l1 = {1, 2};
352 DynList<int> l2 = {10, 20};
354
355 bool found = exists_perm(l, [](const DynList<int> & p)
356 {
357 return p.get_first() == 100; // Never true
358 });
359
360 EXPECT_FALSE(found);
361}
362
363TEST(AhComb, ExistsPermStopsEarly)
364{
365 DynList<int> l1 = {1, 2, 3};
366 DynList<int> l2 = {10, 20, 30};
368
369 size_t calls = 0;
370 (void)exists_perm(l, [&calls](const DynList<int> & p)
371 {
372 ++calls;
373 return p.get_first() == 1 && p.get_last() == 10; // First one matches
374 });
375
376 EXPECT_EQ(calls, 1u); // Should stop after first match
377}
378
379TEST(AhComb, AllPermAllSatisfy)
380{
381 DynList<int> l1 = {2, 4};
382 DynList<int> l2 = {10, 20};
384
385 // All sums are >= 12
386 bool all = all_perm(l, [](const DynList<int> & p)
387 {
388 int sum = 0;
389 p.for_each([&sum](int v) { sum += v; });
390 return sum >= 12;
391 });
392
393 EXPECT_TRUE(all);
394}
395
396TEST(AhComb, AllPermSomeFail)
397{
398 DynList<int> l1 = {1, 2};
399 DynList<int> l2 = {10, 20};
401
402 bool all = all_perm(l, [](const DynList<int> & p)
403 {
404 return p.get_first() == 2; // Only half satisfy this
405 });
406
407 EXPECT_FALSE(all);
408}
409
410TEST(AhComb, AllPermStopsEarly)
411{
412 DynList<int> l1 = {1, 2, 3, 4};
413 DynList<int> l2 = {10, 20, 30, 40};
415
416 size_t calls = 0;
417 (void)all_perm(l, [&calls](const DynList<int> & p)
418 {
419 ++calls;
420 return p.get_first() != 1; // First permutation fails
421 });
422
423 EXPECT_EQ(calls, 1u); // Should stop after first failure
424}
425
426TEST(AhComb, NonePermNoneSatisfy)
427{
428 DynList<int> l1 = {1, 2};
429 DynList<int> l2 = {10, 20};
431
432 bool none = none_perm(l, [](const DynList<int> & p)
433 {
434 return p.get_first() == 100; // Never true
435 });
436
437 EXPECT_TRUE(none);
438}
439
440TEST(AhComb, NonePermSomeSatisfy)
441{
442 DynList<int> l1 = {1, 2};
443 DynList<int> l2 = {10, 20};
445
446 bool none = none_perm(l, [](const DynList<int> & p)
447 {
448 return p.get_first() == 1; // Some satisfy
449 });
450
451 EXPECT_FALSE(none);
452}
453
454TEST(AhComb, FilterPermBasic)
455{
456 DynList<int> l1 = {1, 2, 3};
457 DynList<int> l2 = {10, 20};
459
460 auto filtered = filter_perm(l, [](const DynList<int> & p)
461 {
462 return p.get_first() >= 2; // Only 2,10 2,20 3,10 3,20
463 });
464
465 EXPECT_EQ(filtered.size(), 4u);
466}
467
468TEST(AhComb, FilterPermEmpty)
469{
470 DynList<int> l1 = {1, 2};
471 DynList<int> l2 = {10, 20};
473
474 auto filtered = filter_perm(l, [](const DynList<int> &)
475 {
476 return false; // None pass
477 });
478
479 EXPECT_TRUE(filtered.is_empty());
480}
481
482TEST(AhComb, FilterPermAll)
483{
484 DynList<int> l1 = {1, 2};
485 DynList<int> l2 = {10};
487
488 auto filtered = filter_perm(l, [](const DynList<int> &)
489 {
490 return true; // All pass
491 });
492
493 EXPECT_EQ(filtered.size(), 2u);
494}
495
496TEST(AhComb, MapPermBasic)
497{
498 DynList<int> l1 = {1, 2};
499 DynList<int> l2 = {10, 20};
501
502 auto sums = map_perm<int>(l, [](const DynList<int> & p)
503 {
504 int sum = 0;
505 p.for_each([&sum](int v) { sum += v; });
506 return sum;
507 });
508
509 EXPECT_EQ(sums.size(), 4u);
510
511 std::set<int> s;
512 sums.for_each([&s](int v) { s.insert(v); });
513 // (1,10)=11, (2,10)=12, (1,20)=21, (2,20)=22
514 EXPECT_TRUE(s.contains(11));
515 EXPECT_TRUE(s.contains(12));
516 EXPECT_TRUE(s.contains(21));
517 EXPECT_TRUE(s.contains(22));
518}
519
520TEST(AhComb, MapPermToString)
521{
522 DynList<int> l1 = {1, 2};
523 DynList<int> l2 = {10};
525
526 auto strs = map_perm<std::string>(l, [](const DynList<int> & p)
527 {
528 return list_to_string(p);
529 });
530
531 EXPECT_EQ(strs.size(), 2u);
532
533 std::set<std::string> s;
534 strs.for_each([&s](const std::string & v) { s.insert(v); });
535 EXPECT_TRUE(s.contains("1,10"));
536 EXPECT_TRUE(s.contains("2,10"));
537}
538
539TEST(AhComb, ForEachPermBasic)
540{
541 DynList<int> l1 = {1, 2};
542 DynList<int> l2 = {10};
544
545 std::set<std::string> perms;
546 for_each_perm(l, [&perms](const DynList<int> & p)
547 {
548 perms.insert(list_to_string(p));
549 });
550
551 EXPECT_EQ(perms.size(), 2u);
552 EXPECT_TRUE(perms.contains("1,10"));
553 EXPECT_TRUE(perms.contains("2,10"));
554}
555
556TEST(AhComb, ForEachPermEmpty)
557{
559
560 size_t calls = 0;
561 for_each_perm(l, [&calls](const DynList<int> & p)
562 {
563 EXPECT_TRUE(p.is_empty());
564 ++calls;
565 });
566
567 EXPECT_EQ(calls, 1u);
568}
569
570TEST(AhComb, TraversePermThreeLists)
571{
572 DynList<int> l1 = {1, 2};
573 DynList<int> l2 = {10, 20};
574 DynList<int> l3 = {100, 200};
576
577 std::set<std::string> perms;
578 traverse_perm(l, [&perms](const DynList<int> & p)
579 {
580 perms.insert(list_to_string(p));
581 return true;
582 });
583
584 EXPECT_EQ(perms.size(), 8u); // 2 * 2 * 2
585}
586
587TEST(AhComb, TraversePermSingleElement)
588{
589 DynList<int> l1 = {42};
591
592 std::set<std::string> perms;
593 traverse_perm(l, [&perms](const DynList<int> & p)
594 {
595 perms.insert(list_to_string(p));
596 return true;
597 });
598
599 EXPECT_EQ(perms.size(), 1u);
600 EXPECT_TRUE(perms.contains("42"));
601}
602
603TEST(AhComb, TransposeSingleRow)
604{
605 DynList<int> r1 = {1, 2, 3};
606 DynList<DynList<int>> m = {r1};
607
608 auto t = transpose(m);
609 EXPECT_EQ(t.size(), 3u); // 3 columns => 3 rows
610
611 size_t idx = 1;
612 for (auto it = t.get_it(); it.has_curr(); it.next_ne(), ++idx)
613 {
614 EXPECT_EQ(it.get_curr().size(), 1u);
615 EXPECT_EQ(it.get_curr().get_first(), static_cast<int>(idx));
616 }
617}
618
619TEST(AhComb, TransposeSingleColumn)
620{
621 DynList<int> r1 = {1};
622 DynList<int> r2 = {2};
623 DynList<int> r3 = {3};
624 DynList<DynList<int>> m = {r1, r2, r3};
625
626 auto t = transpose(m);
627 EXPECT_EQ(t.size(), 1u); // 1 column => 1 row
628 EXPECT_EQ(t.get_first().size(), 3u); // 3 rows => 3 columns
629
630 DynList<int> expected = {1, 2, 3};
631 EXPECT_EQ(t.get_first(), expected);
632}
633
634TEST(AhComb, InPlaceTransposeSingleRow)
635{
636 DynList<int> r1 = {1, 2, 3};
637 DynList<DynList<int>> m = {r1};
638
640 EXPECT_EQ(m.size(), 3u);
641 m.for_each([](const DynList<int> &row) { EXPECT_EQ(row.size(), 1u); });
642
643 auto it = m.get_it();
644 EXPECT_EQ(it.get_curr().get_first(), 1);
645 it.next_ne();
646 EXPECT_EQ(it.get_curr().get_first(), 2);
647 it.next_ne();
648 EXPECT_EQ(it.get_curr().get_first(), 3);
649}
650
651TEST(AhComb, TransposeSquare)
652{
653 DynList<int> r1 = {1, 2};
654 DynList<int> r2 = {3, 4};
655 DynList<DynList<int>> m = {r1, r2};
656
657 auto t = transpose(m);
658
659 DynList<int> c1 = {1, 3};
660 DynList<int> c2 = {2, 4};
661 DynList<DynList<int>> expected = {c1, c2};
662
663 EXPECT_EQ(t, expected);
664}
665
666TEST(AhComb, BuildCombsAllSame)
667{
668 DynList<int> l1 = {1};
669 DynList<int> l2 = {1};
671
672 auto combs = build_combs(l);
673 EXPECT_EQ(combs.size(), 1u);
674
675 DynList<int> expected = {1, 1};
676 EXPECT_EQ(sort(combs.get_first()), expected);
677}
678
679TEST(AhComb, BuildCombsThreeLists)
680{
681 DynList<int> l1 = {1, 2};
682 DynList<int> l2 = {2, 1};
683 DynList<int> l3 = {1, 2};
685
686 auto combs = build_combs(l);
687
688 // Possible combinations after sorting:
689 // (1,1,1), (1,1,2), (1,2,2), (2,2,2)
690 EXPECT_EQ(combs.size(), 4u);
691}
692
693TEST(AhComb, FoldPermMultiplyFirstElements)
694{
695 DynList<int> l1 = {2, 3};
696 DynList<int> l2 = {10};
698
699 // (2,10) and (3,10) => product of first elements = 2 * 3 = 6
700 auto product = fold_perm<int, int>(1, l, [](int acu, const DynList<int> & p)
701 {
702 return acu * p.get_first();
703 });
704
705 EXPECT_EQ(product, 6);
706}
707
708TEST(AhComb, StressTestManyPermutations)
709{
710 // 3^5 = 243 permutations
711 DynList<int> l1 = {1, 2, 3};
712 DynList<int> l2 = {10, 20, 30};
713 DynList<int> l3 = {100, 200, 300};
714 DynList<int> l4 = {1000, 2000, 3000};
715 DynList<int> l5 = {10000, 20000, 30000};
716 DynList<DynList<int>> l = {l1, l2, l3, l4, l5};
717
718 EXPECT_EQ(perm_count(l), 243u);
719
720 size_t count = 0;
721 traverse_perm(l, [&count](const DynList<int> & p)
722 {
723 EXPECT_EQ(p.size(), 5u);
724 ++count;
725 return true;
726 });
727
728 EXPECT_EQ(count, 243u);
729}
730
731TEST(AhComb, NodiscardBuildPerms)
732{
733 DynList<int> l1 = {1, 2};
735
736 // Should not trigger nodiscard warning - use result
737 auto perms = build_perms(l);
738 EXPECT_EQ(perms.size(), 2u);
739}
740
741TEST(AhComb, NodiscardBuildCombs)
742{
743 DynList<int> l1 = {1, 2};
745
746 // Should not trigger nodiscard warning - use result
747 auto combs = build_combs(l);
748 EXPECT_EQ(combs.size(), 2u);
749}
750
751TEST(AhComb, NodiscardTranspose)
752{
753 DynList<int> r1 = {1, 2};
754 DynList<DynList<int>> m = {r1};
755
756 // Should not trigger nodiscard warning - use result
757 auto t = transpose(m);
758 EXPECT_EQ(t.size(), 2u);
759}
760
761TEST(AhComb, NodiscardFoldPerm)
762{
763 DynList<int> l1 = {1, 2};
765
766 // Should not trigger nodiscard warning - use result
767 auto sum = fold_perm<int, int>(0, l, [](int a, const DynList<int> & p)
768 {
769 return a + p.get_first();
770 });
771 EXPECT_EQ(sum, 3);
772}
773
774TEST(AhComb, NodiscardPermCount)
775{
776 DynList<int> l1 = {1, 2};
778
779 // Should not trigger nodiscard warning - use result
780 auto count = perm_count(l);
781 EXPECT_EQ(count, 2u);
782}
783
784TEST(AhComb, NodiscardExistsPerm)
785{
786 DynList<int> l1 = {1, 2};
788
789 // Should not trigger nodiscard warning - use result
790 auto exists = exists_perm(l, [](const DynList<int> &) { return true; });
791 EXPECT_TRUE(exists);
792}
793
794TEST(AhComb, NextPermutationArrayBasicLexicographicOrder)
795{
796 Array<int> a = {1, 2, 3};
797
798 std::vector<std::string> seen;
799 seen.push_back(seq_to_string(a));
800 while (next_permutation(a))
801 seen.push_back(seq_to_string(a));
802
803 const std::vector<std::string> expected = {
804 "1,2,3", "1,3,2", "2,1,3", "2,3,1", "3,1,2", "3,2,1"
805 };
806 EXPECT_EQ(seen, expected);
807
808 // Default behavior resets to first permutation at the end.
809 EXPECT_EQ(seq_to_string(a), "1,2,3");
810}
811
812TEST(AhComb, NextPermutationArrayHandlesDuplicatesWithoutRepeats)
813{
814 Array<int> a = {1, 1, 2};
815
816 std::vector<std::string> seen;
817 seen.push_back(seq_to_string(a));
818 while (next_permutation(a))
819 seen.push_back(seq_to_string(a));
820
821 const std::vector<std::string> expected = {
822 "1,1,2", "1,2,1", "2,1,1"
823 };
824 EXPECT_EQ(seen, expected);
825 EXPECT_EQ(seq_to_string(a), "1,1,2");
826}
827
828TEST(AhComb, NextPermutationArrayMatchesStdWithCustomComparator)
829{
830 Array<int> a = {3, 2, 1};
831 std::vector<int> v = {3, 2, 1};
832
833 while (true)
834 {
835 EXPECT_EQ(seq_to_string(a), vector_to_string(v));
836
837 const bool ha = Aleph::next_permutation(a, Aleph::greater<int>());
838 const bool hv = std::next_permutation(v.begin(), v.end(),
839 std::greater<int>());
840 EXPECT_EQ(ha, hv);
841
842 if (not ha)
843 break;
844 }
845}
846
847TEST(AhComb, NextPermutationResetOnLastCanBeDisabled)
848{
849 Array<int> a = {3, 2, 1};
850 EXPECT_FALSE(next_permutation(a, Aleph::less<int>(), false));
851 EXPECT_EQ(seq_to_string(a), "3,2,1");
852}
853
854TEST(AhComb, NextPermutationDynArray)
855{
857 a.reserve(3);
858 a(0) = 1;
859 a(1) = 2;
860 a(2) = 3;
861
862 size_t count = 1;
863 while (next_permutation(a))
864 ++count;
865
866 EXPECT_EQ(count, 6u);
867 EXPECT_EQ(seq_to_string(a), "1,2,3");
868}
869
870TEST(AhComb, NextCombinationIndicesArrayEnumeratesAll)
871{
872 Array<size_t> idx = {0, 1, 2};
873 const size_t n = 5;
874
875 std::vector<std::array<size_t, 3>> seen;
876 while (true)
877 {
878 seen.push_back({idx(0), idx(1), idx(2)});
879 if (not next_combination_indices(idx, n))
880 break;
881 }
882
883 const std::vector<std::array<size_t, 3>> expected = {
884 {0, 1, 2}, {0, 1, 3}, {0, 1, 4}, {0, 2, 3}, {0, 2, 4},
885 {0, 3, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}
886 };
887 EXPECT_EQ(seen, expected);
888
889 // Default behavior resets to first combination at the end.
890 EXPECT_EQ(idx(0), 0u);
891 EXPECT_EQ(idx(1), 1u);
892 EXPECT_EQ(idx(2), 2u);
893}
894
895TEST(AhComb, NextCombinationIndicesResetOnLastCanBeDisabled)
896{
897 Array<size_t> idx = {2, 3, 4};
898 EXPECT_FALSE(next_combination_indices(idx, 5, false));
899 EXPECT_EQ(idx(0), 2u);
900 EXPECT_EQ(idx(1), 3u);
901 EXPECT_EQ(idx(2), 4u);
902}
903
904TEST(AhComb, NextCombinationIndicesValidation)
905{
906 Array<size_t> not_increasing = {0, 2, 2};
907 EXPECT_THROW(next_combination_indices(not_increasing, 5), std::domain_error);
908
909 Array<size_t> out_of_range = {0, 1, 5};
910 EXPECT_THROW(next_combination_indices(out_of_range, 5), std::out_of_range);
911
912 Array<size_t> k_gt_n = {0, 1, 2};
913 EXPECT_THROW(next_combination_indices(k_gt_n, 2), std::domain_error);
914}
915
916TEST(AhComb, NextCombinationIndicesDynArray)
917{
919 idx.reserve(2);
920 idx(0) = 0;
921 idx(1) = 1;
922
923 size_t count = 1;
924 while (next_combination_indices(idx, 4))
925 ++count;
926
927 EXPECT_EQ(count, 6u); // C(4,2)
928 EXPECT_EQ(idx(0), 0u);
929 EXPECT_EQ(idx(1), 1u);
930}
931
932TEST(AhComb, CombinationCountBasicCases)
933{
934 EXPECT_EQ(combination_count(0, 0), 1u);
935 EXPECT_EQ(combination_count(5, 0), 1u);
936 EXPECT_EQ(combination_count(5, 5), 1u);
937 EXPECT_EQ(combination_count(5, 2), 10u);
938 EXPECT_EQ(combination_count(5, 3), 10u);
939 EXPECT_EQ(combination_count(20, 10), 184756u);
940 EXPECT_EQ(combination_count(6, 8), 0u);
941}
942
943TEST(AhComb, CombinationCountOverflowThrows)
944{
945 if (sizeof(size_t) >= 8)
946 EXPECT_THROW(combination_count(68, 34), std::runtime_error);
947 else
948 EXPECT_THROW(combination_count(35, 17), std::runtime_error);
949}
950
951TEST(AhComb, CombinationMaskEnumerationAndReset)
952{
953 uint64_t mask = first_combination_mask(3); // 0b00111
954 const size_t n = 5;
955
956 std::vector<uint64_t> seen;
957 while (true)
958 {
959 seen.push_back(mask);
960 if (not next_combination_mask(mask, n))
961 break;
962 }
963
964 const std::vector<uint64_t> expected = {
965 0x07, 0x0b, 0x0d, 0x0e, 0x13, 0x15, 0x16, 0x19, 0x1a, 0x1c
966 };
967 EXPECT_EQ(seen, expected);
968 EXPECT_EQ(mask, uint64_t(0x07)); // reset to first
969}
970
971TEST(AhComb, CombinationMaskValidation)
972{
973 uint64_t mask = 0;
974 EXPECT_THROW((void)next_combination_mask(mask, 65), std::out_of_range);
975
976 mask = (uint64_t(1) << 7); // outside n=5
977 EXPECT_THROW((void)next_combination_mask(mask, 5), std::domain_error);
978}
979
980TEST(AhComb, ForEachCombinationArrayAndEarlyStop)
981{
982 Array<int> values = {10, 20, 30, 40};
983
984 std::vector<std::string> seen;
985 bool full = for_each_combination(values, 2, [&seen](const Array<int> & c)
986 {
987 seen.push_back(seq_to_string(c));
988 return true;
989 });
990 EXPECT_TRUE(full);
991
992 const std::vector<std::string> expected = {
993 "10,20", "10,30", "10,40", "20,30", "20,40", "30,40"
994 };
995 EXPECT_EQ(seen, expected);
996
997 size_t calls = 0;
998 bool done = for_each_combination(values, 3, [&calls](const Array<int> &)
999 {
1000 ++calls;
1001 return calls < 3;
1002 });
1003 EXPECT_FALSE(done);
1004 EXPECT_EQ(calls, 3u);
1005}
1006
1007TEST(AhComb, ForEachCombinationEdgeCases)
1008{
1009 Array<int> values = {1, 2, 3};
1010
1011 size_t calls = 0;
1012 bool ok = for_each_combination(values, 0, [&calls](const Array<int> & c)
1013 {
1014 ++calls;
1015 EXPECT_EQ(c.size(), 0u);
1016 return true;
1017 });
1018 EXPECT_TRUE(ok);
1019 EXPECT_EQ(calls, 1u);
1020
1021 EXPECT_THROW((void)for_each_combination(values, 4,
1022 [](const Array<int> &) { return true; }), std::domain_error);
1023}
1024
1025TEST(AhComb, BuildCombinationsArrayAndDynArray)
1026{
1027 Array<int> values = {1, 2, 3, 4};
1028 auto combs = build_combinations(values, 3);
1029 ASSERT_EQ(combs.size(), 4u);
1030 EXPECT_EQ(seq_to_string(combs(0)), "1,2,3");
1031 EXPECT_EQ(seq_to_string(combs(1)), "1,2,4");
1032 EXPECT_EQ(seq_to_string(combs(2)), "1,3,4");
1033 EXPECT_EQ(seq_to_string(combs(3)), "2,3,4");
1034
1035 DynArray<int> dyn;
1036 dyn.reserve(4);
1037 dyn(0) = 1;
1038 dyn(1) = 2;
1039 dyn(2) = 3;
1040 dyn(3) = 4;
1041
1042 auto combs_dyn = build_combinations(dyn, 2);
1043 ASSERT_EQ(combs_dyn.size(), 6u);
1044 EXPECT_EQ(seq_to_string(combs_dyn(0)), "1,2");
1045 EXPECT_EQ(seq_to_string(combs_dyn(5)), "3,4");
1046}
1047
1048TEST(AhComb, NodiscardAllPerm)
1049{
1050 DynList<int> l1 = {1, 2};
1052
1053 // Should not trigger nodiscard warning - use result
1054 auto all = all_perm(l, [](const DynList<int> &) { return true; });
1055 EXPECT_TRUE(all);
1056}
1057
1058TEST(AhComb, NodiscardNonePerm)
1059{
1060 DynList<int> l1 = {1, 2};
1062
1063 // Should not trigger nodiscard warning - use result
1064 auto none = none_perm(l, [](const DynList<int> &) { return false; });
1065 EXPECT_TRUE(none);
1066}
1067
1068TEST(AhComb, NodiscardFilterPerm)
1069{
1070 DynList<int> l1 = {1, 2};
1072
1073 // Should not trigger nodiscard warning - use result
1074 auto filtered = filter_perm(l, [](const DynList<int> &) { return true; });
1075 EXPECT_EQ(filtered.size(), 2u);
1076}
1077
1078TEST(AhComb, NodiscardMapPerm)
1079{
1080 DynList<int> l1 = {1, 2};
1082
1083 // Should not trigger nodiscard warning - use result
1084 auto mapped = map_perm<int>(l, [](const DynList<int> & p) { return p.get_first(); });
1085 EXPECT_EQ(mapped.size(), 2u);
1086}
1087
1088TEST(AhComb, GrayCodeConversion)
1089{
1090 // n = 0..7
1091 const std::vector<uint32_t> expected_gray = {
1092 0, 1, 3, 2, 6, 7, 5, 4
1093 };
1094
1095 for (uint32_t i = 0; i < expected_gray.size(); ++i)
1096 {
1097 uint32_t g = bin_to_gray(i);
1098 EXPECT_EQ(g, expected_gray[i]) << "bin_to_gray mismatch at i=" << i;
1099 EXPECT_EQ(gray_to_bin(g), i) << "gray_to_bin mismatch at g=" << g;
1100 }
1101}
1102
1103TEST(AhComb, BuildGrayCode)
1104{
1105 const size_t n = 4;
1106 auto gray = build_gray_code(n);
1107
1108 ASSERT_EQ(gray.size(), 16u);
1109
1110 // Verify adjacency property (exactly one bit difference)
1111 for (size_t i = 1; i < gray.size(); ++i)
1112 {
1113 uint32_t diff = gray[i] ^ gray[i-1];
1114 // diff should be a power of 2
1115 EXPECT_TRUE(diff > 0 && (diff & (diff - 1)) == 0)
1116 << "Not a Gray code sequence at i=" << i
1117 << " (values: " << gray[i-1] << ", " << gray[i] << ")";
1118 }
1119
1120 // Verify cyclic property
1121 uint32_t diff_last = gray[gray.size()-1] ^ gray[0];
1122 EXPECT_TRUE(diff_last > 0 && (diff_last & (diff_last - 1)) == 0);
1123}
1124
1125TEST(AhComb, GrayCodeLargeValue)
1126{
1127 uint64_t val = 0x123456789ABCDEF0ULL;
1128 uint64_t g = bin_to_gray(val);
1129 EXPECT_EQ(gray_to_bin(g), val);
1130}
1131
1132TEST(AhComb, BuildGrayCodeThrowsOnTooLarge)
1133{
1134 EXPECT_THROW(build_gray_code(32), std::domain_error);
1135}
1136// satisfy CI policy
Combinatorics utilities: permutations, combinations, and matrix transposition.
Functional programming utilities for Aleph-w containers.
size_t row
Definition ca-c-api.h:115
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void reserve(const size_t l, const size_t r)
Allocate a range of entries.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & get_first()
Return the first item of the list.
Definition htlist.H:1548
T & insert(const T &item)
Definition htlist.H:1308
T & get_last()
Return the last item of the list.
Definition htlist.H:1529
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Minimal std::expected-style result type for C++20.
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
constexpr bool is_empty() const noexcept
Checks if the table is empty.
Definition hashDry.H:959
#define TEST(name)
Main namespace for Aleph-w library functions.
bool none_perm(const DynList< DynList< T > > &l, Pred &pred)
Check if no permutation satisfies a predicate.
Definition ah-comb.H:694
DynList< DynList< T > > build_combs(const DynList< DynList< T > > &l)
Build the set of unique combinations from a list of lists.
Definition ah-comb.H:535
bool for_each_combination(const Array< T > &values, const size_t k, Op &&op)
*‍/
Definition ah-comb.H:1013
Array< Array< T > > build_combinations(const Array< T > &values, const size_t k)
Materialize all k-combinations of Array<T>.
Definition ah-comb.H:1035
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
bool next_combination_indices(Array< size_t > &idx, const size_t n, const bool reset_on_last=true)
Advance an index-combination [i0 < i1 < ... < i(k-1)] to the next one.
Definition ah-comb.H:878
size_t perm_count(const DynList< DynList< T > > &l)
Count the total number of permutations from a list of lists.
Definition ah-comb.H:601
bool traverse_perm(const DynList< DynList< T > > &l, Op &op)
*‍/
Definition ah-comb.H:443
constexpr T gray_to_bin(T g) noexcept
Convert a Gray code number to its binary representation.
Definition ah-comb.H:1088
bool next_combination_mask(uint64_t &mask, const size_t n, const bool reset_on_last=true)
Advance a fixed-popcount bitmask to the next combination (Gosper hack).
Definition ah-comb.H:919
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
DynList< DynList< T > > filter_perm(const DynList< DynList< T > > &l, Pred &pred)
Filter permutations that satisfy a predicate.
Definition ah-comb.H:720
bool exists(Container &container, Operation &operation)
Return true if at least one element satisfies a predicate.
DynArray< T > sort(const DynArray< T > &a, Cmp &&cmp=Cmp())
Returns a sorted copy of a DynArray.
Definition ahSort.H:234
Array< uint32_t > build_gray_code(const size_t n)
Generate the sequence of n-bit Gray codes.
Definition ah-comb.H:1107
bool next_permutation(Array< T > &a, Compare cmp=Compare(), const bool reset_on_last=true)
Compute the next lexicographic permutation of an Array.
Definition ah-comb.H:800
void for_each_perm(const DynList< DynList< T > > &l, Op &op)
Apply a procedure to every permutation produced by traverse_perm.
Definition ah-comb.H:482
DynList< DynList< T > > transpose(const DynList< DynList< T > > &l)
*‍/
Definition ah-comb.H:250
T product(const Container &container, const T &init=T{1})
Compute product of all elements.
bool diff(const C1 &c1, const C2 &c2, Eq e=Eq())
Check if two containers differ.
uint64_t first_combination_mask(const size_t k)
Build the first k-of-64 combination mask (k low bits set).
Definition ah-comb.H:892
size_t combination_count(size_t n, size_t k)
Compute n choose k with overflow checks.
Definition ah-comb.H:824
DynList< DynList< T > > build_perms(const DynList< DynList< T > > &l)
Materialize all permutations from a list of lists.
Definition ah-comb.H:511
void in_place_transpose(C< C< T > > &l)
In-place transpose of a rectangular matrix stored as a nested container.
Definition ah-comb.H:294
bool exists_perm(const DynList< DynList< T > > &l, Pred &pred)
Check if any permutation satisfies a predicate.
Definition ah-comb.H:628
constexpr T bin_to_gray(const T n) noexcept
Convert a binary number to its Gray code representation.
Definition ah-comb.H:1071
bool all_perm(const DynList< DynList< T > > &l, Pred &pred)
Check if all permutations satisfy a predicate.
Definition ah-comb.H:666
bool none(const Container &container, Operation &operation)
Return true if no element satisfies operation.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
DynList< char > l3
DynList< int > l1
DynList< int > l2
DynSetTree< char > l5
DynList< int > l