Skip to content

Commit da7e149

Browse files
committed
Tweaks in chapter 9
1 parent 1810d4e commit da7e149

File tree

1 file changed

+48
-16
lines changed

1 file changed

+48
-16
lines changed

Chapter9/main.cpp

Lines changed: 48 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -91,22 +91,45 @@ int calculate_payout(int left, int middle, int right)
9191
//{
9292
// ++counter[number % 10];
9393
//}
94-
// TODO generalize this bit:
95-
if (counter.size()==1)
96-
{
97-
if (counter[3] == 3 || counter[8] == 3)
98-
{
99-
return 4;
100-
}
101-
return 2;
102-
}
103-
else if (counter.size() == 2)
94+
// TODO compare with max_element next:
95+
//if (counter.size()==1)
96+
//{
97+
// if (counter[3] == 3 || counter[8] == 3)
98+
// {
99+
// return 4;
100+
// }
101+
// return 2;
102+
//}
103+
//else if (counter.size() == 2)
104+
//{
105+
// if (counter[3] == 2 || counter[8] == 2)
106+
// {
107+
// return 2;
108+
// }
109+
// return 1;
110+
//}
111+
//return 0;
112+
// TODO can we constexpr this?
113+
// TODO ranges version and mention niebloids
114+
// https://en.cppreference.com/w/cpp/algorithm/ranges/max_element
115+
/*
116+
* The function-like entities described on this page are niebloids, that is:
117+
* Explicit template argument lists cannot be specified when calling any of them.
118+
* None of them are visible to argument-dependent lookup.
119+
* When any of them are found by normal unqualified lookup as the name to the left of the function-call operator,
120+
* argument-dependent lookup is inhibited.
121+
*/
122+
auto it = std::max_element(counter.begin(), counter.end(),
123+
[](auto it1, auto it2) { return it1.second < it2.second; });
124+
// can this ever be end?
125+
// what if two match?
126+
if (it != counter.end())
104127
{
105-
if (counter[3] == 2 || counter[8] == 2)
106-
{
107-
return 2;
108-
}
109-
return 1;
128+
int digit = it->first;
129+
size_t count = it->second;
130+
constexpr int value[] = {0, 0, 1, 2};
131+
auto pay = ((digit == 8 || digit == 3) ? 2 : 1) * value[count];
132+
return pay;
110133
}
111134
return 0;
112135
}
@@ -168,12 +191,21 @@ void check_properties()
168191
// parallel request
169192
assert(std::count(std::execution::par, diffs.begin(), diffs.end(), 1) == count);
170193

171-
// Check closed form n * (n+1)/2 // TODO an algo rather than an old skool for loop?
194+
// Check closed form n * (n+1)/2
195+
// either with a for loop
172196
for (size_t i = 0; i < triangle_numbers.size(); ++i)
173197
{
174198
const int n = i + 1;
175199
assert(triangle_numbers[i] == n * (n + 1) / 2);
176200
}
201+
// or an algo with a mutable lambda
202+
assert(std::all_of(triangle_numbers.begin(), triangle_numbers.end(),
203+
[n = 0](int x) mutable
204+
{
205+
++n;
206+
return x == n * (n + 1) / 2;
207+
}
208+
));
177209

178210
assert(calculate_payout(0, 1, 3) == 0);
179211
assert(calculate_payout(0, 0, 3) == 1);

0 commit comments

Comments
 (0)