text stringlengths 1 2.12k | source dict |
|---|---|
c++, template, signal-processing
We then check that that we don't use a time constant that's too large to convert to the sum type:
explicit damper(Count time_constant)
: time_constant{time_constant}
{
if (time_constant <= 0) {
throw std::invalid_argument("damper needs positive time constant");
}
if constexpr (std::is_integral_v<Sum> && std::is_signed_v<Sum>) {
if (!std::in_range<Sum>(time_constant)) {
throw std::invalid_argument("time constant too large for signed arithmetic");
}
}
}
And the final calculation divides using the sum type:
return damped_value = static_cast<Value>(sum / static_cast<Sum>(count));
This passes the full provided test suite, and this additional test:
TEST(Damper, MixedSignedness)
{
test_damper<int, int, unsigned int>();
EXPECT_THROW((damper<int, int, unsigned>(std::numeric_limits<unsigned>::max())),
std::invalid_argument);
} | {
"domain": "codereview.stackexchange",
"id": 42985,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, signal-processing",
"url": null
} |
python, beginner, python-3.x, object-oriented
Title: OOP Matchsticks Game [Update]
Question: I made the changes that were suggested to improve the program in the previous version. I would like to know if it is decent now or is there something to tweak.
class MatchsticksGame:
def __init__(self, initial_matchsticks=23):
self.players = ('Player 1', 'Player 2')
self.player = None
self.turn = 0
self.matchsticks = initial_matchsticks
def _current_player(self):
return self.players[self.turn % 2]
def _show_matchsticks(self):
x, y = divmod(self.matchsticks, 5)
return '||||| '*x + '|'*y
def _get_move(self, player):
while True:
try:
matchsticks_to_remove = int(input(f'{player} removes matchsticks: '))
if 1 <= matchsticks_to_remove <= 3:
return matchsticks_to_remove
print('You can delete only between 1 and 3 matchsticks.')
except ValueError:
print('The value entered is invalid. You can only enter numeric values.')
def _play_turn(self):
self.player = self._current_player()
self.turn += 1
def _game_finished(self):
return self.matchsticks <= 0
def play(self):
print('Game starts.')
print(self._show_matchsticks())
while self.matchsticks > 0:
self._play_turn()
matchsticks_to_remove = self._get_move(self.player)
self.matchsticks -= matchsticks_to_remove
print(self._show_matchsticks())
if self._game_finished():
print(f'{self.player} is eliminated.')
break
if __name__ == '__main__':
game = MatchsticksGame()
game.play()
Answer: There are a few things that you may want to improve. | {
"domain": "codereview.stackexchange",
"id": 42986,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, object-oriented",
"url": null
} |
python, beginner, python-3.x, object-oriented
Answer: There are a few things that you may want to improve.
Currently, the active player is determined in _current_player() by the turn number: if it's even, it's the turn of Player 1, otherwise, it's the turn of Player 2. This works, but it's not very explicit, and it would fail for any single- or multiplayer version of your game where the number of players is not two. Given that you only need the value determined by _current_player() to be able to print the right player name, I'd recommend using a different data structure to handle the players: deque from the collections module.
A deque is basically a list that is optimized for inserting new elements at the beginning of the list. It also has a rotate(n=1) method that shifts the elements in the list by n positions. You can use this after every turn so that the first element of the deque contains always the current player. In this way, you can dispose of the class variables turn and player, as well as the methods _current_player() and _play_turn().
Your program doesn't properly handle cases in which the current player enters a number that exceeds the number of remaining sticks. For example, if there is only one stick left, the current player can still input 3. They will lose after all, but _show_matchsticks() will produce an output that looks as if there were still sticks remaining. You can solve this by changing the input validation in _get_move() to take the current number of sticks into account. | {
"domain": "codereview.stackexchange",
"id": 42986,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, object-oriented",
"url": null
} |
python, beginner, python-3.x, object-oriented
Your main game loop is a while loop with a losing condition, but you also use the method _game_finished() to determine the losing condition, and to explicitly break from the while loop even though it would stop at that point anyway. You can either remove the check for _game_finished(), or you can change the conditional while loop to a loop that will need to be halted explicitly (i.e. while True:). The latter version is an idiom frequently found for game loops or event loops. Given the simplicity of your game, however, I think it's more explicit and reader-friendly if you make the while loop determine whether the game has been lost, thus getting rid of _game_finished().
There are two calls to _show_matchsticks(), one before and one inside of your game loop. By rearranging them, you can reduce that to just one.
For reasons of brevity, I'd recommend to subtract the result of _get_move() from matchsticks without storing it in the intermediate variable matchsticks_to_remove.
Currently, you haven't limited the number of characters per line. PEP8, which is the ultimate reference for all issues concerning Python coding style, recommends a line length of 79 characters. This affects the lines with print() statements, which can be reformatted to include line breaks at appropriate places. For more complex programs, you may want to consider to store the strings in constants that are defined in one place anyway, because this will make changing the game output easier e.g. if you want to offer localized versions of your game.
Here's a version that combines these suggestions:
from collections import deque
class MatchsticksGame:
def __init__(self, initial_matchsticks=23):
self.players = deque(['Player 1', 'Player 2'])
self.matchsticks = initial_matchsticks
def _show_matchsticks(self):
x, y = divmod(self.matchsticks, 5)
return '||||| '*x + '|'*y | {
"domain": "codereview.stackexchange",
"id": 42986,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, object-oriented",
"url": null
} |
python, beginner, python-3.x, object-oriented
def _get_move(self, player):
max_value = min(3, self.matchsticks)
while True:
try:
matchsticks_to_remove = int(
input(f'{player} removes matchsticks: '))
if 1 <= matchsticks_to_remove <= max_value:
return matchsticks_to_remove
print('You can delete only between 1 and '
f'{max_value} matchsticks.')
except ValueError:
print('The value entered is invalid. You can only enter '
'numeric values.')
def play(self):
print('Game starts.')
while self.matchsticks > 0:
print(self._show_matchsticks())
player = self.players[0]
self.matchsticks -= self._get_move(player)
self.players.rotate()
print(f'{player} is eliminated.')
if __name__ == '__main__':
game = MatchsticksGame()
game.play()
However, now there is only little justification left to use an object-oriented structure – a procedural version of your game is even more readable than that. This version will feature your methods _get_move(), _show_matchsticks(), and play() as separate module-level functions, and the game state will be passed between the functions as arguments. play() will be expanded by the initialization statements, and relabeled as main() because it's now the main top-level function.
In my opinion, this is pretty close to the most concise and most explicit version of your game that you can get:
from collections import deque
def show_matchsticks(matchsticks):
x, y = divmod(matchsticks, 5)
return '||||| ' * x + '|' * y
def get_move(player, matchsticks):
max_value = min(3, matchsticks)
while True:
try:
value = int(input(f'{player} removes matchsticks: '))
if 1 <= value <= max_value:
return value | {
"domain": "codereview.stackexchange",
"id": 42986,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, object-oriented",
"url": null
} |
python, beginner, python-3.x, object-oriented
if 1 <= value <= max_value:
return value
print(f'You can delete only between 1 and {max_value} matchsticks.')
except ValueError:
print('The value entered is invalid. You can only enter numeric '
'values.')
def main(matchsticks=23):
players = deque(['Player 1', 'Player 2'])
print('Game starts.')
while matchsticks > 0:
print(show_matchsticks(matchsticks))
player = players[0]
matchsticks -= get_move(player, matchsticks)
players.rotate()
print(f'{player} is eliminated.')
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 42986,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, object-oriented",
"url": null
} |
python, performance, python-3.x, algorithm, fibonacci-sequence
Title: Python functions that calculate first n terms of a given order of Fibonacci sequences
Question: I have written two functions that calculate the first n terms of a given order o of Fibonacci sequence, and return the result as a list of ints.
from en.Wikipedia
Extension to negative integers
Using \$F_{n−2} = F_n − F_{n−1}\$, one can extend the Fibonacci
numbers to negative integers. So we get:
… −8, 5, −3, 2, −1, 1, 0, 1, 1, 2, 3, 5, 8, …
and \$F_{-n} = (−1)^{n+1}F_n\$
Fibonacci numbers of higher order
A Fibonacci sequence of order \$n\$ is an integer sequence in which each
sequence element is the sum of the previous \$n\$
elements (with the exception of the first \$n\$
elements in the sequence).
The usual Fibonacci numbers are a Fibonacci sequence of order \$2\$.
The cases \$n = 3\$ and \$n = 4\$ have been thoroughly investigated.
The number of compositions of nonnegative integers into parts
that are at most \$n\$ is a Fibonacci sequence of order \$n\$.
The sequence of the number of strings of \$0\$s and
\$1\$s of length \$m\$ that contain at most \$n\$ consecutive 0s
is also a Fibonacci sequence of order \$n\$.
Tribonacci numbers
The tribonacci numbers are like the Fibonacci numbers,
but instead of starting with two predetermined terms,
the sequence starts with three predetermined terms
and each term afterwards is the sum of the preceding three terms.
The first few tribonacci numbers are:
0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768, 10609, 19513, 35890, 66012, …
(sequence A000073 in the OEIS)
Tetranacci numbers
The tetranacci numbers start with four predetermined terms,
each term afterwards being the sum of the preceding four terms.
The first few tetranacci numbers are:
0, 0, 0, 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536, 10671, 20569, 39648, 76424, 147312, 283953, 547337, …
(sequence A000078 in the OEIS) | {
"domain": "codereview.stackexchange",
"id": 42987,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, algorithm, fibonacci-sequence",
"url": null
} |
python, performance, python-3.x, algorithm, fibonacci-sequence
(sequence A000078 in the OEIS)
A random Fibonacci sequence can be defined by
tossing a coin for each position \$n\$ of the sequence and taking
\$F(n) = F(n−1) + F(n−2)\$ if it lands heads and
\$F(n) = F(n−1) − F(n−2)\$ if it lands tails.
Work by Furstenberg and Kesten guarantees that this sequence
almost surely grows exponentially at a constant rate:
the constant is independent of the coin tosses
and was computed in 1999 by Divakar Viswanath.
It is now known as Viswanath's constant.
The two functions support extension to negative integers and random Fibonacci sequences, and take three parameters: o: int, n: int, r: int, o means order (of recursion), n means number of terms and r specifies whether you want the result randomized or not (default False).
o must be no less than 2. If you input 2 you get Fibonacci, 3 to get Tribonacci, 4 -> Tetranacci, 5 -> Pentanacci, and so on.
n must be greater than or equal to o (so that you can always tell the order of the sequence and the function never returns a list consisted solely of 0s),
r should be always an int (bool subclasses from int).
The following are the functions I want reviewed, I choose the iterative approach, their share the same logic, but I implemented one with a list-based approach, the other using variable swapping and variable unpacking:
import random | {
"domain": "codereview.stackexchange",
"id": 42987,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, algorithm, fibonacci-sequence",
"url": null
} |
python, performance, python-3.x, algorithm, fibonacci-sequence
def h_nacci(o, n, r=False):
if any(not isinstance(i, int) for i in (n, o, r)):
raise TypeError('All parameters must be an integer')
if o < 2 or abs(n) < o:
raise ValueError('Order is less than 2 or number of terms is less than order')
positive = True
if n < 0:
positive = False
n = -n
def worker(n):
stack = [0] * (o-1) + [1]
for i in range(n):
yield stack[0] if positive else (-1)**(i%2+1)*stack[0]
o_stack = stack
stack = stack[1:]
if r and random.randrange(2):
stack.append(stack[-1] - sum(o_stack[:-1]))
continue
stack.append(sum(o_stack))
series = list(worker(n))
return series if positive else series[::-1]
def o_nacci(o, n, r=False):
if any(not isinstance(i, int) for i in (n, o, r)):
raise TypeError('All parameters must be an integer')
if o < 2 or abs(n) < o:
raise ValueError('Order is less than 2 or number of terms is less than order')
positive = True
if n < 0:
positive = False
n = -n
def worker(n):
x, *y, z = [0] * (o-1) + [1]
for i in range(n):
yield x if positive else (-1)**(i%2+1)*x
if r and random.randrange(2):
x, *y, z = *y, z, z - sum(y) - x
continue
x, *y, z = *y, z, x + sum(y) + z
series = list(worker(n))
return series if positive else series[::-1]
Sample output:
In [2]: h_nacci(2, 10)
Out[2]: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
In [3]: o_nacci(2, 10)
Out[3]: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
In [4]: h_nacci(3, 10)
Out[4]: [0, 0, 1, 1, 2, 4, 7, 13, 24, 44]
In [5]: o_nacci(3, 10)
Out[5]: [0, 0, 1, 1, 2, 4, 7, 13, 24, 44]
In [6]: h_nacci(3, -10)
Out[6]: [44, -24, 13, -7, 4, -2, 1, -1, 0, 0]
In [7]: o_nacci(3, -10)
Out[7]: [44, -24, 13, -7, 4, -2, 1, -1, 0, 0]
In [8]: h_nacci(2, 10, 1)
Out[8]: [0, 1, 1, 2, 3, 1, 4, 3, -1, 2] | {
"domain": "codereview.stackexchange",
"id": 42987,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, algorithm, fibonacci-sequence",
"url": null
} |
python, performance, python-3.x, algorithm, fibonacci-sequence
In [8]: h_nacci(2, 10, 1)
Out[8]: [0, 1, 1, 2, 3, 1, 4, 3, -1, 2]
Performance:
In [9]: %timeit o_nacci(2, 256)
149 µs ± 3.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [10]: %timeit h_nacci(2, 256)
123 µs ± 4.25 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [11]: %timeit h_nacci(2, -256)
220 µs ± 4.21 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [12]: %timeit o_nacci(2, -256)
256 µs ± 35.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [13]: %timeit o_nacci(2, 256, 1)
331 µs ± 40 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [14]: %timeit h_nacci(2, 256, 1)
305 µs ± 33.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [15]: %timeit h_nacci(3, 256)
133 µs ± 6.14 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [16]: %timeit o_nacci(3, 256)
169 µs ± 4.71 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
I want to know how to improve their performance, I have implemented every idea I can think of and yet they are still too slow...
Below are some functions posted for comparison only:
def fibonacci(n):
positive = True
if n < 0:
positive = False
n = -n
def worker(n):
a, b = 0, 1
for i in range(n):
yield a if positive else (-1)**(i%2+1)*a
a, b = b, a + b
series = list(worker(n))
return series if positive else series[::-1]
def tribonacci(n):
positive = True
if n < 0:
positive = False
n = -n
def worker(n):
a, b, c = 0, 0, 1
for i in range(n):
yield a if positive else (-1)**(i%2+1)*a
a, b, c = b, c, a + b + c
series = list(worker(n))
return series if positive else series[::-1] | {
"domain": "codereview.stackexchange",
"id": 42987,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, algorithm, fibonacci-sequence",
"url": null
} |
python, performance, python-3.x, algorithm, fibonacci-sequence
def random_fibonacci(n):
def worker(n):
a, b = 0, 1
for i in range(n):
yield a
c = random.randrange(2)
if c == 0:
a, b = b, a + b
else:
a, b = b, b - a
return list(worker(n))
In [18]: %timeit fibonacci(256)
33.2 µs ± 2.71 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [19]: %timeit fibonacci(-256)
130 µs ± 5.54 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [20]: %timeit tribonacci(256)
45.2 µs ± 5.26 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [21]: %timeit tribonacci(-256)
148 µs ± 4.27 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [22]: %timeit random_fibonacci(256)
210 µs ± 5.57 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
How can I implement the same idea more efficiently? How can the two big functions be optimized further?
Answer: I can't see much in terms of ways to improve this. A deque (from collections) is a little faster than a list for adding to both ends:
def deque_nacci(o, n, r=False):
if any(not isinstance(i, int) for i in (n, o, r)):
raise TypeError('All parameters must be an integer')
if o < 2 or abs(n) < o:
raise ValueError('Order is less than 2 or number of terms is less than order')
positive = True
if n < 0:
positive = False
n = -n
def worker(n):
stack = deque([0] * (o-1) + [1])
for i in range(n):
if r and random.randrange(2):
last = stack.pop()
new_last = last - sum(stack)
stack.append(last)
stack.append(new_last)
else:
stack.append(sum(stack))
yield stack.popleft() if positive else (-1)**(i%2+1)*stack.popleft()
series = list(worker(n))
return series if positive else series[::-1]
That gives a slight improvement: | {
"domain": "codereview.stackexchange",
"id": 42987,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, algorithm, fibonacci-sequence",
"url": null
} |
c++, median, constrained-templates
Title: Flexible median evaluator
Question: I recently posted an externally-evaluating median algorithm
(i.e. not requiring move or copy of elements), and the feedback encouraged me
to develop it further.
One simple suggestion was to handle NaN values, and test using infinities.
It seems reasonable to return NaN if any are present in the input, as
median becomes meaningless. If users wish to ignore NaNs, they can by
using a filter view (see example in the test suite).
The other suggestion was to consider supporting projections of values.
I also wanted to avoid inefficiency of storing pointers (worse: I had
been storing iterators) in the cases where it's not necessary.
My original algorithm was already configurable with custom comparator
and midpoint functions; adding a projection to this was heading for
some combinatorial explosion of arguments, and making it hard to
default some subset of them, so I moved to a Builder pattern. That
allows simple use such as
// values is any sequence that satisfies Forward Range
auto m = stats::median(values);
and more advanced use by calling factories, possibly chained:
auto m = stats::median.using_compare(<std::greater>)
.using_arithmetic_midpoint()
(values);
To minimise copying, I wanted to sort in-place when we're passed
ownership:
auto m = stats::median(std::move(values));
If we want to permit mutating of all writable ranges, then we can
specifically ask for the in-place policy:
auto calc_median = stats::median.using_inplace_strategy();
auto m = calc_median(values);
The other primitive policies are
copy_strategy, which always makes a copy of the (projected)
values, and
external_strategy, which makes pointers to the elements (without
projection, since that need not be transparent). | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
Note that these three strategies have different requirements on the
range - copy accepts an input range; external needs a forward range;
inplace is most restrictive, needing a random-access range.
From these, we have two composite strategies:
The default strategy sorts in-place if possible, otherwise by
copying, falling back to the external strategy as a last resort.
The minimum-space (frugal) strategy also prefers to sort in-place
if possible, but prefers the external strategy over copying when
pointers to elements are smaller than projected values.
I've tried to use consistent template parameter names (i.e. Comp for
a comparator and Proj for projection). I looked to the standard for
guidance, but it's inconsistent in this respect - sometimes even within
one section (e.g. the description of nth_element() and its associated
concepts).
#include <algorithm>
#include <cmath>
#include <concepts>
#include <functional>
#include <iterator>
#include <memory>
#include <numeric>
#include <ranges>
#include <utility>
/*
A flexible but user-friendly way to evaluate the median of almost any collection.
Easy interface:
* stats::median(values) // values is unchanged
* stats::median(std::move(values)) // may re-order the container
* values | stats::median // works like a view
More advanced:
* auto small_median = stats::median.using_frugal_strategy();
small_median(values) // tries harder not to minimize memory use
* Other strategies are provided. The "inplace" strategy is useful to end users, as it treats all
inputs as rvalues (modifying through references) even without `std::move()`. The "copy" and
"external" strategies are mostly useful to the implementation of the default and frugal ones.
* We can use any comparator or projection function, and any any function to calculate the mean of
the mid elements (this function will be passed duplicate arguments if the input size is odd). | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
An "arithmetic" midpoint function is provided; this can be useful for getting fractional medians
from integer inputs. For example:
stats::median.using_arithmetic_midpoint()(std::array{ 0, 1, 2, 3}) ⟶ 1.5
*/
namespace stats
{
// Type traits
template<std::ranges::forward_range Range, typename Proj>
using projected_t =
std::projected<std::ranges::iterator_t<Range>, Proj>::value_type;
template<std::ranges::forward_range Range, typename Proj, typename Midpoint>
using median_result_t =
std::invoke_result_t<Midpoint, projected_t<Range, Proj>, projected_t<Range, Proj>>;
// Concepts
template<typename Range, typename Comp, typename Proj>
concept sortable_range =
std::sortable<std::ranges::iterator_t<Range>, Comp, Proj>;
template<typename C, typename Range, typename Proj>
concept projected_strict_weak_order =
std::indirect_strict_weak_order<C, std::projected<std::ranges::iterator_t<Range>, Proj>>;
template<typename M, typename Range, typename Proj>
concept midpoint_function =
std::invocable<M, projected_t<Range, Proj>, projected_t<Range, Proj>>;
template<typename S>
concept median_strategy =
std::is_same_v<std::invoke_result_t<S, std::vector<int>&&, std::less<>, std::identity, std::less<>>, bool>;
// Midpoint policies
struct default_midpoint
{
template<typename T>
constexpr auto operator()(T const& a, T const& b) const
{
using std::midpoint;
return midpoint(a, b);
}
};
template<typename T>
struct arithmetic_midpoint
{
constexpr auto operator()(T const& a, T const& b) const
{
return default_midpoint{}.operator()<T>(a, b);
}
}; | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
// Median policies
struct inplace_strategy
{
template<std::ranges::random_access_range Range,
std::invocable<std::ranges::range_value_t<Range>> Proj,
projected_strict_weak_order<Range, Proj> Comp,
midpoint_function<Range, Proj> Midpoint>
auto operator()(Range&& values, Comp compare, Proj proj, Midpoint midpoint) const
-> median_result_t<Range, Proj, Midpoint>
requires sortable_range<Range, Comp, Proj>
{
auto const size = std::ranges::distance(values);
auto upper = std::ranges::begin(values) + size / 2;
std::ranges::nth_element(values, upper, compare, proj);
auto lower = size % 2 ? upper
: std::ranges::max_element(std::ranges::begin(values), upper, compare, proj);
return midpoint(std::invoke(proj, *lower), std::invoke(proj, *upper));
}
};
struct inplace_strategy_rvalues_only
{
// Exists mainly to implement the default and frugal strategies
// But could be useful if you need to disallow copy and external.
template<std::ranges::random_access_range Range,
std::invocable<std::ranges::range_value_t<Range>> Proj,
projected_strict_weak_order<Range, Proj> Comp,
midpoint_function<Range, Proj> Midpoint>
auto operator()(Range&& values, Comp compare, Proj proj, Midpoint midpoint) const
-> median_result_t<Range, Proj, Midpoint>
requires sortable_range<Range, Comp, Proj> && (!std::is_lvalue_reference_v<Range>)
{
return inplace_strategy{}(std::forward<Range>(values), compare, proj, midpoint);
}
}; | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
struct copy_strategy
{
template<std::ranges::input_range Range,
std::invocable<std::ranges::range_value_t<Range>> Proj,
projected_strict_weak_order<Range, Proj> Comp,
midpoint_function<Range, Proj> Midpoint>
auto operator()(Range&& values, Comp compare, Proj proj, Midpoint midpoint) const
-> median_result_t<Range, Proj, Midpoint>
requires std::copyable<std::remove_reference_t<projected_t<Range, Proj>>>
{
auto projected = values | std::views::transform(proj);
auto v = std::vector(std::ranges::begin(projected), std::ranges::end(projected));
return inplace_strategy{}(v, compare, std::identity{}, midpoint);
}
};
struct external_strategy
{
template<std::ranges::forward_range Range,
std::invocable<std::ranges::range_value_t<Range>> Proj,
projected_strict_weak_order<Range, Proj> Comp,
midpoint_function<Range, Proj> Midpoint>
auto operator()(Range&& values, Comp compare, Proj proj, Midpoint midpoint) const
-> median_result_t<Range, Proj, Midpoint>
{
using pointer_type = std::add_pointer_t<const std::ranges::range_value_t<Range>>;
using pointer_traits = std::pointer_traits<pointer_type>;
auto indirect_project = [proj](auto *a)->decltype(auto) { return std::invoke(proj, *a); };
auto pointers = values | std::views::transform(pointer_traits::pointer_to);
auto v = std::vector(std::ranges::begin(pointers), std::ranges::end(pointers));
return inplace_strategy{}(v, compare, indirect_project, midpoint);
}
}; | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
struct default_strategy
{
template<std::ranges::forward_range Range,
std::invocable<std::ranges::range_value_t<Range>> Proj,
projected_strict_weak_order<Range, Proj> Comp,
midpoint_function<Range, Proj> Midpoint>
auto operator()(Range&& values, Comp compare, Proj proj, Midpoint midpoint) const
-> median_result_t<Range, Proj, Midpoint>
requires std::invocable<inplace_strategy_rvalues_only, Range, Comp, Proj, Midpoint>
|| std::invocable<copy_strategy, Range, Comp, Proj, Midpoint>
|| std::invocable<external_strategy, Range, Comp, Proj, Midpoint>
{
if constexpr (std::invocable<inplace_strategy_rvalues_only, Range, Comp, Proj, Midpoint>) {
return inplace_strategy_rvalues_only{}(std::forward<Range>(values), compare, proj, midpoint);
}
if constexpr (std::invocable<copy_strategy, Range, Comp, Proj, Midpoint>) {
try {
return copy_strategy{}(std::forward<Range>(values), compare, proj, midpoint);
} catch (std::bad_alloc&) {
if constexpr (!std::invocable<external_strategy, Range, Comp, Proj, Midpoint>) {
throw;
}
if constexpr (sizeof (projected_t<Range, Proj>*) >= sizeof (projected_t<Range, Proj>)) {
// external strategy won't help
throw;
}
// Else, we can try using external strategy more cheaply,
// so fallthrough to try that.
}
}
if constexpr (std::invocable<external_strategy, Range, Comp, Proj, Midpoint>) {
return external_strategy{}(std::forward<Range>(values), compare, proj, midpoint);
}
}
}; | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
struct frugal_strategy
{
template<std::ranges::forward_range Range,
std::invocable<std::ranges::range_value_t<Range>> Proj,
projected_strict_weak_order<Range, Proj> Comp,
midpoint_function<Range, Proj> Midpoint>
auto operator()(Range&& values, Comp compare, Proj proj, Midpoint midpoint) const
-> median_result_t<Range, Proj, Midpoint>
requires std::invocable<inplace_strategy_rvalues_only, Range, Comp, Proj, Midpoint>
|| std::invocable<copy_strategy, Range, Comp, Proj, Midpoint>
|| std::invocable<external_strategy, Range, Comp, Proj, Midpoint>
{
if constexpr (std::invocable<inplace_strategy_rvalues_only, Range, Comp, Proj, Midpoint>) {
return inplace_strategy_rvalues_only{}(std::forward<Range>(values), compare, proj, midpoint);
}
if constexpr (std::invocable<external_strategy, Range, Comp, Proj, Midpoint>) {
return external_strategy{}(std::forward<Range>(values), compare, proj, midpoint);
}
if constexpr (std::invocable<copy_strategy, Range, Comp, Proj, Midpoint>) {
return copy_strategy{}(std::forward<Range>(values), compare, proj, midpoint);
}
}
};
// The median calculator type
template<typename Proj, typename Comp, typename Midpoint, typename Strategy>
class median_engine
{
const Strategy strategy;
const Comp compare;
const Proj projection;
const Midpoint midpoint; | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
public:
// For simple construction, start with stats::median and use
// the builder interface to customise it.
constexpr median_engine(Proj projection, Comp comparer,
Midpoint midpoint, Strategy strategy) noexcept
: strategy{std::move(strategy)},
compare{std::move(comparer)},
projection{std::move(projection)},
midpoint{std::move(midpoint)}
{}
// Builder interface
template<typename P>
constexpr auto using_projection(P projection) const {
return median_engine<P, Comp, Midpoint, Strategy>
(std::move(projection), compare, midpoint, strategy);
}
template<typename C>
constexpr auto using_compare(C compare) const {
return median_engine<Proj, C, Midpoint, Strategy>
(projection, std::move(compare), midpoint, strategy);
}
template<typename M>
constexpr auto using_midpoint(M midpoint) const {
return median_engine<Proj, Comp, M, Strategy>
(projection, compare, std::move(midpoint), strategy);
}
template<typename T = double>
constexpr auto using_arithmetic_midpoint() const {
return using_midpoint(arithmetic_midpoint<T>{});
} | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
template<median_strategy S>
constexpr auto using_strategy(S strategy) const
{
return median_engine<Proj, Comp, Midpoint, S>
(projection, compare, midpoint, std::move(strategy));
}
constexpr auto using_external_strategy() const { return using_strategy(external_strategy{}); }
constexpr auto using_inplace_strategy() const { return using_strategy(inplace_strategy{}); }
constexpr auto using_copy_strategy() const { return using_strategy(copy_strategy{}); }
constexpr auto using_frugal_strategy() const { return using_strategy(frugal_strategy{}); }
constexpr auto using_default_strategy() const { return using_strategy(default_strategy{}); }
// Main function interface:
// Compute the median of a range of values
template<std::ranges::forward_range Range>
auto operator()(Range&& values) const
requires std::invocable<Strategy, Range, Comp, Proj, Midpoint>
{
return calculate_median(std::forward<Range>(values));
}
// Overload for const filter views which are not standard ranges.
// Some standard views (chunk_by_view, drop_while_view, filter_view, split_view) are not
// const-iterable, due to time complexity requirements on begin() requiring it to remember
// its result. See https://stackoverflow.com/q/67667318
template<typename View>
auto operator()(View&& values) const
requires (!std::ranges::range<View>)
&& std::ranges::range<std::decay_t<View>>
{
// Make a copy - which is a range
auto values_copy = values;
// but pass it as an lvalue ref so we don't order in-place by default
return calculate_median(values_copy);
} | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
private:
template<std::ranges::forward_range Range>
auto calculate_median(Range&& values) const
requires std::invocable<Strategy, Range, Comp, Proj, Midpoint>
{
auto const begin = std::ranges::begin(values);
auto const size = std::ranges::distance(values);
switch (size) {
case 0:
throw std::invalid_argument("Attempting median of empty range");
case 1:
{
auto const& a = project(begin);
return midpoint(a, a);
}
case 2:
{
auto const& a = project(begin);
auto const& b = project(std::next(begin));
if (compare(a, b)) {
// Yes, the order matters!
// e.g. std::midpoint rounds towards its first argument.
return midpoint(a, b);
} else {
return midpoint(b, a);
}
}
}
// If the range contains NaN values, there is no meaningful median.
// We still need to launder through mipoint() for correct return type.
using value_type = std::ranges::range_value_t<Range>;
if constexpr (std::is_floating_point_v<std::remove_reference_t<value_type>>) {
auto isnan = [](value_type d){ return std::isnan(d); };
if (auto it = std::ranges::find_if(values, isnan, projection); it != std::ranges::end(values)) {
return midpoint(project(it), project(it));
}
} | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
// If already ordered, just access the middle elements
if (std::ranges::is_sorted(values, compare, projection)) {
auto const lower = std::next(std::ranges::begin(values), (size - 1) / 2);
auto const upper = size % 2 ? lower : std::next(lower);
return midpoint(project(lower), project(upper));
}
// else use selected strategy
return strategy(std::forward<Range>(values), compare, projection, midpoint);
}
auto project(std::indirectly_readable auto p) const -> decltype(auto)
{
return std::invoke(projection, *p);
}
};
// We can put a median engine at the end of an adaptor chain
// e.g. auto midval = view | filter | median;
template<typename InputRange, typename... MedianArgs>
auto operator|(InputRange&& range, median_engine<MedianArgs...> engine)
{
return std::forward<median_engine<MedianArgs...>>(engine)(std::forward<InputRange>(range));
}
// Default engine, from which we can obtain customised ones using the builder interface.
static constexpr auto median = median_engine
{
std::identity{},
std::less<>{},
default_midpoint{},
default_strategy{}
};
}
#include <gtest/gtest.h>
#include <array>
#include <forward_list>
#include <stdexcept>
#include <vector>
namespace test
{
struct moveonly_int
{
int value;
moveonly_int(int i) : value{i} {}
moveonly_int(const moveonly_int&) = delete;
moveonly_int(moveonly_int&&) = default;
void operator=(const moveonly_int&) = delete;
moveonly_int& operator=(moveonly_int&&) = default;
bool operator<(const moveonly_int& other) const
{ return value < other.value; }
}; | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
// specific midpoint for this type, to be found by ADL
double midpoint(const moveonly_int& a, const moveonly_int& b)
{
return b.value - a.value; // the name is a lie
}
struct nocopy_int
{
int value;
nocopy_int(int i) : value{i} {}
nocopy_int(const nocopy_int&) = delete;
void operator=(const nocopy_int&) = delete;
bool operator<(const nocopy_int& other) const
{ return value < other.value; }
};
// specific midpoint for this type, to be found by ADL
double midpoint(const nocopy_int& a, const nocopy_int& b)
{
return a.value + b.value; // the name is a lie
}
template<typename T>
struct expect_midpoint {
const T expected_a;
const T expected_b;
void operator()(T const& actual_a, T const& actual_b) const
{
EXPECT_EQ(expected_a, actual_a);
EXPECT_EQ(expected_b, actual_b);
}
};
struct dummy_midpoint
{
auto operator()(auto&&, auto&&) const {}
};
struct invalid_strategy
{
template<std::ranges::forward_range Range,
typename Comp,
typename Proj,
typename Midpoint>
auto operator()(Range&&, Comp, Proj, Midpoint) const
-> stats::median_result_t<Range, Proj, Midpoint>
{
throw std::logic_error("should not be called");
}
};
}
// C++20 version of detection idiom
template<typename Func, typename... Args>
constexpr bool can_call(Func&&, Args&&...)
requires std::invocable<Func, Args...>
{ return true; }
template<typename... Args>
constexpr bool can_call(Args&&...)
{ return false; }
template<typename Strategy, typename Range>
concept strategy_accepts_type =
std::invocable<Strategy, Range, std::less<>, std::identity, test::dummy_midpoint>; | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
enum strategy_mask : unsigned {
sm_inplace = 0x01,
sm_inplace_rvalue = 0x02,
sm_copy = 0x04,
sm_external = 0x08,
sm_default = 0x10,
sm_frugal = 0x20,
sm_none = 0u,
sm_all = ~0u,
};
constexpr auto operator+(strategy_mask a, strategy_mask b)
{ return static_cast<strategy_mask>(static_cast<unsigned>(a) | static_cast<unsigned>(b)); }
constexpr auto operator-(strategy_mask a, strategy_mask b)
{ return static_cast<strategy_mask>(static_cast<unsigned>(a) & ~static_cast<unsigned>(b)); }
constexpr bool is_set(strategy_mask a, strategy_mask b)
{ return a & b; }
template<typename Range>
void expect_usable(strategy_mask m = 0)
{
if (!is_set(m, sm_inplace)) {
// if we can't inplace, then we certainly can't inplace-rvalue
m = m - sm_inplace_rvalue;
}
EXPECT_EQ(is_set(m, sm_inplace), (strategy_accepts_type<stats::inplace_strategy, Range>));
EXPECT_EQ(is_set(m, sm_inplace_rvalue), (strategy_accepts_type<stats::inplace_strategy_rvalues_only, Range>));
EXPECT_EQ(is_set(m, sm_copy), (strategy_accepts_type<stats::copy_strategy, Range>));
EXPECT_EQ(is_set(m, sm_external), (strategy_accepts_type<stats::external_strategy, Range>));
EXPECT_EQ(is_set(m, sm_default), (strategy_accepts_type<stats::default_strategy, Range>));
EXPECT_EQ(is_set(m, sm_frugal), (strategy_accepts_type<stats::frugal_strategy, Range>));
}
// Tests of callability
// (Could be static, but we get better diagnostics this way)
TEST(Strategies, Regular)
{
using Range = std::vector<int>;
{
SCOPED_TRACE("pass by value\n");
expect_usable<Range>(sm_all);
}
{
SCOPED_TRACE("pass by ref\n");
expect_usable<Range&>(sm_all - sm_inplace_rvalue);
}
{
SCOPED_TRACE("pass by const ref\n");
expect_usable<Range const&>(sm_all - sm_inplace);
}
{
SCOPED_TRACE("pass by rvalue\n");
expect_usable<Range&&>(sm_all);
}
} | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
TEST(Strategies, MoveOnly)
{
using Range = std::vector<test::moveonly_int>;
// can't be copied
{
SCOPED_TRACE("pass by value\n");
expect_usable<Range>(sm_all - sm_copy);
}
{
SCOPED_TRACE("pass by ref\n");
expect_usable<Range&>(sm_all - sm_copy - sm_inplace_rvalue);
}
{
SCOPED_TRACE("pass by const ref\n");
expect_usable<Range const&>(sm_external + sm_default + sm_frugal);
}
{
SCOPED_TRACE("pass by rvalue\n");
expect_usable<Range&&>(sm_all - sm_copy);
}
}
TEST(Strategies, NoCopy)
{
using Range = std::vector<test::nocopy_int>;
{
SCOPED_TRACE("pass by value\n");
expect_usable<Range>(sm_all - sm_inplace - sm_copy);
}
{
SCOPED_TRACE("pass by ref\n");
expect_usable<Range&>(sm_all - sm_inplace - sm_copy);
}
{
SCOPED_TRACE("pass by const ref\n");
expect_usable<Range const&>(sm_all - sm_inplace - sm_copy);
}
{
SCOPED_TRACE("pass by rvalue\n");
expect_usable<Range&&>(sm_all - sm_inplace - sm_copy);
}
}
TEST(Strategies, ForwardOnly)
{
using Range = std::forward_list<int>;
{
SCOPED_TRACE("pass by value\n");
expect_usable<Range>(sm_all - sm_inplace);
}
{
SCOPED_TRACE("pass by ref\n");
expect_usable<Range&>(sm_all - sm_inplace);
}
{
SCOPED_TRACE("pass by const ref\n");
expect_usable<Range const&>(sm_all - sm_inplace);
}
{
SCOPED_TRACE("pass by rvalue\n");
expect_usable<Range&&>(sm_all - sm_inplace);
}
} | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
TEST(Strategies, FilteredView)
{
using View = std::ranges::filter_view<std::ranges::ref_view<int[1]>, std::function<bool(int)>>;
{
SCOPED_TRACE("pass by value\n");
expect_usable<View>(sm_all - sm_inplace);
}
{
SCOPED_TRACE("pass by ref\n");
expect_usable<View&>(sm_all - sm_inplace);
}
{
SCOPED_TRACE("pass by const ref\n");
// const view isn't a range - needs median_engine to copy it
expect_usable<View const&>(sm_none);
}
{
SCOPED_TRACE("pass by rvalue\n");
expect_usable<View&&>(sm_all - sm_inplace);
}
}
// Don't even try compiling the rest unless earlier tests succeed!
#ifndef TYPE_TESTS_FAILED
// Use this one for tests where the engine should not call out to strategy.
// I.e. when input is ordered, or there's only 1 or 2 elements.
template<std::ranges::forward_range Container = std::vector<int>,
typename Midpoint = test::expect_midpoint<std::ranges::range_value_t<Container>>,
typename Comp = std::less<>, typename Proj = std::identity>
static void test_values_trivial(Container&& values, Midpoint expected,
Comp compare = {}, Proj projection = {})
{
stats::median
.using_compare(compare)
.using_projection(projection)
.using_midpoint(expected)
.using_strategy(test::invalid_strategy{}) // will fail if called
(std::forward<Container>(values));
}
template<std::ranges::forward_range Container = std::vector<int>,
typename Midpoint = test::expect_midpoint<std::ranges::range_value_t<Container>>,
typename Comp = std::less<>, typename Proj = std::identity>
static void test_values_const_input(const Container& values, Midpoint expected,
Comp compare = {}, Proj projection = {})
{
auto const m = stats::median
.using_compare(compare)
.using_projection(projection)
.using_midpoint(expected); | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
{
SCOPED_TRACE("default strategy");
m(values);
}
{
SCOPED_TRACE("copy strategy");
m.using_copy_strategy()(values);
}
{
SCOPED_TRACE("external strategy");
m.using_external_strategy()(values);
}
}
template<std::ranges::forward_range Container = std::vector<int>,
typename Midpoint = test::expect_midpoint<std::ranges::range_value_t<Container>>,
typename Comp = std::less<>, typename Proj = std::identity>
static void test_values(Container&& values, Midpoint expected,
Comp compare = {}, Proj projection = {})
{
test_values_const_input(values, expected, compare, projection);
auto const m = stats::median
.using_compare(compare)
.using_projection(projection)
.using_midpoint(expected);
SCOPED_TRACE("inplace strategy");
m.using_inplace_strategy()(std::move(values));
}
TEST(Median, Empty)
{
EXPECT_THROW(stats::median(std::vector<int>{}), std::invalid_argument);
}
TEST(Median, OneElement)
{
SCOPED_TRACE("from here\n");
test_values_trivial({100}, {100, 100});
}
TEST(Median, TwoElements)
{
SCOPED_TRACE("from here\n");
test_values_trivial({100, 200}, {100, 200});
SCOPED_TRACE("from here\n");
test_values_trivial({200, 100}, {100, 200});
}
TEST(Median, ThreeSortedElements)
{
SCOPED_TRACE("from here\n");
test_values_trivial({1, 2, 3}, {2, 2});
}
TEST(Median, ThreeElements)
{
SCOPED_TRACE("from here\n");
test_values({1, 3, 2}, {2, 2});
}
TEST(Median, FourSortedElements)
{
SCOPED_TRACE("from here\n");
test_values_trivial({2, 4, 6, 8}, {4, 6});
SCOPED_TRACE("from here\n");
test_values_trivial({4, 4, 4, 6}, {4, 4});
}
TEST(Median, FourElements)
{
SCOPED_TRACE("from here\n");
test_values({8, 2, 6, 4}, {4, 6});
SCOPED_TRACE("from here\n");
test_values({4, 4, 6, 4}, {4, 4});
} | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
TEST(Median, FiveElements)
{
SCOPED_TRACE("from here\n");
test_values({8, 2, 6, 4, 0}, {4, 4});
}
TEST(Median, PlainArray)
{
int values[] = { 2, 1, 3};
test_values(values, {2, 2});
}
TEST(Median, ConstPlainArray)
{
const int values[] = { 2, 1, 3};
test_values_const_input(values, {2, 2});
// Also exercise the range-adaptor style
EXPECT_EQ(values | stats::median, 2);
}
TEST(Median, Strings)
{
SCOPED_TRACE("from here\n");
std::string_view values[] = { "one", "two", "three", "four", "five", "six" };
// Alphabetical: five four ONE SIX three two
test_values(values, test::expect_midpoint<std::string_view>{"one", "six"});
}
TEST(Median, NaNsFirst)
{
constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
double values[] = { nan, nan, 1, 1, 100, 100, 10 };
EXPECT_TRUE(std::isnan(stats::median(values)));
}
TEST(Median, NaNsLast)
{
constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
double values[] = { 1, 1, 100, 100, 10, nan, nan };
EXPECT_TRUE(std::isnan(stats::median(values)));
}
TEST(Median, Infinities)
{
constexpr auto inf = std::numeric_limits<double>::infinity();
std::vector<double> values;
values = { -inf, inf, -inf };
EXPECT_EQ(stats::median(values), -inf);
values = { inf, -inf, inf };
EXPECT_EQ(stats::median(values), inf);
values = { inf, -inf, inf, -inf };
EXPECT_TRUE(std::isnan(stats::median(values))); // midpoint of ±∞
}
TEST(Median, CustomOrder)
{
auto const values = std::array{20, 91, 92, 54, 63};
// order by last digit: 0, 1, 2, 4, 3
auto const compare = [](int a, int b){ return a % 10 < b % 10; };
EXPECT_EQ(stats::median.using_compare(compare)(values), 92);
} | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
TEST(Median, CustomProjection)
{
auto const values = std::array{20, 91, 92, 54, 63};
// project to last digit: 0, 1, 2, 4, 3
auto const projection = [](int a){ return a % 10; };
EXPECT_EQ(stats::median.using_projection(projection)(values), 2);
}
TEST(Median, Value)
{
auto const values = std::forward_list{0, 1, 2, 3};
EXPECT_EQ(stats::median(values), 1); // rounded down
EXPECT_EQ(stats::median.using_arithmetic_midpoint()(values), 1.5);
// And with reverse order (causing integer std::midpoint() to round upwards)
auto m = stats::median.using_compare(std::greater<int>{});
EXPECT_EQ(m(values), 2);
EXPECT_EQ(m.using_arithmetic_midpoint<long double>()(values), 1.5L);
}
TEST(Median, MoveOnly)
{
// finds test::midpoint (which returns the difference!)
std::array<test::moveonly_int, 4> values{0, 3, 5, 2};
EXPECT_FALSE(can_call(stats::median.using_copy_strategy(), values));
EXPECT_EQ(stats::median(values), 1); // 3 - 2
EXPECT_EQ(stats::median.using_inplace_strategy()(values), 1);
}
TEST(Median, NoCopy)
{
// finds test::midpoint (which returns the sum!)
std::array<test::nocopy_int, 4> values{0, 1, 4, 2};
EXPECT_FALSE(can_call(stats::median.using_inplace_strategy(), values));
EXPECT_FALSE(can_call(stats::median.using_copy_strategy(), values));
EXPECT_EQ(stats::median.using_external_strategy()(values), 3); // 1 + 2
EXPECT_EQ(stats::median(std::move(values)), 3);
}
TEST(Median, ProjectByValue)
{
auto twice = [](auto x) { return 2 * x; };
constexpr auto m = stats::median.using_projection(twice);
int values[] = {0, 1, 3, 4, 2};
EXPECT_EQ(m.using_copy_strategy()(values), 4);
EXPECT_EQ(m.using_external_strategy()(values), 4);
EXPECT_EQ(m.using_inplace_strategy()(values), 4);
}
TEST(Median, FilteredRange)
{
constexpr auto nan = std::numeric_limits<double>::quiet_NaN(); | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
TEST(Median, FilteredRange)
{
constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
double values[] = { nan, nan, 1, 100, 10 };
auto view = values | std::views::filter([](double d){ return !std::isnan(d); });
EXPECT_EQ(stats::median.using_copy_strategy()(view), 10);
EXPECT_EQ(stats::median.using_external_strategy()(view), 10);
EXPECT_EQ(stats::median(view), 10);
EXPECT_EQ(values[2], 1); // shouldn't have modified underlying range
}
TEST(Median, FilteredRangeConst)
{
constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
double values[] = { nan, nan, 1, 100, 10 };
auto const view = values | std::views::filter([](double d){ return !std::isnan(d); });
EXPECT_EQ(stats::median.using_copy_strategy()(view), 10);
EXPECT_EQ(stats::median.using_external_strategy()(view), 10);
EXPECT_EQ(stats::median(view), 10);
EXPECT_EQ(values[2], 1); // shouldn't have modified underlying range
}
#endif
The updated code is now on GitHub; this version corresponds to commit d6ac335. | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
Answer: This looks very watertight. Just a few minor remarks:
Perhaps too much constraints?
You constrain the template parameters inside the template parameter list, but also using a requires-clause. A concept like std::sortable, or your own helper sortable_range, will already check that Range is a random access range and that Projected values can be compared using Comp. So it's a bit redundant, and you could remove some to make the code slightly more readable.
It might also the impact on the quality of the error messages. It might be nice to see "this set of arguments must form something that I can sort with" instead of "this comparator function does not give me a strict weak order over this range". But you'd have to check the output from different compilers to check what the actual effect is.
Make indirect_project() take a const pointer
A small nitpick, but the projection operation should not modify the range, so it would be better to make indirect_project take a const pointer argument.
The frugal_strategy might not be right for small value types
Consider that I might want the median value of a vector of std::int8_ts, then copy_strategy is preferrably over external_strategy, yet frugal_strategy always prefers the latter. Maybe have it check the size first and prefer copy when the size of a projected value type is equal to or smaller than a pointer.
Moving vs. copying the parameters of median_engine
The constructor of median_engine std::move()s all parameters. But the builder interface std::move()s only the single parameter of each builder function, but copies the corresponding 3 other member variables. You could make the member values of median_engine non-const, so all of them can be moved in the builder interface. On the other hand, you could just always copy, assuming it's unlikely that it is expensive.
Overhead of std::is_sorted() | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
c++, median, constrained-templates
Overhead of std::is_sorted()
While checking if the input is already sorted might speed up things greatly if the range is indeed sorted, it adds overhead in case it isn't. Also consider that for the in-place strategies, not checking it might be as fast as checking it, depending on the implementation of std::ranges::nth_element(). For the copy and external strategies, perhaps checking for sortedness during the copy is cheap enough to always do. | {
"domain": "codereview.stackexchange",
"id": 42988,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, median, constrained-templates",
"url": null
} |
php, authentication
Title: Authenticate and login script updated
Question: How can I improve/secure my login script and how to check for any possible injection?
PS. the script must run on multiple platforms, so I need empty arrays for cases such as the Android ones.
UPDATES
mysql structure
php switch cases instead of UNION
user_table:
CREATE TABLE `user_table` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_type` varchar(255) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_pass ` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=latin1
Field
Type
Null
Key
Default
Extra
user_id
int(11)
NO
PRI
NULL
auto_increment
user_type
varchar(255)
NO
NULL
user_email
varchar(255)
NO
NULL
user_pass
varchar(255)
NO
NULL
student_table:
CREATE TABLE `student_table` (
`user_id` int(11) NOT NULL,
`user_type` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Field
Type
Null
Key
Default
Extra
user_id
int(11)
NO
PRI
NULL
user_type
varchar(255)
NO
NULL
teacher_table:
CREATE TABLE `teacher_table` (
`user_id` int(11) NOT NULL,
`Class` varchar(255) NOT NULL,
`DEPARTMENT` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Field
Type
Null
Key
Default
Extra
user_id
int(11)
NO
PRI
NULL
Class
varchar(255)
NO
NULL
DEPARTMENT
varchar(255)
NO
NULL
management_table:
CREATE TABLE `management_table` (
`user_id` int(11) NOT NULL,
`Class` varchar(255) NOT NULL,
`DEPARTMENT` varchar(255) NOT NULL,
`HEAD` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Field
Type
Null
Key
Default
Extra
user_id
int(11)
NO
PRI
NULL
Class
varchar(255)
NO
NULL
DEPARTMENT
varchar(255)
NO
NULL
HEAD
varchar(255)
NO
NULL | {
"domain": "codereview.stackexchange",
"id": 42989,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, authentication",
"url": null
} |
php, authentication
Class
varchar(255)
NO
NULL
DEPARTMENT
varchar(255)
NO
NULL
HEAD
varchar(255)
NO
NULL
user_status table:
CREATE TABLE `user_status` (
`user_id` int(11) NOT NULL,
`Login_id` int(11) NOT NULL,
`user_token` varchar(255) NOT NULL,
`user_status` varchar(255) NOT NULL,
`time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Field
Type
Null
Key
Default
Extra
user_id
int(11)
NO
NULL
Login_id
int(11)
NO
PRI
NULL
auto_increment
user_token
varchar(255)
NO
NULL
user_status
varchar(255)
NO
NULL
time_stamp
timestamp
NO
CURRENT_TIMESTAMP
on update CURRENT_TIMESTAMP
login script:
<?php
//filter email var before connecting to database
function validateEmail($email) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//echo "email is valid";
}
else {
//echo "Email not valid";
exit;
}
}
//connect to database
function db_connect($db_name, $db_username, $db_password)
{
$conn = new PDO($db_name, $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
// check login credentials
function userLogin($email, $password,$PDO)
{
$stmt = $PDO->prepare("
SELECT user_table.user_id ,user_table.user_pass
FROM user_table
WHERE user_table.user_email = :EMAIL");
$stmt->bindParam(':EMAIL', $email);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$hash = $row['user_pass'];
$returnApp = array( 'LOGIN' => 'Wrong_password_email'); | {
"domain": "codereview.stackexchange",
"id": 42989,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, authentication",
"url": null
} |
php, authentication
if (!empty($row) && password_verify($password, $hash))
{
$user_id = $row['user_id'];
return $user_id;
}
else{
return $returnApp;
}
}
//guidv4
function guidv4($data = null) {
$data = $data ?? random_bytes(16);
assert(strlen($data) == 16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
//create token
function createtoken($user_id,$user_online,$user_token,$PDO){
$sql_insert = "INSERT INTO user_status
(user_id, user_token,user_status)
VALUES
(:ID,:TOKEN,:ONLINE );";
$stmt = $PDO->prepare($sql_insert);
$stmt->bindParam(':ID', $user_id);
$stmt->bindParam(':ONLINE', $user_online);
$stmt->bindParam(':TOKEN', $user_token);
if ($stmt->execute()){
}else{
}
}
//getting user type
function usertype($user_id,$PDO){
$sql_select ="SELECT user_table.user_type AS user
FROM user_table
WHERE user_table.user_id = :USER_ID";
$stmt = $PDO->prepare($sql_select);
$stmt->bindParam(':USER_ID', $user_id);
if ($stmt->execute()) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row;
}else{
}
}
//specifyuserquery
function specifyuser($user_type){
foreach ($user_type as $key) {
switch ($key) { | {
"domain": "codereview.stackexchange",
"id": 42989,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, authentication",
"url": null
} |
php, authentication
foreach ($user_type as $key) {
switch ($key) {
case 'STUDENT':
$query = "
SELECT
student_table.user_type AS type,
user_status.login_id AS id,
user_status.user_token AS Token
FROM student_table
LEFT JOIN user_status ON user_status.user_id = student_table.user_id
WHERE student_table.user_id = :USERID ";
return $query;
case 'TEACHER':
$query = "
SELECT
teacher_table.Class AS CL,
teacher_table.DEPARTMENT AS DEP,
user_status.login_id AS ID,
user_status.user_token AS TOKEN
FROM teacher_table
LEFT JOIN user_status ON user_status.user_id = teacher_table.user_id
WHERE teacher_table.user_id = :USERID ";
return $query;
case 'MANAGEMENT':
$query = "
SELECT
management_table.CLASS AS CL,
management_table.DEPARTMENT AS DEP,
management_table.HEAD AS HEAD,
user_status.login_id AS ID,
user_status.user_token AS TOKEN
FROM management_table
LEFT JOIN user_status ON user_status .user_id = management_table.user_id
WHERE management_table.user_id = :USERID"; | {
"domain": "codereview.stackexchange",
"id": 42989,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, authentication",
"url": null
} |
php, authentication
return $query;
}
}
}
//getdata
function getdata($query,$user_id,$PDO){
$stmt = $PDO->prepare($query);
$stmt->bindParam(':USERID', $user_id);
if ($stmt->execute()) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$data = array( 'LOGIN' => 'Log_In_Success');
$final = array_merge($data, $row);
return $final;
}else{
}
}
$email = $_POST['email'];
//validate email
validateEmail($email);
// connect to data base
try
{
$PDO=db_connect("mysql:host=localhost;dbname=DATABASE", "root", "");
//echo "connection success";
}
catch (PDOException $e) {
//echo "Database error! " . $e->getMessage();
}
$password =$_POST['pass'];
//getting either user_id or email/pass dont match database
$result = userLogin($email,$password,$PDO);
$user_online = 'ONLINE';
$user_token = guidv4();
//if checks if email/pass is correct or error
if (ctype_digit($result)) {
//create token
$token = createtoken($result,$user_online,$user_token,$PDO);
//get type
$user_type = usertype($result,$PDO);
//specifyuser
$query =specifyuser($user_type);
//getdata
$data = getdata($query,$result,$PDO);
// merge data with type
$final = array_merge($data,$user_type);
echo json_encode($final);
}else{
echo json_encode($result);
exit;
}
?> | {
"domain": "codereview.stackexchange",
"id": 42989,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, authentication",
"url": null
} |
php, authentication
}else{
echo json_encode($result);
exit;
}
?>
Answer: I'm still not a fan of this code.
For instance, the userLogin() function will return the user id, when an user was found. That's fine. However, when no user was found, it returns something completely different: An array with a error status and message. I prefer functions that always return the same type, or null/false. I would write something like this:
function getUserIdFromCredentials($database, $userEmail, $userPassword)
{
$query = "SELECT user_table.user_id ,user_table.user_pass " .
"FROM user_table " .
"WHERE user_table.user_email = :email";
$statement = $database->prepare($query);
$statement->execute([":email" => $email]);
if (($row = $statement->fetch(PDO::FETCH_ASSOC)) &&
password_verify($password, $row["user_pass"])) {
return $row["user_id"];
}
return null; // no user was found - credentials were not valid
} | {
"domain": "codereview.stackexchange",
"id": 42989,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, authentication",
"url": null
} |
php, authentication
This function returns null when no user id was found. The only thing we need to know is whether the credentials were valid or not. Error messages, if any, should be handled at another level of the code.
I also renamed the function from userLogin() to getUserIdFromCredentials(). Now this name might seem a bit long, but it does accurately describe what the function does. It doesn't log an user in, it gets the user id given the credentials entered by a visitor. In your code an user is only really "logged in" after you've created a token, I hope. Longer names are preferred, when they more accurately describe what they refer to. Longer names do not impact the speed at which the code executes.
Note how I don't access the $row array, until I know it exists.
You also use the login script to get information about the specific type of user. You store this information in separate tables. I feel that this doesn't belong in this login script. It's not needed for a valid login, and you need to retrieve this information elsewhere anyway. I would get rid of it here.
Now I cannot escape the feeling that this code isn't written for a web site, it seems to be written for an App or API. You don't tell us, but there's this very suspicious $returnApp variable, suggesting it's an App. An App might need to authenticate on every access to a script, when it is working stateless.
It would explain the absence of a logout function, and the lack of a cookie or session variable. On the other hand, you do generate a token, which is only useful when the script is not stateless. I don't know.
I would like you to actually make this code work. Finish it, so you can actually run and test it. Handle all errors properly. It's time to leave any theoretical discussions behind and get your hands dirty. | {
"domain": "codereview.stackexchange",
"id": 42989,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, authentication",
"url": null
} |
python, beginner, object-oriented, tic-tac-toe
Title: Tic Tac Toe in Python with OOP
Question: I programmed the tic-tac-toe game in Python using object oriented programming and I wanted to share it here to get some feedback
class TicTacToe:
def __init__(self):
self.board = [" "] * 9
self.spacer = "-" * 50
@property
def _select_letter(self):
computer_side = None
player_side = None
while True:
player_side = input("Choose your side: ").upper()
if player_side not in ("X", "O"):
print("You can only choose X or O.")
else:
break
computer_side = "O" if player_side == "X" else "X"
print(f"The computer has chosen to be {computer_side}.")
print(f"You will be {player_side}.")
return player_side, computer_side
@property
def _human_goes_first(self):
go_first = None
while go_first not in ("y", "n"):
go_first = input(("Do you require the first move? (y/n): ")).lower()
return go_first == "y"
@property
def _print_board(self):
return f"{self.board[0]}|{self.board[1]}|{self.board[2]}\n-+-+-\n{self.board[3]}|{self.board[4]}|{self.board[5]}\n-+-+-\n{self.board[6]}|{self.board[7]}|{self.board[8]}"
@property
def _board_full(self):
return not " " in self.board
def _check_win(self, letter):
win_combs = [letter, letter, letter]
return self.board[:3] == win_combs or self.board[3:6] == win_combs or self.board[6:] == win_combs or \
self.board[:7:3] == win_combs or self.board[1:8:3] == win_combs or self.board[2::3] == win_combs or \
self.board[::4] == win_combs or self.board[2:7:2] == win_combs | {
"domain": "codereview.stackexchange",
"id": 42990,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, tic-tac-toe",
"url": null
} |
python, beginner, object-oriented, tic-tac-toe
def _computer_move(self, player_letter, computer_letter):
corners = (2, 4, 6, 8)
# First, check if we can win in the next move.
for i in range(8):
if self.board[i] == " ":
if self._check_win(computer_letter):
self.board[i] = computer_letter
return
# Check if the player could win on their next move, and block them.
for i in range(8):
if self.board[i] == " ":
if self._check_win(player_letter):
self.board[i] = computer_letter
return
# Try to take one of the corners, if they are free.
for i in corners:
if self.board[i] == " ":
self.board[i] = computer_letter
return
# Try to take the center, if it is free.
if self.board[4] == " ":
self.board[4] = computer_letter
return
def _player_move(self, letter):
while True:
try:
move = int(input(f"It's your turn {letter}. Enter a number between 1-9: ")) - 1
if not 0 <= move <= 8:
print("The number entered is invalid. Enter a number between 1 and 9.")
elif self.board[move] != " ":
print("This place is already occupied.")
print(f"\n{self.spacer}\n")
else:
self.board[move] = letter
break
except ValueError:
print(f"Enter a number!\n\n{self.spacer}\n")
def play(self):
print("Welcome to Tic Tac Toe!")
human, computer = self._select_letter
first_player = self._human_goes_first
print(f"\n{self.spacer}") | {
"domain": "codereview.stackexchange",
"id": 42990,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, tic-tac-toe",
"url": null
} |
python, beginner, object-oriented, tic-tac-toe
while not self._board_full:
if first_player:
print(f"\nNow playing: Human ({human})")
self._player_move(human)
else:
print(f"\nNow playing: Computer ({computer})")
self._computer_move(human, computer)
first_player = False if first_player else True
print(f"\n{self._print_board}")
print(f"\n{self.spacer}")
if self._check_win(human):
print("\nYou won!")
print("Thanks for playing!")
break
elif self._check_win(computer):
print("\nComputer won!")
print("Thanks for playing!")
break
else:
print("\nNobody won, it's a tie.")
if __name__ == '__main__':
game = TicTacToe()
game.play()
Answer: Don't scatter magic values everywhere. Values like 'X', 'O', or ' '.
Instead, define named constants like X, O, and EMPTY.
Smarter data, simpler code. Your current _check_win() method is
repetitive and laid out with long lines are are not easy to scan visually.
# I suppose this is correct ... but I don't want to think so hard.
def _check_win(self, letter):
win_combs = [letter, letter, letter]
return self.board[:3] == win_combs or self.board[3:6] == win_combs or self.board[6:] == win_combs or \
self.board[:7:3] == win_combs or self.board[1:8:3] == win_combs or self.board[2::3] == win_combs or \
self.board[::4] == win_combs or self.board[2:7:2] == win_combs
To eliminate the repetition, define a data structure of slices -- and lay it
out nicely so that the intent and the correctness are obvious at a quick
glance.
WIN_SLICES = (
# Rows.
slice(0, 3, 1),
slice(3, 6, 1),
slice(6, 9, 1),
# Columns.
slice(0, 7, 3),
slice(1, 8, 3),
slice(2, 9, 3),
# Diagonals.
slice(0, 9, 4),
slice(2, 7, 2),
) | {
"domain": "codereview.stackexchange",
"id": 42990,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, tic-tac-toe",
"url": null
} |
python, beginner, object-oriented, tic-tac-toe
def _check_win(self, letter):
return any(
self.board[s] == [letter, letter, letter]
for s in self.WIN_SLICES
) | {
"domain": "codereview.stackexchange",
"id": 42990,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, tic-tac-toe",
"url": null
} |
python, beginner, object-oriented, tic-tac-toe
The logic in play() is unnecessarily complicated. You have some
duplicated code to handle the difference between human and computer. But that
duplication can be eliminated if you think about the problem in terms of data.
Human and computer differ in these ways: their labels ("Human" vs
"Computer"), their letters, and the methods to be called. Put that data in
some kind of structure (something as simple as a pair of tuples would work) and
then just toggle between the tuples with each iteration of the while-loop. You
could also simplify things quite a bit by changing _check_win() so that it
always checks for a win by either player and just returns the winner or None.
You have the ability to figure this out. What's missing right now is your
instinct to notice the annoying code duplication and determine to do something
about it. Thinking in terms of data is often the key to these kinds of issues.
The computer move logic has bugs. Your _computer_move() method isn't
doing what you think it's doing. It claims to be looking into the future (for
example, one comment says "Check if the player could win on their next move,
and block them"). However, the logic is confined to making calls to
_check_win() and that method does not examine the future; it examines only
the current board state. In order to make this type of forward look you would
need to temporarily fill the empty spot, then call _check_win(), and then
undo the temporary move (or not) depending on the result. To see this issue
(and a separate bug) in action, play as X, move first, and enter the following
choices: 7, 5, 6. Notice that on the next computer move ... the computer does
nothing. Not only does it fail to block, it fails to play anything at all.
Rather than going into the details, I think I'd rather leave fixing such bugs
in your hands. You are writing reasonable code and can clearly figure these
things out on your own.
A different OO vision: your TicTacToe class is doing too much, at least for | {
"domain": "codereview.stackexchange",
"id": 42990,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, tic-tac-toe",
"url": null
} |
python, beginner, object-oriented, tic-tac-toe
things out on your own.
A different OO vision: your TicTacToe class is doing too much, at least for
my tastes. While learning, it's understandable that you want to experiment
with object-oriented programming. I would encourage you to use OO in a more
fine-grained manner. Consider your current TicTacToe class. It has only two
attributes (board and spacer), and that latter is more properly understood
as a constant. In other words, your current class is masquerading as a class
that knows how to orchestrate the playing of tic-tac-toe, but in reality it's
just a vehicle to store a tic-tac-toe board. And you know what? That would be a
better design decision: a Board class that keeps track of the current board and can answer simple question about it. Pull the game orchestration out of that class and put
it somewhere else -- either in ordinary functions or in other classes. We can
catch a glimpse of why this decomposition might be better by considering
_computer_move() again. In spite of its bugs, that method is interesting
because it represents a game-playing strategy. Conceivably, you might want to
implement multiple strategies and pit them against each other in a tournament. And even if you don't want to go that far,
the human player is also a game-playing strategy: one that
gets the next move via input().
Under your current design -- where everything is combined under the umbrella of
a big class -- it's not easy to experiment with different strategy implementations. Under a more fine-grained OO approach,
your finished program might have different classes focused narrowly on specific
aspects of the problem: board state; player strategy; overall game
orchestration; and so forth. Admittedly, that's a lot to consider for
something as simple as tic-tac-toe, but if you're trying to learn how to build
more complex programs, these are the kinds of questions you want to be thinking
about. | {
"domain": "codereview.stackexchange",
"id": 42990,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, tic-tac-toe",
"url": null
} |
c#, design-patterns, asp.net, factory-method
Title: Handling resource authorization in a service
Question: Problem: My application is built upon clean architecture. I want to create a new instance of a class in my lower layer, but the class itself resides in an upper layer. The upper layer can depend on lower layer, but the lower layer can not depend on a upper one.
Why: That's because, AuthorizationService requires new instance of requirement. These requirements sit in API layer (upper). And my resource based authorization happens in services that are situated in Application layer (lower).
My solution: I created factory pattern.
EDIT: I changed name of factory to be generic.
EDIT2: I changed factory pattern to simple factory.
THIS IS SITUATED IN SERVICE / APPLICATION LAYER
var testFactory = _requirementFactory.Create("MemberOwnerOnlyRequirement");
var testListReq = new List<IAuthorizationRequirement>(){testFactory}; // Testing
var authorization = await _authorizationService.AuthorizeAsync(_currentUserService.MemberIdentity, member, //Testing
testListReq);
THESE INTERFACES ARE IN INTERFACES / APPLICATION LAYER
public interface IRequirementFactory
{
IAuthorizationRequirement Create(string requirementType);
}
THESE CONCRETE CLASSES ARE IN AUTHORIZATION / API LAYER
public class RequirementFactory : IRequirementFactory
{
public IAuthorizationRequirement Create(string requirementType)
{
switch (requirementType)
{
case "MemberOwnerOnlyRequirement":
return new MemberOwnerOnlyRequirement();
default:
return null;
}
}
}
public class MemberOwnerOnlyRequirement : IAuthorizationRequirement
{
}
I'm a beginner and I pursue clean code & best practices. My friend, who's a mid-level asp.net developer suggested bending the rule & create same class in Application layer, thus violating DRY.
Could you please suggest other approach / review mine? | {
"domain": "codereview.stackexchange",
"id": 42991,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, asp.net, factory-method",
"url": null
} |
c#, design-patterns, asp.net, factory-method
Answer: From the current context, it seems Requirment was meant for Provider, so instead of IRequirementFactory, and IAuthorizationRequirement it would be clearer if they were IProviderFactory and IAuthorizationProvider (or IProviderAuthorization).
The other note is requirementType instead of string it should be enum or Type (or better yet using Generics), so you can avoid human-mistake, and have a better type/value handling.
The RequirementFactory (or ProviderFactory) should handle the creation of the concrete class of the Requirement (or Provider) along with any required
Requirement objects or dependencies. Think of it as a basic gateway to initialize objects with their minimum requirements.
You can either have a factory for each requirement, or you can have one Factory for all requirements (as same as the provided code). both are valid approaches., and choosing between them depends totally on the code and business logic requirements.
So, as long as the Create is inside the Factory class, it should be fine, you can also market it as static method (also another common used approach) so you can do this :
RequirementFactory.Create(typeof(MemberOwnerOnlyRequirement));
if you need a different way of Create(string requirementType); you can use Generics so you could do something like this :
public IAuthorizationRequirement Create<T>() where T : class, IAuthorizationRequirement, new()
{
return new T();
}
the above code will restrict the creation to classes that implements IAuthorizationRequirement that have default constructors.
using that would be :
_requirementFactory.Create<MemberOwnerOnlyRequirement>(); | {
"domain": "codereview.stackexchange",
"id": 42991,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, asp.net, factory-method",
"url": null
} |
c#, .net, asp.net-core
Title: How to process multiple background concurrent Tasks in c#
Question: I am trying to work out the best way to go about a task which relys on multiple long running tasks taking place.
My use case is that I want to have multiple events running for set periods of time, where I have websocket connections to each event for that period.
My thoughts were that I keep a conurrent list of all active events, when a new event pops into the list, it spawns a new thread to handle the event, when the event pops off the list, this thread will be closed.
Is this a good way to go about it? I am trying to set up a proof of concept, where all I am doing is logging out the event ID to the console for now, it kind of works, but I haven't worked out a way to remove the thread yet etc.
Any advise anyone can give I would be really appreciative.
public class EventProcessingService : IHostedService, IDisposable
{
private readonly ILogger<EventProcessingService> _logger;
private readonly ICacheService _cacheService;
private const int MaxThreads = 10;
private static readonly CountdownEvent cde = new CountdownEvent(MaxThreads);
public static readonly BlockingCollection<int> eventIds = new BlockingCollection<int>();
ConcurrentBag<int> EventIdsProcessing = new ConcurrentBag<int>();
private Timer _timer = null!;
public EventProcessingService(ILogger<EventProcessingService> logger, ICacheService cacheService)
{
_logger = logger;
_cacheService = cacheService;
for (int i = 0; i < MaxThreads; i++)
{
Task.Factory.StartNew(Process, TaskCreationOptions.LongRunning);
}
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
return Task.CompletedTask;
} | {
"domain": "codereview.stackexchange",
"id": 42992,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asp.net-core",
"url": null
} |
c#, .net, asp.net-core
return Task.CompletedTask;
}
private void DoWork(object? state)
{
var ids = _cacheService.GetCachedEventIds();
foreach (var id in ids)
{
if (!EventIdsProcessing.Contains(id))
{
EventIdsProcessing.Add(id);
eventIds.Add(id);
}
}
cde.Wait();
}
private async Task Process()
{
foreach (var id in eventIds.GetConsumingEnumerable())
{
cde.Signal();
while (true)
{
Console.WriteLine(id);
await Task.Delay(1000);
}
}
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
Answer: private members
I know naming is hard and MSDN has a lots of bad examples but cde is not a really good name
Try to capture what does it limit, like
ConcurrentProcessThrottler
ConcurrentProcessLimiter
etc.
Same applies for _timer, try to capture the essence why did you introduce it
I'm not sure that you really need to use the null-forgiving / damn-it operator
Please try to follow consistent naming pattern
Inconsistent: EventIdsProcessing, _cacheService, cde, etc.
Either use underscore prefix for all your private members or do not prefix them
I know it is a POC but I would suggest to receive the maxThreads as a constructor parameter rather than using a hard-coded const
Tasks are not Threads, so a way better name would be
MaxDegreeOfParallelism
ThresholdForMaxConcurrency
etc.
public member
Please try to use Pascal Casing for public member (eventIds)
It is unclear why it should be public
EventProcessingService constructor
Try to express your intent by using the discard operator | {
"domain": "codereview.stackexchange",
"id": 42992,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asp.net-core",
"url": null
} |
c#, .net, asp.net-core
EventProcessingService constructor
Try to express your intent by using the discard operator
If you want to just fire off a new Task and you don't care about the Task itself then make this intent explicit
_ = Task.Factory.StartNew(Process, TaskCreationOptions.LongRunning);
Here the StartNew returns a Task<Task> so you need to call Unwrap to have a flattened Task
Please prefer Task.Run over StartNew since the latter one might be dangerous
Process
Using GetConsumingEnumerable works fine if the producer side calls the CompleteAdding to signal it will not produce new elements
I assume that your infinite loop simulates some real processing logic
Based on your code I don't see how will it move from the first element to the next since you have an infinite loop inside the loop body
StartAsync
I do believe you should kick off your concurrent Process workers/consumers here, not inside the constructor
With that you would be able to pass the CancellationToken to the Task.Run and to the Process as well
I would also recommend to add protection against multiple StartAsync calls
A StartAsync should have any affect only if it was not called before or if there was a completed StopAsync prior it
DoWork
It took me a couple of seconds to realize that DoWork has to match to TimerCallback delegate that's why it has a object? state parameter
Please consider to add a comment there for future maintainers or to enhance legibility
As I said several times please try to use better naming
Here your DoWork acts like a single producer, please try to capture this information inside the method name
Please bear in my that ConcurrentBag is thread-safe if you perform atomic operation
Performing Contains then Add is not atomic << not thread-safe
Please consider to use lock or use ConcurrentDictionary which does expose TryAdd
Dispose
Please try to implement the Dispose pattern as it should be | {
"domain": "codereview.stackexchange",
"id": 42992,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asp.net-core",
"url": null
} |
beginner, programming-challenge, haskell, checksum
Title: Introduction to Haskell: Validating credit card numbers
Question: I have implemented the introductory challenge of University of Pennsylvania's CIS 194: Introduction to Haskell (Spring 2013) course. I have added the most important information of the problem statement below, and the full assignment is available as a PDF on the course website.
Problem statement
It starts with a short description of the Luhn algorithm:
Validating Credit Card Numbers
[…]
In this section, you will implement the validation algorithm for credit cards. It follows these steps:
Double the value of every second digit beginning from the right. That is, the last digit is unchanged; the second-to-last digit is doubled; the third-to-last digit is unchanged; and so on. For example, [1,3,8,6] becomes [2,3,16,6].
Add the digits of the doubled values and the undoubled digits from the original number. For example, [2,3,16,6] becomes \$2+3+1+6+6 = 18\$.
Calculate the remainder when the sum is divided by \$10\$. For the above example, the remainder would be \$8\$.
If the result equals \$0\$, then the number is valid.
[…] | {
"domain": "codereview.stackexchange",
"id": 42993,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, haskell, checksum",
"url": null
} |
beginner, programming-challenge, haskell, checksum
[…]
Then, over the course of four exercises, it has you implement the following functions:
toDigits :: Integer -> [Integer] and toDigitsRev :: Integer -> [Integer]
toDigits should convert positive Integers to a list of digits. (For 0 or negative inputs, toDigits should return the empty list.) toDigitsRev should do the same, but with the digits reversed.
doubleEveryOther :: [Integer] -> [Integer]
Once we have the digits in the proper order, we need to double every other one.
Remember that doubleEveryOther should double every other number beginning from the right, that is, the second-to-last, fourth-to-last … numbers are doubled.
sumDigits :: [Integer] -> Integer
The output of doubleEveryOther has a mix of one-digit and two-digit numbers, and sumDigits calculates the sum of all digits
validate :: Integer -> Bool
Function that indicates whether an Integer could be a valid credit card number. This will use all functions defined in the previous exercises.
My code
This is my first "big" program after "Hello, World!". I've added isValid, which returns a string with the
credit card number and whether it is valid, and main, so it can be compiled. If you want, you can run it online.
import Data.Char
{- toDigits returns the digits of a number as an array.
It returns an empty list if n is zero or less. -}
toDigits :: Integer -> [Integer]
toDigits n
| n > 0 = map (\c -> toInteger $ digitToInt c) $ show n
| otherwise = []
-- toDigitsRev is like toDigits, except it reverses the array.
toDigitsRev :: Integer -> [Integer]
toDigitsRev n = reverse $ toDigits n
{- doubleAtEvenIndex is a helper function for doubleEveryOther.
It doubles a number (the second argument) if the index (the first argument)
is even. -}
doubleAtEvenIndex :: (Integer, Integer) -> Integer
doubleAtEvenIndex (index, n)
| index `mod` 2 == 0 = n * 2
| otherwise = n | {
"domain": "codereview.stackexchange",
"id": 42993,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, haskell, checksum",
"url": null
} |
beginner, programming-challenge, haskell, checksum
-- doubleEveryOther doubles every other integer in an array.
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther [] = []
doubleEveryOther v = map doubleAtEvenIndex (zip [1..] v)
-- sumDigits sums the digits in a list of integers.
sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x:xs) = sum (toDigits x) + sumDigits xs
{- validate validates the creditCardNumber using the Luhn formula:
- Double the value of every second digit beginning from the right.
- Add the digits of the doubled values and the undoubled digits from the
original number.
- Calculate the remainder when the sum is divided by 10.
- If the result equals 0, then the number is valid. -}
validate :: Integer -> Bool
validate creditCardNumber = digitSum `mod` 10 == 0
where
digitSum = sumDigits $ doubleEveryOther $ toDigitsRev creditCardNumber
{- isValid exists purely for cosmetic reasons. It returns a string with the
credit card number and whether it is valid according to the Luhn algorithm
(see `validate`). -}
isValid :: Integer -> String
isValid creditCardNumber = case validate creditCardNumber of
True -> "Credit card number " ++ show creditCardNumber ++ " is valid!"
False -> "Credit card number " ++ show creditCardNumber ++ " is invalid."
main :: IO ()
main = do
putStrLn $ isValid 4012888888881881 -- Valid
putStrLn $ isValid 4012888888881882 -- Invalid
Answer: The way you have divided the problem into subproblems seems fine, so I'll comment on the way you have solved each subproblem. | {
"domain": "codereview.stackexchange",
"id": 42993,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, haskell, checksum",
"url": null
} |
beginner, programming-challenge, haskell, checksum
toDigits: With the strategy of using show to generate a string and then convert each element in that string back to a number, you could also use read :: Read a => String -> a which takes a string (remember that String is an alias for [Char], so [c] is a string with one character in it) and parses and returns a Read a => a which in this case is Integer (inferred from the type signature).
toDigits :: Integer -> [Integer]
toDigits
| n > 0 = map (\c -> read [c]) (show n)
| otherwise = []
Even though the function becomes less robust, I might still move the error handling of non-positive numbers out of it and handle errors earlier in the chain of function calls. This might look like:
toDigits :: Integer -> [Integer]
toDigits n = map (\c -> read [c]) (show n)
A fancy name for the function \c -> [c] is return. Doing a few transformations this function could look like:
toDigits n = map (\c -> read [c]) (show n)
toDigits n = map (\c -> read (return c)) (show n)
toDigits n = map (\c -> (read . return) c) (show n)
toDigits n = map (read . return) (show n)
toDigits = map (read . return) . show
with a final result of:
toDigits :: Integer -> [Integer]
toDigits = map (read . return) . show
Another strategy is to recursively remove the last digit from n using integer modulo / division. This has the peculiar side-effect that you'll generate the list backwards (because you start by adding the least significant digit). But since this is what you wanted after all, you're just saving a reverse here:
toDigitsRev :: Integer -> [Integer]
toDigitsRev n
| n <= 0 = []
| otherwise = (n `rem` 10) : toDigits' (n `quot` 10) | {
"domain": "codereview.stackexchange",
"id": 42993,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, haskell, checksum",
"url": null
} |
beginner, programming-challenge, haskell, checksum
Here, rem is remainder and quot is integer division. There's mod and div, but they only differ for negative integers. I like this solution better because converting something to String and then back seems a bit screwy. Still, it's very readable.
Another thing you could do here is to remove explicit recursion by using a higher-order function. In this case it might be unfoldr :: (b -> Maybe (a, b)) -> b -> [a] which produces a list of values (the digits) by feeding an input (n) to a function again and again with one digit less each time.
import Data.List (unfoldr)
import Data.Tuple (swap)
toDigitsRev :: Integer -> [Integer]
toDigitsRev n = unfoldr next n
where
next 0 = Nothing
next n = Just (swap (n `divMod` 10))
For example, 12345 `divMod` 10 produces both the division and the remainder, (1234, 5). Unfortunately, unfoldr expects the digit to be in the first part (with type a) and the next n to be in the second part (with type b), so we swap the result into (5, 1234). A final improvement we can do here is to eta-reduce the outer n and use quotRem instead of divMod:
toDigitsRev :: Integer -> [Integer]
toDigitsRev = unfoldr next
where
next 0 = Nothing
next n = Just (swap (n `quotRem` 10))
doubleEveryOther: It's very good to see that you employ both map and zip here, but since you also need to write a manually recursive helper function, doubleAtEvenIndex, the effort seems a bit lost. Here's how I'd do it using explicit recursion only:
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther (x:y:xs) = x : y*2 : doubleEveryOther xs
doubleEveryOther xs = xs | {
"domain": "codereview.stackexchange",
"id": 42993,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, haskell, checksum",
"url": null
} |
beginner, programming-challenge, haskell, checksum
With pattern matching you can match arbitrarily deep into a data type, so for lists, you can match lists with at least two elements. The fallback pattern xs matches both lists of one and zero elements.
How might a higher-order solution look like? You're already using zip and map, but rather than zipping the indices [1..] you could also zip the factors [1,2,1,2,...]:
> zip [1,2,3,4,5] [1,2,1,2,1]
[(1,1),(2,2),(3,1),(4,2),(5,1)]
and then map (\(x,y) -> x * y) the result:
> map (\(x,y) -> x * y) (zip [1,2,3,4,5] [1,2,1,2,1])
[(1 * 1),(2 * 2),(3 * 1),(4 * 2),(5 * 1)]
= [1,4,3,8,5]
You can also write that as map (uncurry (*)), but something even neater is to use zipWith (*) which is a combination of map and zip where you save the intermediate tuple representation: You just take one element of each list and combine them using (*) to produce the zipped-with element.
Finally, if you cycle [1,2] you get an infinite list of [1,2,...] which zipWith will shorten to the point that it matches the length of the digits:
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther digits = zipWith (*) digits (cycle [1,2])
If we wanted to eta-reduce digits, we'd have a bit of a problem since it's not the last argument to zipWith. Fortunately we're zipping with a commutative operator, so we might as well write
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther digits = zipWith (*) (cycle [1,2]) digits
which is equivalent to
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther = zipWith (*) (cycle [1,2])
sumDigits: Excellent. The only thing I can think of improving here is to remove explicit recursion. What we're doing here is to sum the digits of each integer in the list and then sum the result of that. You already found sum and map, so combining those:
sumDigits :: [Integer] -> Integer
sumDigits ns = sum (map (\n -> sum (toDigits n)) ns) | {
"domain": "codereview.stackexchange",
"id": 42993,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, haskell, checksum",
"url": null
} |
beginner, programming-challenge, haskell, checksum
which can be eta-reduced as:
sumDigits ns = sum (map (\n -> sum (toDigits n)) ns)
sumDigits ns = sum (map (\n -> (sum . toDigits) n) ns)
sumDigits ns = sum (map (sum . toDigits) ns)
sumDigits ns = (sum . map (sum . toDigits)) ns
sumDigits = sum . map (sum . toDigits)
giving
sumDigits :: [Integer] -> Integer
sumDigits = sum . map (sum . toDigits)
validate: Excellent. The only thing I can think of improving here is to remove the where:
validate :: Integer -> Bool
validate creditCardNumber =
sumDigits (doubleEveryOther (toDigitsRev creditCardNumber)) `mod` 10 == 0
You could eta-reduce this, too, but I don't think it looks any better:
validate :: Integer -> Bool
validate =
(== 0) . (`mod` 10) . sumDigits . doubleEveryOther . toDigitsRev
At this point your solution would look like:
toDigits :: Integer -> [Integer]
toDigits = map (read . return) . show
toDigitsRev :: Integer -> [Integer]
toDigitsRev = unfoldr next
where
next 0 = Nothing
next n = Just (swap (n `quotRem` 10))
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther = zipWith (*) (cycle [1,2])
sumDigits :: [Integer] -> Integer
sumDigits = sum . map (sum . toDigits)
validate :: Integer -> Bool
validate creditCardNumber =
sumDigits (doubleEveryOther (toDigitsRev creditCardNumber)) `mod` 10 == 0
The error handling that was removed from toDigits could be inserted back into validate, for which the name indicates that it actually does validation, and it could be extended to check that the input is not just a positive number but also has the exact amount of digits that a credit card has.
I hope this feedback was useful and not too low-level. | {
"domain": "codereview.stackexchange",
"id": 42993,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, programming-challenge, haskell, checksum",
"url": null
} |
python, performance, algorithm
Title: Optimizing Code for Spectral Gradient algorithm in Python
Question: I am building an algorithm to run proximal spectral gradient for research purposes. The code is almost in its finalized step, but the runtime of the code is slow. I hope to seek your professional review to improve my code efficiency.
Below is the code for my algorithm:
from numpy import ones_like,array,diag,trace,identity,negative,random,cov,mean
from math import sqrt
from numpy.linalg import norm, inv
from numba import njit,jit
@njit(fastmath={'nsz'})
def project_f(v, mu, covar, lam_k, beta_1, theta, beta_2, gam):
func = 0.5*beta_1*v.T@covar@v - theta*mu.T@v + gam/2*(v.sum()-1.)**2 + lam_k * (
v.sum()-1.) + beta_2/2*v@v
return func
@njit(fastmath={'nsz'})
def project_df(v, mu, covar, lam_k, beta_1, theta, beta_2, gam):
par_func = beta_1*covar@v - theta*mu + gam*ones_like(v)*(v.sum()-1.) + lam_k*ones_like(v) + beta_2*v
return par_func
@njit(fastmath={'nsz'})
def aug_lag(lam, gam, v):
lam += gam*(v.sum()-1.)
return lam
@njit(fastmath={'nsz'})
def lipschitz(beta_1,beta_2,gam,v,covar):
lips = beta_1*sqrt(trace(covar@covar)) + beta_2*sqrt(len(v)) + gam*len(v)
return min(1.,1./lips)
@njit(fastmath={'nsz'})
def spectral_grad(v,v_1,g,g_1,prev_B):
s = v_1 - v
y = g_1 - g
if s.T@s > s.T@y:
s1 = s**4
s2 = s**2
w_k = ((s.T@s) - (s.T@y)) / s1.sum()
B_k = array([1./(1.+ w_k*i) for i in s2])
return diag(B_k)
return prev_B
#return np.identity(len(s)) #rescaling
@njit(fastmath={'nsz'})
def proximal(vec,sparsity,b1,b2,gam,covar,grad):
L = lipschitz(b1,b2,gam,vec,covar)
parameter = (2*sparsity/(L+1/L))**0.5
v = []
for i,j in zip(vec,grad):
if abs(i) < parameter:
v.append(0)
else:
new_v = i - j/(L+1/L)
v.append(new_v)
return array(v)
@njit(fastmath={'nsz'})
def return_and_risk(vec,mu,covar):
return vec@mu,vec@covar@vec | {
"domain": "codereview.stackexchange",
"id": 42994,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm",
"url": null
} |
python, performance, algorithm
@njit(fastmath={'nsz'})
def return_and_risk(vec,mu,covar):
return vec@mu,vec@covar@vec
@njit(fastmath=True)
def negative_count(vec):
result = 0
for i in vec:
if i < 0:
result += 1
return result
@njit(fastmath=True)
def zero_count(vec):
result = 0
for i in vec:
if i == 0:
result += 1
return result
@jit(forceobj=True)
def spectral_gradient1(df,v,covar,mu,b1,thet,b2,gam,tol,lam,spars,MAX_ITER=2000):
vec = v
B = identity(len(vec))
aug_lam = lam
vec_sum, grad = [],[]
alpha = lipschitz(b1, b2, gam, vec, covar)
for i in range(MAX_ITER):
gradient = df(vec,mu,covar,aug_lam,b1,thet,b2,gam)
direction = negative(inv(B) @ gradient)
profit, std_dev = return_and_risk(vec,mu,covar)
vec_1 = vec + alpha * direction
gradient_1 = df(vec_1,mu,covar,aug_lam,b1,thet,b2,gam)
B = spectral_grad(vec,vec_1,gradient,gradient_1,B)
aug_lam = aug_lag(aug_lam, gam, vec_1)
vec = proximal(vec_1,spars,b1,b2,gam,covar,gradient_1)
vec_sum.append(vec.sum())
grad.append(norm(gradient,2))
# stopping criteria
if norm(gradient,2) <= tol:
#print("The optimum vector for", {df}, " is at ", vec,"at iteration ", i+1)
#negat = negative_count(vec)
#print("No of negative: ", negat)
#zero = zero_count(vec)
#print("No. of zeros: ", zero)
#print("Vector sum: ",sum(vec))
#print("Gradient: ", norm(gradient,2))
break
if i == MAX_ITER-1:
#print('Higher no. of iterations is needed')
#print("Vector: ", vec)
#negat = negative_count(vec)
#print("No of negative: ",negat)
#zero = zero_count(vec)
#print("No. of zeros: ", zero)
#print("Vector sum: ",sum(vec))
#print("Gradient: ", norm(gradient,2))
break | {
"domain": "codereview.stackexchange",
"id": 42994,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm",
"url": null
} |
python, performance, algorithm
return vec, array(vec_sum), array(grad), i+1, profit, std_dev
tol, spars, ini_lam = 1.e-4, 1.e-3, 1000
beta_1,theta,beta_2,gam = 1.,.5,1.,1.
sim_data = -1+2*random.rand(1000,5)
sim_mean = mean(sim_data,axis=0)
sim_covar = cov(sim_data,rowvar=False)
v = array([1. / (len(sim_mean)) for i in range(len(sim_mean))])
vec2000,vsum,grad,_,_,_ =spectral_gradient1(project_df,v,sim_covar,sim_mean,beta_1,theta,beta_2,gam,tol,ini_lam,spars)
I have run the code once to check on its speed and it definitely needs to be optimized more
%timeit spectral_gradient1(project_df,v,sim_covar,sim_mean,beta_1,theta,beta_2,gam,tol,ini_lam,spars)
3.15 ms ± 1.09 ms per loop (mean ± std. dev. of 7 runs, 100 loops each) | {
"domain": "codereview.stackexchange",
"id": 42994,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm",
"url": null
} |
python, performance, algorithm
Answer: Descoping-import from numpy is unconventional, and you should instead do the conventional import numpy as np.
Don't from math import when sqrt exists in numpy. Also, don't **0.5; use sqrt.
Add PEP484 type hints. These are important for self-documentation and do not impact performance.
gam is not a useful abbreviation of gamma; likewise for lam etc. Since lambda is a Python keyword the typical strategy is to write an underscore suffix.
Cache repeated calculations such as s.T@s and norm() into local variables.
In proximal, replace your for loop with a vectorised assignment.
Step 0 in performance analysis is to profile, and this is a one-line invocation of cProfile.run that immediately illustrates the problem: the overwhelming cost is the repeated call to linalg.inv(). So the problem is algorithmic and not in implementation; the algorithm needs to be examined critically. To this end: it looks like B remains the identity matrix throughout your calculation, which means that direction, rather than negative(inv(B) @ gradient), is numerically equivalent to -gradient. Of course this is much faster, but I cannot say whether this betrays a fault in your implementation.
Don't add your test parameters in the global namespace. Wrap these in a main.
Your use of rand is deprecated and you should be using default_rng instead.
Add at least bare-minimum numerical regression tests.
Remove your unused functions: project_f, negative_count and zero_count.
You need to move several repeated calculations to pre-calculated constants higher up in the call chain. For instance, theta * mean is constant, and the beta1*covariance calculation is also constant.
trace(covar@covar) is inefficient and is better-expressed as np.tensordot(cov, cov).
Suggested
import cProfile
from typing import Protocol
import numpy as np | {
"domain": "codereview.stackexchange",
"id": 42994,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm",
"url": null
} |
python, performance, algorithm
import numpy as np
class ProjectFun(Protocol):
def __call__(
self,
v: np.ndarray, theta_mean: np.ndarray, cov: np.ndarray,
lambda_k: float, beta_1: float, beta_2: float, gamma: float,
) -> np.ndarray:
...
def project_df(
v: np.ndarray, # varies
theta_mean: np.ndarray, cov: np.ndarray,
lambda_k: float, # varies
beta_1: float, beta_2: float, gamma: float,
) -> np.ndarray:
return (
beta_1 * cov @ v
+ beta_2 * v
+ (gamma * (v.sum() - 1) + lambda_k)
- theta_mean
)
def lipschitz(
beta_1_cov: np.ndarray, beta_2: float, gamma: float,
v: np.ndarray, # varies
) -> float:
lips = (
beta_1_cov # beta_1 * np.sqrt(np.tensordot(cov, cov))
+ beta_2 * np.sqrt(len(v))
+ gamma * len(v)
)
return min(1., 1/lips)
def spectral_grad(
v: np.ndarray, v_1: np.ndarray,
g: np.ndarray, g_1: np.ndarray, prev_B: np.ndarray,
) -> np.ndarray:
s = v_1 - v
y = g_1 - g
sT_y = s.T@y
sT_s = s.T@s
if sT_s <= sT_y:
return prev_B
s1 = s**4
s2 = s**2
w_k = (sT_s - sT_y) / s1.sum()
B_k = 1/(1 + w_k*s2)
return np.diag(B_k)
def proximal(
vec: np.ndarray, # varies
sparsity: float,
beta_1_cov: np.ndarray, beta2: float, gamma: float,
grad: np.ndarray, # varies
) -> np.ndarray:
L = lipschitz(beta_1_cov, beta2, gamma, vec)
parameter = np.sqrt(2*sparsity/(L + 1/L))
v = vec - grad/(L + 1/L)
v[np.abs(vec) < parameter] = 0
return v
def aug_lag(lambda_: float, gamma: float, v: np.ndarray) -> float:
return lambda_ + gamma * (v.sum() - 1)
def return_and_risk(vec: np.ndarray, mean: np.ndarray, cov: np.ndarray) -> tuple[
float, # profit
float, # standard deviation
]:
return vec@mean, vec@cov@vec | {
"domain": "codereview.stackexchange",
"id": 42994,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm",
"url": null
} |
python, performance, algorithm
def spectral_gradient(
df: ProjectFun,
v: np.ndarray,
cov: np.ndarray,
mean: np.ndarray,
beta1: float,
theta: float,
beta2: float,
gamma: float,
tol: float,
lambda_: float,
sparsity: float,
MAX_ITER: int = 2000,
) -> tuple[
np.ndarray, # some mystery vector
np.ndarray, # some mystery vector sum
np.ndarray, # gradient
int, # iterations
float, # profit
float, # standard deviation
]:
vec = v
B = np.identity(len(vec))
aug_lambda = lambda_
vec_sum, grad = [], []
beta_1_cov = beta1 * np.sqrt(np.tensordot(cov, cov))
alpha = lipschitz(beta_1_cov, beta2, gamma, vec)
theta_mean = theta * mean
for i in range(MAX_ITER):
gradient = df(vec, theta_mean, cov, aug_lambda, beta1, beta2, gamma)
direction = -gradient # -(np.linalg.inv(B) @ gradient) ??? B is always the identity
profit, std_dev = return_and_risk(vec, mean, cov)
vec_1 = vec + alpha*direction
gradient_1 = df(vec_1, theta_mean, cov, aug_lambda, beta1, beta2, gamma)
B = spectral_grad(vec, vec_1, gradient, gradient_1, B)
aug_lambda = aug_lag(aug_lambda, gamma, vec)
vec = proximal(vec_1, sparsity, beta_1_cov, beta2, gamma, gradient_1)
vec_sum.append(vec.sum())
norm = np.linalg.norm(gradient, 2)
grad.append(norm)
# stopping criteria
if norm <= tol:
break
return vec, np.array(vec_sum), np.array(grad), i+1, profit, std_dev
def main() -> None:
rand = np.random.default_rng(seed=0)
sim_data = -1 + 2*rand.random((1000, 100))
sim_mean = np.mean(sim_data, axis=0)
sim_covar = np.cov(sim_data, rowvar=False)
v = np.full_like(sim_mean, 1 / (len(sim_mean))) | {
"domain": "codereview.stackexchange",
"id": 42994,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm",
"url": null
} |
python, performance, algorithm
vec, vec_sum, grad, iters, profit, std_dev = spectral_gradient(
df=project_df,
v=v,
cov=sim_covar,
mean=sim_mean,
beta1=1,
theta=0.5,
beta2=1,
gamma=1,
tol=1e-4,
lambda_=1000,
sparsity=1e-3,
)
def isclose(expected: float, actual: float) -> None:
assert np.isclose(expected, actual, rtol=0, atol=1e-12)
assert vec.shape == (100,)
isclose(-0.007010796055097749, vec[0])
isclose(-0.004207865733542051, vec.mean())
assert vec_sum.shape == (2000,)
isclose(-974.5320405384236, vec_sum[0])
isclose(0.4996461919685679, vec_sum.mean())
assert grad.shape == (2000,)
isclose(10000.137462968969, grad[0])
isclose(574.544628745777, grad.mean())
assert iters == 2000
isclose(0.0087850136941670460, profit)
isclose(0.0016628777135266198, std_dev)
if __name__ == '__main__':
cProfile.run('main()', sort='tottime')
Output
72558 function calls (70525 primitive calls) in 0.491 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
4000 0.267 0.000 0.285 0.000 274298.py:16(project_df)
2000 0.111 0.000 0.111 0.000 274298.py:77(return_and_risk)
8023 0.021 0.000 0.021 0.000 {method 'reduce' of 'numpy.ufunc' objects}
1 0.021 0.021 0.488 0.488 274298.py:84(spectral_gradient)
... | {
"domain": "codereview.stackexchange",
"id": 42994,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm",
"url": null
} |
java
Title: Is this the way of truncating the fractional part of a BigDecimal when its scale is zero in Java?
Question: I need to remove the fractional part of a BigDecimal value when its scale has a value of zero. For example,
BigDecimal value = new BigDecimal("12.00").setScale(2, RoundingMode.HALF_UP);
It would assign 12.00. I want it to assign only 12 to value in such cases.
BigDecimal value = new BigDecimal("12.000000").setScale(2, RoundingMode.HALF_UP);
should assign 12,
BigDecimal value = new BigDecimal("12.0001").setScale(2, RoundingMode.HALF_UP);
should assign 12.
BigDecimal value = new BigDecimal("12.0051").setScale(2, RoundingMode.HALF_UP);
should assign12.01
BigDecimal value = new BigDecimal("12.99").setScale(2, RoundingMode.HALF_UP);
should assign 12.99.
BigDecimal value = new BigDecimal("12.999").setScale(2, RoundingMode.HALF_UP);
should assign13
BigDecimal value = new BigDecimal("12.3456").setScale(2, RoundingMode.HALF_UP);
should assign 12.35 and alike.
I have this question on StackOverflow.
For this to be so, I'm doing the following.
String text="123.008";
BigDecimal bigDecimal=new BigDecimal(text);
if(bigDecimal.scale()>2)
{
bigDecimal=new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
}
if(bigDecimal.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO)==0)
{
bigDecimal=new BigDecimal(text).setScale(0, BigDecimal.ROUND_HALF_UP);
}
System.out.println("bigDecimal = "+bigDecimal);
It's just as an example. Is there a better way to do this?
Answer:
Is there a better way to do this?
Yes, stripTrailingZeros().
To check your tests:
public static void main(final String[] args) {
check(truncate("12.000000"), "12");
check(truncate("12.0001"), "12");
check(truncate("12.0051"), "12.01");
check(truncate("12.99"), "12.99");
check(truncate("12.999"), "13");
check(truncate("12.3456"), "12.35");
System.out.println("if we see this message without exceptions, everything is ok");
} | {
"domain": "codereview.stackexchange",
"id": 42995,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
private static BigDecimal truncate(final String text) {
BigDecimal bigDecimal = new BigDecimal(text);
if (bigDecimal.scale() > 2)
bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
return bigDecimal.stripTrailingZeros();
}
private static void check(final BigDecimal bigDecimal, final String string) {
if (!bigDecimal.toString().equals(string))
throw new IllegalStateException("not equal: " + bigDecimal + " and " + string);
}
output:
if we see this message without exceptions, everything is ok | {
"domain": "codereview.stackexchange",
"id": 42995,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
php, array, wordpress
Title: Modify a WordPress loop to show posts of certain categories, based on user roles
Question: I've got some code that works as intended, but I have a feeling that it's messy. This code is modifying a wordpress loop and the goal is to check the roles of the current user and show posts of certain categories, based on the user roles.
My working code:
/** Check if the current user is a Student, and if they are, run the custom loop. */
$current_user = wp_get_current_user();
$roles = $current_user->roles;
if ($roles[0] == 'student'){
/** Replace the standard loop with our custom loop */
remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'custom_student_loop' );
function custom_student_loop() {
$grades = array(); //Set up an empty array for the grades. We're gonna add grade categories as necessary based on user roles. | {
"domain": "codereview.stackexchange",
"id": 42996,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, array, wordpress",
"url": null
} |
php, array, wordpress
/** Check the roles of the current user, and add grade categories to the Grades array as needed */
$user = wp_get_current_user();
if ( in_array( 'grade_1_student', (array) $user->roles ) ) {
$grades[] = ('grade-1');
}
if ( in_array( 'grade_2_student', (array) $user->roles ) ) {
$grades[] = ('grade-2');
}
if ( in_array( 'grade_3_student', (array) $user->roles ) ) {
$grades[] = ('grade-3');
}
if ( in_array( 'grade_4_student', (array) $user->roles ) ) {
$grades[] = ('grade-4');
}
if ( in_array( 'grade_5_student', (array) $user->roles ) ) {
$grades[] = ('grade-5');
}
if ( in_array( 'grade_6_student', (array) $user->roles ) ) {
$grades[] = ('grade-6');
}
if ( in_array( 'grade_7_student', (array) $user->roles ) ) {
$grades[] = ('grade-7');
}
if ( in_array( 'grade_8_student', (array) $user->roles ) ) {
$grades[] = ('grade-8');
}
if ( in_array( 'grade_9_student', (array) $user->roles ) ) {
$grades[] = ('grade-9');
}
global $paged; // current paginated page
global $query_args; // grab the current wp_query() args
$args = array(
'paged' => $paged, // respect pagination
'tax_query' => array(
array(
'taxonomy' => 'homework-grades',
'field' => 'slug',
'terms' => $grades,
),
),
);
genesis_custom_loop( wp_parse_args($query_args, $args) );
}
} | {
"domain": "codereview.stackexchange",
"id": 42996,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, array, wordpress",
"url": null
} |
php, array, wordpress
}
Like I said, I'm sure there's a cleaner/better way to do this but I have not been able to find any examples to follow, and I've searched everything I can think of that would apply to this, but I don't know where else to look. If anyone can give me suggestions or point me in the right direction, that would be very much appreciated.
Answer: Optimizations
I recommend separating the logic from the functionality, as well as using a generalized filter instead of explicit conditionals.
You should avoid declaring functions, classes, and methods in conditional statements. If they are unused they are ignored. The exception would be when using if (!function_exists('foo')) { function foo() { } }, etc.
Use strict-type comparison operators to avoid false positives. Such as 'student' == 0 is true in PHP <= 7.4Example: https://3v4l.org/qEKNV
I also believe checking $roles[0] is equal to student may lead to unexpected results, in the event that the values have been reordered. You may want to utilize a different comparison, such as in_array('student', $roles, true) to ensure the condition is met when desired.
- I excluded this optimization from the examples below in favor of using strict-type comparison operators.
The inversion of the comparison operators is called Yoda conditions which is intended to avoid accidental assignment of a variable and has become a programming standard in Wordpress and Symfony frameworks.
function custom_student_loop() {
$user = wp_get_current_user();
//separated logic from functionality - see below for two different methods
$grades = getStudentGradesFromRoles((array) $user->roles); | {
"domain": "codereview.stackexchange",
"id": 42996,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, array, wordpress",
"url": null
} |
php, array, wordpress
global $paged; // current paginated page
global $query_args; // grab the current wp_query() args
$args = array(
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'homework-grades',
'field' => 'slug',
'terms' => $grades,
),
),
);
genesis_custom_loop( wp_parse_args($query_args, $args) );
}
$current_user = wp_get_current_user();
$roles = $current_user->roles;
//Yoda condition and strict-type matching
if ('student' === $roles[0]) {
/** Replace the standard loop with our custom loop */
remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'custom_student_loop' );
}
Regular Expression Filter Method https://3v4l.org/JKpi5
This approach uses a preg_filter regular expression to determine if the string pattern matches and removes those that do not.
Extracting the values within the parentheses () known as capture groups, to return the prefix text of grade and the number \d, separated by a -.
Simplified from array_filter+preg_match+str_replace - credit to mickmackusa for pointing this out.
function getStudentGradesFromRoles(array $roles) {
return array_values(preg_filter('/^(grade)_(\d)_student$/', '$1-$2', $roles));
} | {
"domain": "codereview.stackexchange",
"id": 42996,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, array, wordpress",
"url": null
} |
php, array, wordpress
Indexed Method https://3v4l.org/IODVN
This approach uses an indexed array as a definition list, to intersect on the keys and extract the matching values.
The use of the static keyword allows PHP to retain the initial declaration within the scope of the function.
function getStudentGradesFromRoles(array $roles) {
static $grades = [
'grade_1_student' => 'grade-1',
'grade_2_student' => 'grade-2',
'grade_3_student' => 'grade-3',
'grade_4_student' => 'grade-4',
'grade_5_student' => 'grade-5',
'grade_6_student' => 'grade-6',
'grade_7_student' => 'grade-7',
'grade_8_student' => 'grade-8',
'grade_9_student' => 'grade-9',
];
return array_values(array_intersect_key($grades, array_flip($roles)));
} | {
"domain": "codereview.stackexchange",
"id": 42996,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, array, wordpress",
"url": null
} |
javascript, programming-challenge, binary-search-tree
Title: Maximum Depth of Binary Tree in JavaScript
Question: The task
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest
path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 3
3
/ \
/ \
9 20
/ \
15 7
Example 2:
Input: root = [1,null,2] Output: 2
My solution:
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const maxDepth = (root) => {
if (root === null) {
return 0;
}
return iterateTree(root, 1);
};
const iterateTree = (root, level) => {
const isLeftTreeMissing = root.left === null;
const isRightTreeMissing = root.right === null
let leftLevel = level;
let rightLevel = level;
if (isLeftTreeMissing === false) {
leftLevel = iterateTree(root.left, level + 1);
}
if (isRightTreeMissing === false) {
rightLevel = iterateTree(root.right, level + 1);
}
return leftLevel > rightLevel ? leftLevel : rightLevel;
};
Answer: A few minor style suggestions for starters:
Use const instead of let. let says "I'm going to reassign this variable later" but then you never do, so const is safer and communicates your intent best.
if (isLeftTreeMissing === false) { is clearer as if (!isLeftTreeMissing) {.
I'm generally not crazy about the pattern of creating intermediate variables for conditions:
const isSomethingNull = something === null;
if (isSomethingNull) { ... }
I'd just inline the condition since it's so small (if it wasn't, I'd write a function):
if (something === null) { ... } | {
"domain": "codereview.stackexchange",
"id": 42997,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, programming-challenge, binary-search-tree",
"url": null
} |
javascript, programming-challenge, binary-search-tree
which pretty much reads like English, is easier to understand than the extra layer of indirection and eliminates the potential for a bug to creep in if something unexpected happens to that variable between the assignment and the conditional test. Good to see you're using === though!
If you're testing whether objects exist and the contract for the function is that the parameter is either an object or null, I'd use if (!something) {.
The bigger issue is the presence of two really common antipatterns in recursion -- I'd call these almost universal "beginner recursion" mistakes (but don't take that the wrong way; I've made these mistakes too and still do!).
The first is the tendency to make decisions about root.left and root.right from the parent frame. In general, it adds complexity, isn't necessary and disrupts the magical part of recursion: after you code up the logic for your frame's data, let the children apply the same pattern and hand you their results. Don't dip into and mess with the children's data unless you must. If you find you have to, then you may have formulated the problem incorrectly or recursion may not the correct pattern to apply to the problem.
Better is to let the child calls handle the parent's root.left? as root? itself, after the call to maxDepth(root.left). This simplifies the code quite dramatically and is more natural:
const maxDepth = root => root
? 1 + Math.max(maxDepth(root.left), maxDepth(root.right))
: 0
;
/*
3
/ \
/ \
9 20
/ \
15 7
*/
const tree = {
val: 3,
left: {val: 9},
right: {
val: 20,
left: {val: 15},
right: {val: 7},
},
};
console.log(maxDepth(tree)); | {
"domain": "codereview.stackexchange",
"id": 42997,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, programming-challenge, binary-search-tree",
"url": null
} |
javascript, programming-challenge, binary-search-tree
This code should reveal the second common/universal recursion mistake I see: overcomplicating return values and parameters. Generally speaking, any given piece of data flows one way: results flow back up the tree and state flows down.
If you're passing the same data representing the results down and then back up again without really operating on it, as is the case in your code, oftentimes the downward-flowing data is pointless. You can see I've done away with the unnecessary parameter in favor of the following recursive logic:
If I'm a call frame with an empty node, the depth is 0 so return 0
Otherwise, return 1 for my node plus the larger of whatever values my children have.
That's it!
By the way, adding the result as a parameter isn't just an issue of reducing verbosity (although that's reason enough for me) -- you can actually wreck your memoization attempt with it on dynamic programming problems, so it's quite critical to be clear about what the dependencies are in the DAG of problems you're solving. If it's not a dependency (i.e. it's a result, or irrelevant information), then it has to be taken out of the memoization table.
Here's a concrete example of this over on Stack Overflow: Issue with memoization - House Robber problem. If you haven't done DP yet, no problem -- the point is that adding complexity is usually worse than an aesthetics issue.
So, to summarize how to avoid these recursive antipatterns:
Try not to touch child properties anywhere except to set up your recursive calls
Generally don't use parameters as return values
If the solution seems over-complicated, it probably is. | {
"domain": "codereview.stackexchange",
"id": 42997,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, programming-challenge, binary-search-tree",
"url": null
} |
go, stream
Title: Chunk output into files, based on number of entries and total size
Question: Below is my client code which stream all the customer URLs from a golang grpc server. It takes Request input parameter and streams customer URLs based on matching a particular clientId. In my this code, I am streaming all customer URLs for ClientId 12345 and it works fine.
I am also creating an XML file with all the URLs in it for particular clientId as shown below. I need to split an XML file into multiple XML files for same clientId to ensure it conforms to these requirements:
A single XML file should not be more than 50MB max. It can be approximate, doesn't have to be accurate.
A single XML file should not have more than 50K URLs max.
I know it's weird that 50k URL limit will be reached sooner than 50MB limit but this is the requirement I have. Based on above logic, I need to make multiple XML files for particular clientId. All those multiple files can be like 12345_abc_1.xml, 12345_abc_2.xml or any other better naming format.
Below is the code I got which works fine but I am opting for code review to see if anything can be improved or optimized so that it can be run efficiently.
func main() {
// this "clientId" will be configurable in future
clientId := 12345
timeout := time.Duration(1000) * time.Millisecond
ctx, _ := context.WithTimeout(context.Background(), timeout)
conn, err := grpc.DialContext(ctx, "localhost:50005", grpc.WithInsecure())
if err != nil {
log.Fatalf("can not connect with server %v", err)
} | {
"domain": "codereview.stackexchange",
"id": 42998,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, stream",
"url": null
} |
go, stream
// create stream
client := pb.NewCustomerServiceClient(conn)
req := &pb.Request{ClientId: clientId}
stream, err := client.FetchResponse(context.Background(), req)
if err != nil {
log.Fatalf("open stream error %v", err)
}
// create new object to populate all URL data in memory
urlHolder := NewClient()
t := time.Unix(0, 0).UTC()
done := make(chan bool)
go func() {
// create new object to populate all URL data in memory
urlHolder := NewClient()
urlCounter := 0
byteCounter := 0
fileCounter := 0
for {
resp, err := stream.Recv()
if err == io.EOF {
done <- true
file, _ := os.Create(fmt.Sprintf("%d_abc_%d.xml", clientId, fileCounter))
urlHolder.WriteTo(file)
return
}
if err != nil {
log.Fatalf("can not receive %v", err)
}
log.Printf("Resp received: %s", resp.GetCustomerUrl())
// I add the bytes of the URL here as a return
urlBytes := urlHolder.Add(&URL{
Loc: resp.GetCustomerUrl(),
LastMod: &t,
ChangeFreq: Daily,
Priority: 10.2,
})
byteCounter += urlBytes
urlCounter += 1
if byteCounter > 49000000 || urlCounter >= 50000 {
file, _ := os.Create(fmt.Sprintf("%d_abc_%d.xml", clientId, fileCounter))
urlHolder.WriteTo(file)
urlHolder = NewClient() // create a new object for next loop
fileCounter += 1 // prepare fileCounter for next loop
byteCounter = 0 // restart count variables
urlCounter = 0
}
}
}()
<-done
log.Printf("finished")
} | {
"domain": "codereview.stackexchange",
"id": 42998,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, stream",
"url": null
} |
go, stream
<-done
log.Printf("finished")
}
Here is my urlholder.go file:
type URL struct {
Loc string `xml:"loc"`
LastMod *time.Time `xml:"lastmod"`
ChangeFreq ChangeFreq `xml:"changefreq"`
Priority float32 `xml:"priority"`
}
type UrlMap struct {
XMLName xml.Name `xml:"urlset"`
Xmlns string `xml:"xmlns,attr"`
URLs []*URL `xml:"url"`
Minify bool `xml:"-"`
}
func NewClient() *UrlMap {
return &UrlMap{
Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9",
URLs: make([]*URL, 0),
}
}
func (s *UrlMap) Add(u *URL) (int) {
s.URLs = append(s.URLs, u)
var urlBytes []byte
var err error
urlBytes, err = xml.Marshal(u) // Transform to bytes using xml.Marshal or xml.MarshalIndent
if err != nil {
panic(err) // or return the error
}
return len(urlBytes)
}
// WriteTo writes XML encoded urlMap to given io.Writer.
func (s *UrlMap) WriteTo(w io.Writer) (n int64, err error) {
cw := NewCounterWriter(w)
_, err = cw.Write([]byte(xml.Header))
if err != nil {
return cw.Count(), err
}
en := xml.NewEncoder(cw)
if !s.Minify {
en.Indent("", " ")
}
err = en.Encode(s)
cw.Write([]byte{'\n'})
return cw.Count(), err
}
Here is my CounterWriter class -
type CounterWriter struct {
writer io.Writer
count int64
}
var _ io.Writer = (*CounterWriter)(nil)
func NewCounterWriter(w io.Writer) (cw *CounterWriter) {
return &CounterWriter{
writer: w,
}
}
func (cw *CounterWriter) Write(p []byte) (n int, err error) {
n, err = cw.writer.Write(p)
cw.count = cw.count + int64(n)
return n, err
}
// Count returns the number of bytes written to the Writer.
func (cw *CounterWriter) Count() (n int64) {
return cw.count
}
Problem Statement
I am looking for code review on above code: | {
"domain": "codereview.stackexchange",
"id": 42998,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, stream",
"url": null
} |
go, stream
Problem Statement
I am looking for code review on above code:
Is there anything that can be improved in terms of multiple XML file generation logic? I modified my Add method in urlholder.go file to return bytes (which is int) but I also have WriteTo method in same go file which also returns bytes (which is int64). Can we simplify my above multiple XML file generation logic?
Also do we need to use interface to split out above class and make it more clean?
I am just trying to learn on how to write good go code as this code will be running in production.
Answer: Your code is very clear and readable in general. I came up with a very nitpicky list of style suggestions :)
A few comments on main()
time.Duration(1000) * time.Millisecond can be written as just 1000 * time.Millisecond
Call the cancel function from context.WithTimeout, otherwise your program has a resource leak (not that it matters from main, but still).
ctx, cancel := context.WithTimeout(...)
defer cancel()
Use ctx consistently, there are some places in main where it refers to context.Background() instead.
Handle the error from os.Create, or your code will be impossible to debug when it fails.
Similarly, you probably want to print an error if urlHolder.WriteTo fails.
I would also suggest making a helper function for creating the XML file and writing to it, in particular if you ever change the file naming pattern you would need to change it in two places.
I think there's no need for a goroutine in main? You can just run it directly unless I'm missing something.
A few things on urlholder.go | {
"domain": "codereview.stackexchange",
"id": 42998,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, stream",
"url": null
} |
go, stream
A few things on urlholder.go
Time time.Time type is almost always used as a value and not as a pointer. The URL.LastMod field should be a time.Time, not a *time.Time.
This is subjective, but UrlMap should be spelled as URLMap.
No need to make a slice of size zero, just use nil.
UrlMap.Add should return an error instead of panicing.
The UrlMap.Add method uses a different method of serialization than WriteTo, so the byte count may not be correct. I would suggest calling WriteTo from inside Add, as follows
func (m *UrlMap) Add(u *URL) int {
s.URLs = append(s.URLs, u)
var out strings.Builder
m.WriteTo(&out)
return len(out.String())
}
I'm not sure what the point of CounterWriter is when the result of urlHolder.WriteTo is ignored anyway.
And since you asked about interfaces, there's no need to use an interface here. In general you should only refactor to use interfaces when you already have two implementations in mind. Using an interface preemptively for a "cleaner" design is an example of YAGNI: you ain't gonna need it. | {
"domain": "codereview.stackexchange",
"id": 42998,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, stream",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
Title: Searching for a performance bug in a C++20 pathfinding algorithm (NBA*)
Question: (See the next iteration.)
I have this pathfinding algorithm:
DirectedGraph.hpp
#ifndef COM_GITHUB_CODERODDE_DIRECTED_GRAPH_HPP
#define COM_GITHUB_CODERODDE_DIRECTED_GRAPH_HPP
#include <cstddef> // for std::size_t
#include <sstream>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
namespace com::github::coderodde::directed_graph {
template<typename Node = int>
class DirectedGraph {
private:
std::unordered_map<Node, std::unordered_set<Node>> child_map_;
std::unordered_map<Node, std::unordered_set<Node>> parent_map_;
std::unordered_set<Node> nodes_;
std::size_t number_of_arcs_;
public:
DirectedGraph() : number_of_arcs_{ 0 } {}
bool addNode(Node const& node) {
if (!hasNode(node)) {
child_map_[node] = {};
parent_map_[node] = {};
nodes_.insert(node);
return true;
}
return false;
}
bool hasNode(Node const& node) {
return nodes_.contains(node);
}
bool removeNode(Node const& node) {
if (!hasNode(node)) {
return false;
}
number_of_arcs_ -=
child_map_[node].size() +
parent_map_[node].size();
child_map_.erase(node);
parent_map_.erase(node);
nodes_.erase(node);
return true;
}
bool addArc(Node const& tail, Node const& head) {
bool state_changed = false;
if (!hasNode(tail)) {
addNode(tail);
state_changed = true;
}
if (!hasNode(head)) {
addNode(head);
state_changed = true;
} | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
if (!child_map_[tail].contains(head)) {
child_map_[tail].insert(head);
state_changed = true;
}
if (!parent_map_[head].contains(tail)) {
parent_map_[head].insert(tail);
state_changed = true;
}
if (state_changed) {
number_of_arcs_++;
}
return state_changed;
}
bool hasArc(Node const& tail, Node const& head) {
if (!child_map_.contains(tail)) {
return false;
}
return child_map_[tail].contains(head);
}
bool removeArc(Node const& tail, Node const& head) {
if (!child_map_.contains(tail)) {
return false;
}
if (!child_map_[tail].contains(head)) {
return false;
}
child_map_[tail].erase(head);
parent_map_[head].erase(tail);
number_of_arcs_--;
return true;
}
std::unordered_set<Node>* getParentNodesOf(Node const& node) {
return &parent_map_[node];
}
std::unordered_set<Node>* getChildNodesOf(Node const& node) {
return &child_map_[node];
}
std::unordered_set<Node> const& getNodes() const {
return nodes_;
}
std::size_t getNumberOfNodes() const {
return nodes_.size();
}
std::size_t getNumberOfArcs() const {
return number_of_arcs_;
}
};
template<typename Node = int>
std::string buildNonExistingArcErrorMessage(
Node const& tail,
Node const& head) {
std::stringstream ss;
ss << "The arc (" << tail << ", " << head << ") does not exist.";
return ss.str();
} | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
class NonExistingArcException : public std::logic_error {
public:
NonExistingArcException(std::string const& err_msg)
:
std::logic_error{ err_msg }
{}
};
template<typename Node = int, typename Weight = double>
class DirectedGraphWeightFunction {
private:
std::unordered_map<Node, std::unordered_map<Node, Weight>> weight_map_;
public:
void addWeight(Node const& tail, Node const& head, Weight weight) {
weight_map_[tail][head] = weight;
}
void removeWeight(Node const& tail, Node const& head) {
if (!weight_map_.contains(tail)
|| !weight_map_[tail].contains(head)) {
return;
}
weight_map_[tail].erase(head);
}
Weight getWeight(Node const& tail, Node const& head) {
if (!weight_map_.contains(tail)
|| !weight_map_[tail].contains(head)) {
throw NonExistingArcException{
buildNonExistingArcErrorMessage(tail, head)
};
}
return weight_map_[tail][head];
}
};
} // End of namespace com::github::coderodde::directed_graph.
#endif // COM_GITHUB_CODERODDE_DIRECTED_GRAPH_HPP
Pathfinders.NBAstar.hpp
#ifndef COM_GITHUB_CODERODDE_GRAPH_PATHFINDERS_NBA_STAR_HPP
#define COM_GITHUB_CODERODDE_GRAPH_PATHFINDERS_NBA_STAR_HPP
#include "DirectedGraph.hpp"
#include "Pathfinders.SharedUtils.hpp"
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <sstream>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace com::github::coderodde::pathfinders {
using namespace com::github::coderodde::directed_graph;
using namespace com::github::coderodde::pathfinders::util; | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
template<typename Node = int, typename Weight = double>
void stabilizeForward(
DirectedGraph<Node>& graph,
DirectedGraphWeightFunction<Node, Weight>& weight_function,
HeuristicFunction<Node, Weight>& heuristic_function,
std::priority_queue<
HeapNode<Node, Weight>*,
std::vector<HeapNode<Node, Weight>*>,
HeapNodeComparator<Node, Weight>>& OPEN_FORWARD,
std::unordered_set<Node>& CLOSED,
std::unordered_map<Node, Weight>& distance_map_forward,
std::unordered_map<Node, Weight>& distance_map_backward,
std::unordered_map<Node, Node*>& parent_map_forward,
Node const& current_node,
Node const& target_node,
Weight& best_cost,
const Node** touch_node_ptr) {
std::unordered_set<Node>* children =
graph.getChildNodesOf(current_node);
for (Node const& child_node : *children) {
if (CLOSED.contains(child_node)) {
continue;
}
Weight tentative_distance =
distance_map_forward[current_node] +
weight_function.getWeight(current_node, child_node);
if (!distance_map_forward.contains(child_node)
|| distance_map_forward[child_node] > tentative_distance) {
OPEN_FORWARD.push(
new HeapNode<Node, Weight>(
child_node,
tentative_distance +
heuristic_function.estimate(child_node, target_node)));
distance_map_forward[child_node] = tentative_distance;
Node* node_ptr = new Node{ current_node };
parent_map_forward[child_node] = node_ptr;
if (distance_map_backward.contains(child_node)) {
Weight path_length = tentative_distance +
distance_map_backward[child_node]; | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
if (best_cost > path_length) {
best_cost = path_length;
*touch_node_ptr = &child_node;
}
}
}
}
}
template<typename Node = int, typename Weight = double>
void stabilizeBackward(
DirectedGraph<Node>& graph,
DirectedGraphWeightFunction<Node, Weight>& weight_function,
HeuristicFunction<Node, Weight>& heuristic_function,
std::priority_queue<
HeapNode<Node, Weight>*,
std::vector<HeapNode<Node, Weight>*>,
HeapNodeComparator<Node, Weight>>& OPEN_BACKWARD,
std::unordered_set<Node>& CLOSED,
std::unordered_map<Node, Weight>& distance_map_forward,
std::unordered_map<Node, Weight>& distance_map_backward,
std::unordered_map<Node, Node*>& parent_map_backward,
Node const& current_node,
Node const& source_node,
Weight& best_cost,
const Node** touch_node_ptr) {
std::unordered_set<Node>* parents =
graph.getParentNodesOf(current_node);
for (Node const& parent_node : *parents) {
if (CLOSED.contains(parent_node)) {
continue;
}
Weight tentative_distance =
distance_map_backward[current_node] +
weight_function.getWeight(parent_node, current_node);
if (!distance_map_backward.contains(parent_node)
|| distance_map_backward[parent_node] > tentative_distance) {
OPEN_BACKWARD.push(
new HeapNode<Node, Weight>(
parent_node,
tentative_distance +
heuristic_function.estimate(parent_node, source_node))); | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
distance_map_backward[parent_node] = tentative_distance;
Node* node_ptr = new Node{ current_node };
parent_map_backward[parent_node] = node_ptr;
if (distance_map_forward.contains(parent_node)) {
Weight path_length = tentative_distance +
distance_map_forward[parent_node];
if (best_cost > path_length) {
best_cost = path_length;
*touch_node_ptr = &parent_node;
}
}
}
}
}
template<typename Node = int, typename Weight = double>
Path<Node, Weight>
runBidirectionalAstarAlgorithm(
DirectedGraph<Node>& graph,
DirectedGraphWeightFunction<Node, Weight>& weight_function,
HeuristicFunction<Node, Weight>* heuristic_function,
Node& source_node,
Node& target_node) {
checkTerminalNodes(graph, source_node, target_node);
std::priority_queue<
HeapNode<Node, Weight>*,
std::vector<HeapNode<Node, Weight>*>,
HeapNodeComparator<Node, Weight>> OPEN_FORWARD;
std::priority_queue<
HeapNode<Node, Weight>*,
std::vector<HeapNode<Node, Weight>*>,
HeapNodeComparator<Node, Weight>> OPEN_BACKWARD;
std::unordered_set<Node> CLOSED;
std::unordered_map<Node, Weight> distance_map_forward;
std::unordered_map<Node, Weight> distance_map_backward;
std::unordered_map<Node, Node*> parent_map_forward;
std::unordered_map<Node, Node*> parent_map_backward;
OPEN_FORWARD .push(new HeapNode<Node, Weight>(source_node, Weight{}));
OPEN_BACKWARD.push(new HeapNode<Node, Weight>(target_node, Weight{}));
distance_map_forward[source_node] = Weight{};
distance_map_backward[target_node] = Weight{}; | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
parent_map_forward[source_node] = nullptr;
parent_map_backward[target_node] = nullptr;
const Node* touch_node = nullptr;
Weight best_cost = std::numeric_limits<Weight>::max();
Weight total_distance =
heuristic_function
->estimate(
source_node,
target_node);
Weight f_cost_forward = total_distance;
Weight f_cost_backward = total_distance;
while (!OPEN_FORWARD.empty() && !OPEN_BACKWARD.empty()) {
if (OPEN_FORWARD.size() < OPEN_BACKWARD.size()) {
HeapNode<Node, Weight>* top_heap_node = OPEN_FORWARD.top();
OPEN_FORWARD.pop();
Node current_node = top_heap_node->getElement();
delete top_heap_node;
if (CLOSED.contains(current_node)) {
continue;
}
CLOSED.insert(current_node); | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
CLOSED.insert(current_node);
if (distance_map_forward[current_node] +
heuristic_function->estimate(current_node, target_node)
>= best_cost
||
distance_map_forward[current_node] + f_cost_backward
- heuristic_function->estimate(current_node, source_node)
>= best_cost) {
// Reject the 'current_node'!
} else {
// Stabilize the 'current_node':
stabilizeForward<Node, Weight>(
graph,
weight_function,
*heuristic_function,
OPEN_FORWARD,
CLOSED,
distance_map_forward,
distance_map_backward,
parent_map_forward,
current_node,
target_node,
best_cost,
&touch_node);
}
if (!OPEN_FORWARD.empty()) {
f_cost_forward = OPEN_FORWARD.top()->getDistance();
}
} else {
HeapNode<Node, Weight>* top_heap_node = OPEN_BACKWARD.top();
OPEN_BACKWARD.pop();
Node current_node = top_heap_node->getElement();
delete top_heap_node;
if (CLOSED.contains(current_node)) {
continue;
}
CLOSED.insert(current_node); | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
CLOSED.insert(current_node);
if (distance_map_backward[current_node] +
heuristic_function->estimate(current_node, source_node)
>= best_cost
||
distance_map_backward[current_node] + f_cost_forward
- heuristic_function->estimate(current_node, target_node)
>= best_cost) {
// Reject the 'current_node'!
}
else {
// Stabilize the 'current_node':
stabilizeBackward<Node, Weight>(
graph,
weight_function,
*heuristic_function,
OPEN_BACKWARD,
CLOSED,
distance_map_forward,
distance_map_backward,
parent_map_backward,
current_node,
source_node,
best_cost,
&touch_node);
}
if (!OPEN_BACKWARD.empty()) {
f_cost_backward = OPEN_BACKWARD.top()->getDistance();
}
}
}
cleanPriorityQueue(OPEN_FORWARD);
cleanPriorityQueue(OPEN_BACKWARD);
if (touch_node == nullptr) {
cleanParentMap(parent_map_forward);
cleanParentMap(parent_map_backward);
throw PathDoesNotExistException{
buildPathNotExistsErrorMessage(source_node, target_node)
};
} | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
Path<Node, Weight> path =
tracebackPath(
*touch_node,
parent_map_forward,
parent_map_backward,
weight_function);
cleanParentMap(parent_map_forward);
cleanParentMap(parent_map_backward);
return path;
}
} // End of namespace 'com::github::coderodde::pathfinders'.
#endif // COM_GITHUB_CODERODDE_GRAPH_PATHFINDERS_NBA_STAR_HPP
Pathfinders.SharedUtils.hpp
#ifndef COM_GITHUB_CODERODDE_PATHFINDERS_UTIL_HPP
#define COM_GITHUB_CODERODDE_PATHFINDERS_UTIL_HPP
#include "DirectedGraph.hpp"
#include <queue>
#include <stdexcept>
#include <string>
#include <vector>
using namespace com::github::coderodde::directed_graph;
namespace com::github::coderodde::pathfinders::util {
template<typename Node = int, typename Weight = double>
class HeuristicFunction {
public:
virtual Weight estimate(Node const& tail, Node const& head) = 0;
virtual ~HeuristicFunction() {
}
};
template<typename Node = int, typename Weight = double>
class Path {
private:
std::vector<Node> nodes_;
DirectedGraphWeightFunction<Node, Weight> weight_function_;
public:
Path(std::vector<Node> const& nodes,
DirectedGraphWeightFunction<Node, Weight> const& weight_function)
:
weight_function_{ weight_function }
{
for (Node e : nodes) {
nodes_.push_back(e);
}
}
Node operator[](std::size_t index) {
return nodes_[index];
}
std::size_t length() {
return nodes_.size();
}
Weight distance() {
Weight total_distance = {};
for (std::size_t i = 0; i < nodes_.size() - 1; ++i) {
total_distance +=
weight_function_.getWeight(
nodes_[i],
nodes_[i + 1]);
} | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
return total_distance;
}
};
class PathDoesNotExistException : public std::logic_error {
public:
PathDoesNotExistException(std::string const& err_msg)
:
std::logic_error{ err_msg }
{}
};
class NodeNotPresentInGraphException : public std::logic_error {
public:
NodeNotPresentInGraphException(std::string const& err_msg)
:
std::logic_error{ err_msg }
{}
};
template<typename Node = int, typename Weight = double>
struct HeapNode {
private:
Weight distance_;
Node element_;
public:
HeapNode(Node const& element, Weight const& distance)
:
distance_{ distance },
element_{ element }
{
}
[[nodiscard]] Node const& getElement() noexcept {
return element_;
}
[[nodiscard]] Weight const& getDistance() noexcept {
return distance_;
}
};
template<typename Node = int, typename Weight = double>
class HeapNodeComparator {
public:
bool operator()(HeapNode<Node, Weight>* first,
HeapNode<Node, Weight>* second) {
return first->getDistance() > second->getDistance();
}
};
template<typename Node = int>
std::string buildSourceNodeNotInGraphErrorMessage(Node source_node) {
std::stringstream ss;
ss << "There is no source node " << source_node << " in the graph.";
return ss.str();
}
template<typename Node = int>
std::string buildTargetNodeNotInGraphErrorMessage(Node target_node) {
std::stringstream ss;
ss << "There is no target node " << target_node << " in the graph.";
return ss.str();
}
template<typename Node = int>
void checkTerminalNodes(DirectedGraph<Node> graph,
Node source_node,
Node target_node) { | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
if (!graph.hasNode(source_node)) {
throw NodeNotPresentInGraphException{
buildSourceNodeNotInGraphErrorMessage(source_node)
};
}
if (!graph.hasNode(target_node)) {
throw NodeNotPresentInGraphException{
buildTargetNodeNotInGraphErrorMessage(target_node)
};
}
}
template<typename Node = int>
std::string buildPathNotExistsErrorMessage(Node source_node, Node target_node) {
std::stringstream ss;
ss << "There is no path from "
<< source_node
<< " to "
<< target_node
<< ".";
return ss.str();
}
template<typename Node = int, typename Weight = double>
Path<Node, Weight>
tracebackPath(Node& target_node,
std::unordered_map<Node, Node*>& parent_map,
DirectedGraphWeightFunction<Node, Weight>& weight_function) {
std::vector<Node> path_nodes;
Node previous_node = target_node;
path_nodes.push_back(target_node);
while (true) {
Node* next_node = parent_map[previous_node];
if (next_node == nullptr) {
std::reverse(path_nodes.begin(), path_nodes.end());
return Path<Node, Weight>{path_nodes, weight_function};
}
path_nodes.push_back(*next_node);
previous_node = *next_node;
}
}
template<typename Node = int, typename Weight = double>
Path<Node, Weight>
tracebackPath(
const Node& touch_node,
std::unordered_map<Node, Node*>& forward_parent_map,
std::unordered_map<Node, Node*>& backward_parent_map,
DirectedGraphWeightFunction<Node, Weight>& weight_function) {
std::vector<Node> path_nodes;
Node previous_node = touch_node;
path_nodes.push_back(touch_node); | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
while (true) {
Node* next_node = forward_parent_map[previous_node];
if (next_node == nullptr) {
std::reverse(path_nodes.begin(), path_nodes.end());
break;
}
path_nodes.push_back(*next_node);
previous_node = *next_node;
}
Node* next_node = backward_parent_map[touch_node];
while (next_node != nullptr) {
path_nodes.push_back(*next_node);
next_node = backward_parent_map[*next_node];
}
return Path<Node, Weight>{path_nodes, weight_function};
}
template<typename Node = int, typename Weight = double>
void cleanPriorityQueue(
std::priority_queue<HeapNode<Node, Weight>*,
std::vector<HeapNode<Node, Weight>*>,
HeapNodeComparator<Node, Weight>>&queue) {
while (!queue.empty()) {
HeapNode<Node, Weight>* heap_node = queue.top();
queue.pop();
delete heap_node;
}
}
template<typename Node = int>
void cleanParentMap(std::unordered_map<Node, Node*> parent_map) {
for (const auto p : parent_map) {
// One 'p.second' will be 'nullptr', but we can "delete" it too:
delete p.second;
}
parent_map.clear();
}
}; // End of namespace 'com::github::coderodde::pathfinders::util'.
#endif // COM_GITHUB_CODERODDE_PATHFINDERS_UTIL_HPP
main.cpp
#include "DirectedGraph.hpp"
#include "Pathfinders.API.hpp"
#include "Pathfinders.SharedUtils.hpp"
#include <chrono>
#include <cstddef>
#include <iostream>
#include <random>
constexpr std::size_t NUMBER_OF_NODES = 100 * 1000;
constexpr std::size_t NUMBER_OF_ARCS = 500 * 1000;
constexpr double SPACE_WIDTH = 10000.0;
constexpr double SPACE_HEIGHT = 10000.0;
constexpr double DISTANCE_FACTOR = 1.1; | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
using namespace com::github::coderodde::directed_graph;
using namespace com::github::coderodde::pathfinders;
using namespace com::github::coderodde::pathfinders::api;
class EuclideanCoordinates {
private:
double x_;
double y_;
public:
EuclideanCoordinates(double x = 0.0, double y = 0.0) :
x_{ x },
y_{ y }
{}
double distanceTo(EuclideanCoordinates const& other) const {
const auto dx = x_ - other.x_;
const auto dy = y_ - other.y_;
return std::sqrt(dx * dx + dy * dy);
}
};
class MyHeuristicFunction : public HeuristicFunction<int, double> {
private:
std::unordered_map<int, EuclideanCoordinates> map_;
public:
MyHeuristicFunction(
std::unordered_map<int, EuclideanCoordinates> map)
: map_{ map } {}
MyHeuristicFunction(const MyHeuristicFunction& other)
:
map_{ other.map_ }
{
}
MyHeuristicFunction(MyHeuristicFunction&& other) {
map_ = std::move(other.map_);
}
MyHeuristicFunction& operator=(const MyHeuristicFunction& other) {
map_ = other.map_;
return *this;
}
MyHeuristicFunction& operator=(MyHeuristicFunction&& other) {
map_ = std::move(other.map_);
return *this;
}
~MyHeuristicFunction() {
}
double estimate(int const& tail, int const& head) override {
const auto point1 = map_[tail];
const auto point2 = map_[head];
return point1.distanceTo(point2);
}
};
class GraphData {
private:
DirectedGraph<int> graph_;
DirectedGraphWeightFunction<int, double> weight_function_;
MyHeuristicFunction heuristic_function_;
public:
GraphData(
DirectedGraph<int> graph,
DirectedGraphWeightFunction<int, double> weight_function,
MyHeuristicFunction heuristic_function)
:
graph_{ graph },
weight_function_{ weight_function },
heuristic_function_{ heuristic_function }
{} | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
DirectedGraph<int>& getGraph() {
return graph_;
}
DirectedGraphWeightFunction<int, double>& getWeightFunction() {
return weight_function_;
}
HeuristicFunction<int, double>& getHeuristicFunction() {
return heuristic_function_;
}
};
EuclideanCoordinates getRandomEuclideanCoordinates(
std::mt19937& mt,
std::uniform_real_distribution<double> x_coord_distribution,
std::uniform_real_distribution<double> y_coord_distribution) {
double x = x_coord_distribution(mt);
double y = y_coord_distribution(mt);
EuclideanCoordinates coords{ x, y };
return coords;
}
GraphData createRandomGraphData(std::size_t number_of_nodes,
std::size_t number_of_arcs) {
DirectedGraph<int> graph;
DirectedGraphWeightFunction<int, double> weight_function;
std::vector<int> node_vector;
node_vector.reserve(number_of_nodes);
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<std::size_t>
uniform_distribution(0, number_of_nodes - 1);
std::uniform_real_distribution<double> x_coord_distribution(0, SPACE_WIDTH);
std::uniform_real_distribution<double> y_coord_distribution(0, SPACE_HEIGHT);
std::unordered_map<int, EuclideanCoordinates> coordinate_map;
for (size_t node_id = 0; node_id < number_of_nodes; ++node_id) {
graph.addNode((int)node_id);
node_vector.push_back((int)node_id);
EuclideanCoordinates coords =
getRandomEuclideanCoordinates(
mt,
x_coord_distribution,
y_coord_distribution);
coordinate_map[(int)node_id] = coords;
} | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
coordinate_map[(int)node_id] = coords;
}
for (size_t i = 0; i < number_of_arcs; ++i) {
std::size_t tail_index = uniform_distribution(mt);
std::size_t head_index = uniform_distribution(mt);
int tail = node_vector[tail_index];
int head = node_vector[head_index];
EuclideanCoordinates tail_coords = coordinate_map[tail];
EuclideanCoordinates head_coords = coordinate_map[head];
graph.addArc(tail, head);
weight_function.addWeight(tail,
head,
tail_coords.distanceTo(head_coords)
* DISTANCE_FACTOR);
}
MyHeuristicFunction heuristic_function{ coordinate_map };
GraphData graph_data(
graph,
weight_function,
heuristic_function);
return graph_data;
}
class Milliseconds {
private:
std::chrono::high_resolution_clock m_clock;
public:
auto milliseconds() {
return std::chrono::duration_cast<std::chrono::milliseconds>
(m_clock.now().time_since_epoch()).count();
}
};
int main() {
GraphData graph_data = createRandomGraphData(NUMBER_OF_NODES,
NUMBER_OF_ARCS);
try {
Milliseconds ms;
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(0, NUMBER_OF_NODES - 1);
int source_node = dist(mt);
int target_node = dist(mt);
std::cout << "Source node: " << source_node << "\n";
std::cout << "Target node: " << target_node << "\n";
std::cout << "--- Dijkstra's algorithm: ---\n";
auto start_time = ms.milliseconds();
Path<int, double> path =
findShortestPath()
.in(graph_data.getGraph())
.withWeights(graph_data.getWeightFunction())
.from(source_node)
.to(target_node)
.usingDijkstra();
auto end_time = ms.milliseconds();
std::cout << "Path:\n"; | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
auto end_time = ms.milliseconds();
std::cout << "Path:\n";
for (size_t i = 0; i < path.length(); ++i) {
std::cout << path[i] << "\n";
}
std::cout << "Path distance: " << path.distance() << "\n";
std::cout << "Duration: " << (end_time - start_time) << " ms.\n\n";
std::cout << "--- Bidirectional Dijkstra's algorithm: ---\n";
start_time = ms.milliseconds();
path =
findShortestPath()
.in(graph_data.getGraph())
.withWeights(graph_data.getWeightFunction())
.from(source_node)
.to(target_node)
.usingBidirectionalDijkstra();
end_time = ms.milliseconds();
std::cout << "Path:\n";
for (size_t i = 0; i < path.length(); ++i) {
std::cout << path[i] << "\n";
}
std::cout << "Path distance: " << path.distance() << "\n";
std::cout << "Duration: " << (end_time - start_time) << " ms.\n\n";
std::cout << "--- A* algorithm: ---\n";
start_time = ms.milliseconds();
path =
findShortestPath()
.in(graph_data.getGraph())
.withWeights(graph_data.getWeightFunction())
.from(source_node)
.to(target_node)
.withHeuristicFunction(graph_data.getHeuristicFunction())
.usingAstar();
end_time = ms.milliseconds();
std::cout << "Path:\n";
for (size_t i = 0; i < path.length(); ++i) {
std::cout << path[i] << "\n";
}
std::cout << "Path distance: " << path.distance() << "\n";
std::cout << "Duration: " << (end_time - start_time) << " ms.\n\n";
//// NBA* /////////////////////////////////////////////////////////////
std::cout << "--- Bidirectional A* (NBA*) algorithm: ---\n";
start_time = ms.milliseconds(); | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
path =
findShortestPath()
.in(graph_data.getGraph())
.withWeights(graph_data.getWeightFunction())
.from(source_node)
.to(target_node)
.withHeuristicFunction(graph_data.getHeuristicFunction())
.usingBidirectionalAstar();
end_time = ms.milliseconds();
std::cout << "Path:\n";
for (size_t i = 0; i < path.length(); ++i) {
std::cout << path[i] << "\n";
}
std::cout << "Path distance: " << path.distance() << "\n";
std::cout << "Duration: " << (end_time - start_time) << " ms.\n\n";
}
catch (NodeNotPresentInGraphException const& err) {
std::cout << err.what() << "\n";
}
catch (PathDoesNotExistException const& err) {
std::cout << err.what() << "\n";
}
return 0;
}
Now, what bother me is that NBA* runs with -O3 optimization in around 200 milliseconds, whereas this demo of the same algorithm in Java in a graph with the same topological properties runs only in 29 milliseconds.
I suspect that I do implicitly copy assignments/constructors, but I am not sure about that. Please, help.
(The entire (Visual Studio 2022) project lives here.)
Answer: Avoid manual new and delete
I see a lot of new and delete statements. Those are rarely needed in modern C++, and usually point to a problem. In particular, you declare a lot of priority queues like so:
std::priority_queue<HeapNode<Node, Weight>*,
std::vector<HeapNode<Node, Weight>*>,
HeapNodeComparator<Node, Weight>> OPEN_FORWARD; | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
And then proceed to create HeapNodes with new and add them to the queue. However, STL containers already allocate memory for you, so instead of having them allocate memory for pointers, and you allocating more memory for the actual HeapNode objects, and everything becoming slower because of the added pointer indirection, ideally you should just be able to write:
std::priority_queue<HeapNode<Node, Weight>> OPEN_FORWARD;
You can if you make the member functions of HeapNode const, and add an operator<() so the container can directly compare elements without needing a HeapNodeComparator. To add a new element, instead of:
OPEN_FORWARD.push(new HeapNode<Node, Weight>(source_node, Weight{}));
You can write:
OPEN_FORWARD.emplace(source_node, Weight{});
And accessing the top element:
HeapNode<Node, Weight>* top_heap_node = OPEN_FORWARD.top();
OPEN_FORWARD.pop();
Node current_node = top_heap_node->getElement();
delete top_heap_node;
Now can be simplified to:
Node current_node = OPEN_FORWARD.top().getElement();
OPEN_FORWARD.pop(); | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
Now can be simplified to:
Node current_node = OPEN_FORWARD.top().getElement();
OPEN_FORWARD.pop();
You also don't need cleanPriorityQueue anymore.
You can do something similar for the parent maps. Currently though, you use nullptrs to indicate that a node doesn't have a parent. Instead, either use find() to check if an element is in the std::unordered_map, or store the parent as std::optional<Node> (although I would prefer the former).
Consider using different data structures
runBidirectionalAstarAlgorithm() uses a large amount of containers to store information: two priority queues, an unordered set and four unordered maps. Most of these, possibly even all of them, will at one point contain as many Node objecs as there are in the input graph. That is a lot of duplication. Consider that even if Node is just a small type like an int (and not, say, a std::string or something even more complicated), a std::unordered_map<Node, ...> will still have to allocate memory for each entry it stores, and has to do bookkeeping for the allocated memory, which greatly increases the amount of memory used per Node.
You can already reduce that by combining the auxiliary information you want to store for each Node while the algorithm is running in a single struct:
struct Info {
bool closed;
Weight distance_forward;
Weight distance_backward;
std::optional<Node> parent_forward;
std::optional<Node> parent_backward;
};
std::unordered_map<Node, Info> info; | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
c++, performance, algorithm, pathfinding, c++20
std::unordered_map<Node, Info> info;
The above map info replaces CLOSED, distance_map_forward, distance_map_backward, parent_map_forward and parent_map_backward. Apart from reducing the memory used by these data structures, having only one map also reduces the number of parameters you have to pass to the stabilize*() functions.
Something similar can be done in class DirectedGraph. Instead of nodes_, child_map_ and parent_map_ being different containers and having to add new nodes to all three of them, just do something like:
struct Adjacency {
std::set<Node> children;
std::set<Node> parents;
};
std::unordered_map<Node, Adjacency> nodes_;
Even better would be to add weights in there as well, so you don't need a separate DirectedGraphWeightFunction.
Add more const
You are already using const in a lot of places, but there is more that can be made const. I already mentioned the member functions of HeapNode, but also the parameters graph and weight_function of runBidirectionalAstarAlgorithm() should be const, and when you do that you will find out you need to make a bunch more member functions const.
Use std::function to pass heuristic_function
Instead of creating an abstract base class HeuristicFunction<Node, Weight>, which then must be inherited from, consider passing a std::function<Weight(const Node&, const Node&)> instead. This will still allow you to use a class to store the heuristic function (if you rename estimate() to operator()()), but now it will also allow you to use free functions or lambda expressions. For example, in createRandomGraphData() you could then write:
GraphData graph_data(graph, weight_function,
[map = std::move(coordinate_map)](const Node& tail, const Node& head) {
return map[tail].distanceTo(map[head]);
}
); | {
"domain": "codereview.stackexchange",
"id": 42999,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, pathfinding, c++20",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.