@@ -91,22 +91,45 @@ int calculate_payout(int left, int middle, int right)
91
91
// {
92
92
// ++counter[number % 10];
93
93
// }
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 ())
104
127
{
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 ;
110
133
}
111
134
return 0 ;
112
135
}
@@ -168,12 +191,21 @@ void check_properties()
168
191
// parallel request
169
192
assert (std::count (std::execution::par, diffs.begin (), diffs.end (), 1 ) == count);
170
193
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
172
196
for (size_t i = 0 ; i < triangle_numbers.size (); ++i)
173
197
{
174
198
const int n = i + 1 ;
175
199
assert (triangle_numbers[i] == n * (n + 1 ) / 2 );
176
200
}
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
+ ));
177
209
178
210
assert (calculate_payout (0 , 1 , 3 ) == 0 );
179
211
assert (calculate_payout (0 , 0 , 3 ) == 1 );
0 commit comments