text stringlengths 1 2.12k | source dict |
|---|---|
c++, iterator
constexpr bool operator==(const iterator& other) const noexcept { return m_iterator == other.m_iterator; }
constexpr bool operator!=(const iterator& other) const noexcept { return m_iterator != other.m_iterator; }
constexpr reference operator*() const noexcept { return *m_iterator; }
constexpr pointer operator->() const noexcept { return m_iterator; }
constexpr iterator& operator++() noexcept { ++m_iterator; return *this; }
constexpr iterator operator++(int) noexcept { iterator tmp(*this); ++(*this); return tmp; }
constexpr iterator& operator--() noexcept { --m_iterator; return *this; }
constexpr iterator operator--(int) noexcept { iterator tmp(*this); --(*this); return tmp; }
constexpr iterator& operator+=(const difference_type other) noexcept { m_iterator += other; return *this; }
constexpr iterator& operator-=(const difference_type other) noexcept { m_iterator -= other; return *this; }
constexpr iterator operator+(const difference_type other) const noexcept { return iterator(m_iterator + other); }
constexpr iterator operator-(const difference_type other) const noexcept { return iterator(m_iterator - other); }
constexpr iterator operator+(const iterator& other) const noexcept { return iterator(*this + other.m_iterator); }
constexpr difference_type operator-(const iterator& other) const noexcept { return std::distance(m_iterator, other.m_iterator); }
constexpr reference operator[](std::size_t index) const { return m_iterator[index]; }
constexpr bool operator<(const iterator& other) const noexcept { return m_iterator < other.m_iterator; }
constexpr bool operator>(const iterator& other) const noexcept { return m_iterator > other.m_iterator; }
constexpr bool operator<=(const iterator& other) const noexcept { return m_iterator <= other.m_iterator; } | {
"domain": "codereview.stackexchange",
"id": 44895,
"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++, iterator",
"url": null
} |
c++, iterator
constexpr bool operator>=(const iterator& other) const noexcept { return m_iterator >= other.m_iterator; }
};
} | {
"domain": "codereview.stackexchange",
"id": 44895,
"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++, iterator",
"url": null
} |
c++, iterator
Thanks !
Answer: As pointed out by @Martin York in the comments that your class is just a wrapper for a pointer, I don't have much to say. I only have one suggestion
Better Formatting
Good formatting IMO plays a major role in how readable your code is. In this case, I find it impossible to navigate through the functions because they all look extremely cramped.
constexpr pointer operator->() const noexcept { return m_iterator; }
constexpr iterator& operator++() noexcept { ++m_iterator; return *this; }
Compare that to
constexpr pointer operator->() const noexcept {
return m_iterator;
}
constexpr iterator& operator++() noexcept {
++m_iterator;
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 44895,
"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++, iterator",
"url": null
} |
java, programming-challenge, time-limit-exceeded
Title: HackerRank "Digit sum" challenge
Question: Here's the question:
Scanner scanner = new Scanner(System.in);
long x = scanner.nextLong();
if(x<=1) return;
if(x>=Math.pow(10, 12)) return;
Map<Integer, Long> y = new HashMap<Integer, Long>();
long k = 5;
long yes = 0;
for(int f = 0;f<x; f++){
y.put(f, k);
k++;
if(k==7){
k=1;
}
yes+= y.get(f);
if(f == x-1){
System.out.println((long)yes);
}
}
// for (int g = 0; g<y.size(); g++) {
// yes+= y.get(g);
// } System.out.println((long)yes);
}}
The first time I was using ArrayList instead of HashMap. I changed it yet it keeps giving me the error. I even tried combining the loop as you can see from the commented out code.
The code works for the first few test cases but after it got into the 7+ digits (~2500000) it starts timing me out.
Please go easy on me as I just started learning Java a few days ago but I have decent JavaScript knowledge.
Do provide me tips on how to increase code efficiency in the future if I ever run into this again.
Answer: Your algorithm, which works one digit at a time, can be switched to one that's much more efficient.
See what happens if you divide the long string of digits into blocks of 6:
561234 561234 561234 561234 561234 561234 …
Each of those blocks has the same sum, so we can add them all up quite easily:
sum = x / 6 * 21;
For the partial block remaining, we could use a simple look-up table:
static final int[] partial = new int[6]{ 0, 5, 11, 12, 14, 17 };
sum += partial[x % 6];
This solution scales much better, as we no longer need a loop. | {
"domain": "codereview.stackexchange",
"id": 44896,
"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, programming-challenge, time-limit-exceeded",
"url": null
} |
strings, swift
Title: Swift-function, which counts all occurrences of a character within a string
Question: I wrote this function, which (shall) count all occurrences of a specified character within a given string.
func countOccurrence(of char: Character, within str: String) -> Int {
var strCopy = str
var indexes = [String.Index]()
while true {
let curr = strCopy.firstIndex(of: char)
if let curr = curr {
indexes.append(curr)
let indexAfter = str.index(after: curr)
strCopy = String(strCopy[indexAfter..<strCopy.endIndex])
} else {
break
}
}
return indexes.count
}
let sTest = "Testing Swift, today Tuesday 123 ! tt".lowercased()
print(countOccurrence(of: "t", within: sTest)) // Result: 7
let sTest2 = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.".lowercased()
print(countOccurrence(of: "s", within: sTest2)) // Result: 4
Can I expect my function to work as expected or does someone see any flaws?
Can it become improved? Respectively, does someone know a better solution for the described task?
Answer: This function appears to be very expensive.
I don't know the right way to author it,
but it isn't the current code.
Consider this task: look for occurrences of "a",
in an input string of a thousand "a"'s.
That is, input length N = 1000.
indexes.append(curr)
...
strCopy = String(strCopy[indexAfter..<strCopy.endIndex]) | {
"domain": "codereview.stackexchange",
"id": 44897,
"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": "strings, swift",
"url": null
} |
strings, swift
Why the .append()? Why allocate?
We need to return an integer,
yet the space complexity is O(N) ?
Why the copy?
We duplicate everything from current index to end-of-string,
rather than using an efficient string view.
By the end of it we've copied half a million characters.
Time complexity is O(N^2).
To propose a quadratic algorithm for a linear task
suggests that you'll want to return to the drawing
board and examine the problem's requirements more closely.
Don't allocate for each index.
Don't copy characters.
Just scan and increment. | {
"domain": "codereview.stackexchange",
"id": 44897,
"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": "strings, swift",
"url": null
} |
performance, c, embedded, c11
Title: Calculate a math sequence that converges
Question: Thanks for taking the time to read this. I could use a few pointers. I have written much better code but wrote this as a quick test. There is obviously a major issue/s somewhere except for the functionality as it was dismissed immediately. There is another question on same code but a different topic.
/*
* Assessment Linschoten 65ft
* calculates collatz up to limit of 10^6 on standard desktop pc
*
* optionally increase stack size on linux
* ulimit -t 300 -l 4086688 -s 81920
*/
#include "calculate.h"
uint64_t odd(uint64_t x){
return x*3 + 1;
}
uint64_t even(uint64_t x){
return x/2;
}
/*
* Iterative process until sequence converges to 1.
*/
colliez* calculate(uint64_t u_limit_in) {
//keep track of biggest number and sequence counter
uint64_t xn = u_limit_in;
uint64_t s_length_counter = 0;
uint64_t max_nr = 0;
colliez *computed_data_ptr = malloc(sizeof(colliez));
while (xn != 1) {
if (xn % 2 == 0) {
xn = even(xn);
}
else{
xn = odd(xn);
if (xn>=max_nr) {
max_nr = xn;
}
}
s_length_counter++;
}
if (computed_data_ptr==NULL) {
printf("null ptr");
}
computed_data_ptr->start_seq = u_limit_in;
computed_data_ptr->max_nr = max_nr;
computed_data_ptr->count_val = s_length_counter;
return computed_data_ptr;
}
/*
* Commandline application called with one argument
* eg ./Colliez 3
*/
int main(int argc, char *argv[])
{
int a, n;
char in_limit[ 20 ];
uint64_t in_limit_data;
char ns[ 20 ];
uint64_t xn;
colliez *raw_calc;
raw_calc = NULL; | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
// first process user input
if (argc != 2) {
printf("\n Enter the value of the upper limit : ");
scanf("%s", in_limit);
printf("\n %s \n", in_limit);
long dud = atoi(in_limit);
in_limit_data = (uint64_t)dud;
fflush(stdin);
printf("\n");
}else{
long dud = atoi(argv[1]);
in_limit_data = (uint64_t)dud;
}
uint64_t cmd_user_arg1 = (uint64_t) in_limit_data;
// 40% of input value. Used to calculate the test range for longest sequence length.
float empiric_batch_size = cmd_user_arg1*0.40;
uint64_t empiric_batch_size_int = round(empiric_batch_size);
uint64_t lower_limit = cmd_user_arg1 - empiric_batch_size;
printf("Calculating Collatz: \n");
printf("---");
printf("\nempirical guess of lower limit with longest sequence chain : %lu \n", lower_limit);
uint64_t x = 0;
// run through inputs high-low
if (cmd_user_arg1>0) {
colliez *final = malloc(sizeof(colliez));
uint64_t largest_start_sequence;
uint64_t new_val = 0;
uint64_t old_val = 0;
//just to be safe include one more integer on limit of empiric approximation.
uint64_t counter_res;
while (x<=empiric_batch_size_int) {
counter_res = cmd_user_arg1 - x;
if (raw_calc!=NULL) {
free(raw_calc);
}
raw_calc = calculate(counter_res);
new_val = raw_calc->count_val;
if (new_val>old_val) {
old_val = new_val;
largest_start_sequence = raw_calc->start_seq;
//keep track of ptr to resulting struct
final = raw_calc;
raw_calc = NULL;
}
x++;
}
printf("largest value in sequence : %lu \n", final->max_nr);
printf("start : %lu \n", final->start_seq);
printf("steps : %lu \n", final->count_val); | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
printf("steps : %lu \n", final->count_val);
printf("\nFinished. \nLongest sequence is : %lu \n \n", final->count_val);
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
and the header file
/*
*
* Assessment
*/
#ifndef _CALCULATE_H
#define _CALCULATE_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
typedef struct colli{
uint64_t start_seq;
uint64_t max_nr;
uint64_t count_val;
} colliez;
uint64_t odd(uint64_t x);
uint64_t even(uint64_t x);
colliez * calculate(uint64_t u_limit_in);
#endif
For numbers larger than 10⁸ this will run for quite a few minutes. I tried some tweaking with ulimit but did not have the time to confirm if it helps a lot.
I have been doing Web development for the last few years and have a degree in electronics. Getting a good understanding of C is essential to my career path but I have had very hostile behaviour after attempting to apply for jobs. It's almost like being tortured by the CIA.
Your comments would be appreciated. | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
Answer: Don’t Import Unnecessary Things in Headers
Currently, "calculate.h" brings in several system files that it doesn’t ever use, but either your main() or calculate() routines need. That makes the header less re-usable in other projects.
It also exposes internal interfaces, such as even and odd, that should not be part of the public API. If anybody else uses your API, that makes it harder to refactor the code into something more efficient, because you’d have no idea what other code might depend on the functions being there.
Right now, you seem to be trying to have all the files in your project include a single header that covers everything. What you instead want is something like a collatz.c module, with a matching collatz.h header containing only the interfaces for that module.
In this case, all you need are the include-guard, the declaration of calculate, and the definition of its return type.
Do You Need a Header at All?
You don’t actually have separate .c files. Therefore, you don’t need to externally link to any function or object declared elsewhere, or repeat the same boilerplate at the start of any two of them. You also don’t need function prototypes if the functions are declared before they are called. You can just declare the result type, then any helper functions calculate uses, then calculate, then main.
A .h file should either correspond to one .c file, or put in one convenient place boilerplate that multiple .c files all need, such as configuration.
Use Unambiguous, Unsurprising Names
You apparently spell Collatz three different ways in this program, although there might be a reference I’m missing. If there is, it would be a good thing to leave a comment on. Try to avoid giving things names that will confuse people. | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
Since C does not have namespaces, you may want to give every identifier in a module a prefix, like collatz_. The name calculate is so general that it’s very likely some other program that wants to re-use your code will use it. It would be better to call it collatz_calculate or collatz_test. If modularizing this code would be overkill, I still recommend giving it a less-generic name that says what it’s calculating, like collatz(n).
It’s customary to give types names that end with _t. So the struct holding the return value could be named something like collatz_result_t or collatz_t. It also probably doesn’t need a start_seq member, since the caller already knows what value it passed to the function.
Use const Where Appropriate
You declare most of your variables C89-style. Wherever possible, you should declare and initialize them as const.
Writing your variables as static single assignments makes the code much easier to debug and reason about, since you know that everything has been set once and only once, and exactly what it was set to. This both helps the compiler optimize (especially loops like this where there’s another reference to one of the variables in scope), and also saves you from bugs where a variable is not set on some path, or changed from what you expect.
Use Integer Math Where Possible
Currently, you convert from uint64_t to double, then float (giving yourself a huge round-off error):
float empiric_batch_size = cmd_user_arg1*0.40; | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
Since a factor of 0.40 is two-fifths, and integer math always rounds toward zero, it would be better to write:
const uint64_t approx_batch_size = (user_val*2U + 3U)/5U; | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
(Assuming your user-supplied starting value can be doubled without overflowing.)
Refactor into Helper Functions
A good example of this are the routines to read the user input. This routine uses a lot of data that the rest of the program doesn’t have any need to see, and none of it is marked const. Some of that data can confuse the optimizer or a maintainer. It would be better to separate that out into a function that returns the user-supplied value, the only output the rest of the program needs.
Dynamically Allocate Memory Only When Necessary
Others have mentioned this, but it is very important for performance. You can just return a struct, and the compiler will allocate the buffer for it automatically. That’s probably simplest. Another good approach if you want to be able to report an error is to take the address of the result buffer as a parameter. This would let you use a local variable as the buffer, or at least re-use the same buffer instead of freeing and re-allocating it each time. However, this function cannot fail (except by running out of memory), although it might possibly run forever.
Consider More-Robust Error-Checking
For example, the odd case of the conjecture could overflow the type, or the input could be invalid.
When possible, rewrite your functions so they can’t fail. For example, if you just read in an unsigned long long, you don’t need to copy it to a buffer or convert it. If you don’t allocate dynamic memory, you can’t get an out-of-memory error.
Next-best is to fail fast. There’s no point to reporting errors up the call chain unless you’ll be handling or retrying them there. But, you could retry reading the input immediately, in the input routine, and only return when you get a valid input. Or, on a fatal error, you could abort immediately. That way, functions only ever return if they succeed, and their results do not need to be checked.
Consider a Tail-Recursive Implementation | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
Consider a Tail-Recursive Implementation
The fact that you have a comment suggesting increasing the maximum stack size is a strong warning that something’s gone wrong. It should be possible to get the compiler to write a version that uses only a constant amount of stack space.
On top of that, recursive implementations can use static single assignments and are generally easier to verify and maintain.
Consider a typedef
Several people have mentioned the possibility of changing the type used for calculations. This will be a lot easier if you can change one typedef than if you have to change a thousand lines of code that say uint64_t. (In C, though, this can easily bite you because something like the overflow check or output specifier breaks silently on the new type. C++ has many more features for working with generic types.)
Consider Memoizing the Function
There’s a lot of recalculation of the same values in this function, as you iterate over the possible starting values. If you stored some or all the previously-computed values in a table, you could mark them off in constant time as soon as you encountered them again: the sequence has that many remaining steps, and you could also look up the largest value in the rest of the sequence.
Putting it All Together
Compare this to the original, and see whether it looks more maintainable:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h> | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
/* Use the musttail attribute to guarantee tail-call optimization, but only on
* compilers that support it.
*/
#if __clang__ || __INTEL_LLVM_COMPILER
# define MUSTTAIL __attribute__((musttail))
#else
# define MUSTTAIL /**/
#endif
typedef unsigned long long int value_t;
/* The return values of collatz_test. */
typedef struct collatz_result_t {
value_t max_nr; // Maximum number reached
value_t count_val; // Count of sequence values
} collatz_result_t;
/* Tail-recursive helper function for collatz_test. Aborts if the sequence
* would overflow an unsigned long long int.
*/
static collatz_result_t collatz_test_helper( const value_t n,
const value_t max,
const value_t counter ) {
static const value_t overflow_if_odd_limit = ULLONG_MAX / 3;
const value_t new_max = (n>max) ? n : max;
if (n <= 1) {
return (collatz_result_t){max, counter};
} else if (n%2 == 0) {
MUSTTAIL return collatz_test_helper(n/2, new_max, counter+1);
} else if (n < overflow_if_odd_limit) {
MUSTTAIL return collatz_test_helper(3*n + 1, new_max, counter+1);
} else {
fflush(stdout);
fprintf(stderr, "Collatz sequence overflows after %llu.\n", (unsigned long long)n);
exit(EXIT_FAILURE);
}
}
/* Returns the length and maximum value of the Collatz sequence beginning at
* start--If the Collatz conjecture is correct. (And, more realistically, if
* it doesn't overflow.)
*/
collatz_result_t collatz_test(const value_t start) {
return collatz_test_helper(start, start, 0);
}
/* Parses a start value from a command-line argument. */
value_t value_from_cl(const char* const argv1) {
return strtoull(argv1, NULL, 10);
} | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
performance, c, embedded, c11
/* Reads a start value from the input FILE*. */
value_t value_from_file(FILE* const input) {
unsigned long long value_read = 0;
if (1 != fscanf(input, "%llu ", &value_read)) {
fflush(stdout);
fprintf(stderr, "Error reading a starting value from stdin.\n");
exit(EXIT_FAILURE);
}
return value_read;
}
/*
* Commandline application called with one argument
* eg ./collatz 3
*/
int main(const int argc, const char* const argv[])
{
const value_t start_val = (argc == 2) ? value_from_cl(argv[1]) :
value_from_file(stdin);
// 40% of input value. Used to calculate the test range for longest sequence length.
const value_t batch_size = (start_val*2U + 3U)/5U;
const value_t lower_limit = start_val - batch_size;
printf("For the Collatz sequences up to %llu, the longest sequence is predicted to start with %llu.\n",
start_val,
lower_limit );
value_t longest_start = 0;
value_t longest_len = 0;
value_t longest_max = 0;
for (value_t i = 0; i < start_val; ++i) {
const collatz_result_t r = collatz_test(i);
if (r.count_val > longest_len) {
longest_start = i;
longest_len = r.count_val;
longest_max = r.max_nr;
}
}
printf("The longest sequence starts at %llu and has %llu steps, reaching a maximum value of %llu.\n",
(unsigned long long)longest_start,
(unsigned long long)longest_len,
(unsigned long long)longest_max );
return EXIT_SUCCESS;
}
And a link to Godbolt. | {
"domain": "codereview.stackexchange",
"id": 44898,
"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": "performance, c, embedded, c11",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Title: An arithmeticable Concept Implementation in C++
Question: This is a follow-up question for A recursive_reduce_all Template Function Implementation in C++. As G. Sliepen's answer mentioned:
std::is_arithmetic_v<> checks whether the type is basically an integer or a float, nothing else will match.
I am trying to implement an arithmeticable concept which checks whether the operations plus, minus ,multiplies and divides are supported by given type.
The experimental implementation
arithmeticable Concept Implementation
// arithmeticable concept
template<class T>
concept arithmeticable = requires(T input)
{
std::plus<>{}(input, input);
std::minus<>{}(input, input);
std::multiplies<>{}(input, input);
std::divides<>{}(input, input);
};
Full Testing Code
The full testing code:
// An arithmeticable Concept Implementation in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <queue>
#include <ranges>
#include <stack>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
// arithmeticable concept
template<class T>
concept arithmeticable = requires(T input)
{
std::plus<>{}(input, input);
std::minus<>{}(input, input);
std::multiplies<>{}(input, input);
std::divides<>{}(input, input);
};
// is_reservable concept
template<class T>
concept is_reservable = requires(T input)
{
input.reserve(1);
};
// is_sized concept, https://codereview.stackexchange.com/a/283581/231235
template<class T>
concept is_sized = requires(T x)
{
std::size(x);
}; | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + 1;
}
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
};
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
};
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
// recursive_unwrap_type_t struct implementation
template<std::size_t, typename, typename...>
struct recursive_unwrap_type { }; | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...>
{
using type = std::ranges::range_value_t<Container1<Ts1...>>;
};
template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...>
{
using type = typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>
>::type;
};
template<std::size_t unwrap_level, typename T1, typename... Ts>
using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type;
// recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035
template<std::size_t, typename>
struct recursive_array_unwrap_type { };
template<template<class, std::size_t> class Container,
typename T,
std::size_t N>
struct recursive_array_unwrap_type<1, Container<T, N>>
{
using type = std::ranges::range_value_t<Container<T, N>>;
}; | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<std::size_t unwrap_level, template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires ( std::ranges::input_range<Container<T, N>> &&
requires { typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges
struct recursive_array_unwrap_type<unwrap_level, Container<T, N>>
{
using type = typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>
>::type;
};
template<std::size_t unwrap_level, class Container>
using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type;
// https://codereview.stackexchange.com/a/253039/231235
template<template<class...> class Container = std::vector, std::size_t dim, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times));
}
}
namespace UL // unwrap_level
{
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto make_view(const Container& input, const F& f) noexcept
{
return std::ranges::transform_view(
input,
[&f](const auto&& element) constexpr { return recursive_transform(element, f ); } );
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
/* Override make_view to catch dangling references. A borrowed range is
* safe from dangling..
*/
template <std::ranges::input_range T>
requires (!std::ranges::borrowed_range<T>)
constexpr std::ranges::dangling make_view(T&&) noexcept
{
return std::ranges::dangling();
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// clone_empty_container template function implementation
template< std::size_t unwrap_level = 1,
std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto clone_empty_container(const Container& input, const F& f) noexcept
{
const auto view = make_view(input, f);
recursive_variadic_invoke_result<unwrap_level, F, Container> output(std::span{input});
return output;
}
// recursive_transform template function implementation (the version with unwrap_level template parameter)
template< std::size_t unwrap_level = 1,
class T,
std::copy_constructible F>
requires (unwrap_level <= recursive_depth<T>() && // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
std::ranges::view<T>&&
std::is_object_v<F>)
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
auto output = clone_empty_container(input, f);
if constexpr (is_reservable<decltype(output)>&&
is_sized<decltype(input)>)
{
output.reserve(input.size());
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
}
else
{
std::ranges::transform(
input,
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
);
}
return output;
}
else if constexpr(std::regular_invocable<F, T>)
{
return std::invoke(f, input);
}
else
{
static_assert(!std::regular_invocable<F, T>, "Uninvocable?");
}
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
/* This overload of recursive_transform is to support std::array
*/
template< std::size_t unwrap_level = 1,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
typename F >
requires (std::ranges::input_range<Container<T, N>>)
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
Container<recursive_variadic_invoke_result_t<unwrap_level, F, T>, N> output;
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
// recursive_transform function implementation (the version with unwrap_level, without using view)
template<std::size_t unwrap_level = 1, class T, class F>
requires (!std::ranges::view<T>)
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
static_assert(unwrap_level <= recursive_depth<T>(),
"unwrap level higher than recursion depth of input"); // trying to handle incorrect unwrap levels more gracefully
recursive_variadic_invoke_result_t<unwrap_level, F, T> output{};
std::ranges::transform(
input, // passing a range to std::ranges::transform()
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return std::invoke(f, input); // use std::invoke()
}
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_transform implementation (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class T, class F>
requires (unwrap_level <= recursive_depth<T>() && // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, T> output{};
output.resize(input.size());
std::mutex mutex;
std::transform(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[&](auto&& element)
{
std::lock_guard lock(mutex);
return recursive_transform<unwrap_level - 1>(execution_policy, element, f);
});
return output;
}
else
{
return f(input);
}
}
}
/* recursive_reduce_all template function performs operation on input container exhaustively
*/
template<typename T>
constexpr auto recursive_reduce_all(const T& input)
{
return input;
}
template<std::ranges::input_range T>
requires (arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
recursive_depth<T>() == 1)
constexpr auto recursive_reduce_all(const T& input)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input));
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// overload for std::array
template<template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires (arithmeticable<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
recursive_depth<Container<T, N>>() == 1)
constexpr auto recursive_reduce_all(const Container<T, N>& input)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input));
}
template<std::ranges::input_range T>
requires (arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>>)
constexpr auto recursive_reduce_all(const T& input)
{
auto result = recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(input, [](auto&& element){ return recursive_reduce_all(element); })
);
return result;
}
// recursive_reduce_all template function with execution policy
template<class ExPo, arithmeticable T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input)
{
return input;
}
template<class ExPo, std::ranges::input_range T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
recursive_depth<T>() == 1)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input));
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with execution policy, overload for std::array
template<class ExPo, template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmeticable<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
recursive_depth<Container<T, N>>() == 1)
constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input));
}
template<class ExPo, std::ranges::input_range T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input)
{
auto result = recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_all(execution_policy, element); }
)
);
return result;
}
// recursive_reduce_all template function with initial value
template<arithmeticable T>
constexpr auto recursive_reduce_all(const T& input1, const T& input2)
{
return std::plus<>{}(input1, input2);
}
template<std::ranges::input_range T, class TI>
requires (arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
recursive_depth<T>() == 1)
constexpr auto recursive_reduce_all(const T& input, TI init)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init);
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with initial value, overload for std::array
template<template<class, std::size_t> class Container,
typename T,
std::size_t N,
class TI>
requires (arithmeticable<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> &&
recursive_depth<Container<T, N>>() == 1)
constexpr auto recursive_reduce_all(const Container<T, N>& input, TI init)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init);
}
template<std::ranges::input_range T, class TI>
requires (arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI>)
constexpr auto recursive_reduce_all(const T& input, TI init)
{
auto result = std::plus<>{}(
init,
recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
input,
[&](auto&& element){ return recursive_reduce_all(element); }
)
)
);
return result;
}
// recursive_reduce_all template function with execution policy and initial value
template<class ExPo, arithmeticable T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input1, const T& input2)
{
return std::plus<>{}(input1, input2);
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class ExPo, std::ranges::input_range T, class TI>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
recursive_depth<T>() == 1)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init);
}
// recursive_reduce_all template function with execution policy and initial value, overload for std::array
template<class ExPo,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
class TI>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmeticable<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> &&
recursive_depth<Container<T, N>>() == 1)
constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input, TI init)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init);
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class ExPo, std::ranges::input_range T, class TI>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init)
{
auto result = init + recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_all(execution_policy, element); })
);
return result;
}
// recursive_reduce_all template function with initial value and specified operation
template<arithmeticable T, class BinaryOp>
requires (std::regular_invocable<BinaryOp, T, T>)
constexpr auto recursive_reduce_all(const T& input1, const T& input2, BinaryOp binary_op)
{
return std::invoke(binary_op, input1, input2);
}
template<std::ranges::input_range T, class TI, class BinaryOp>
requires (arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
recursive_depth<T>() == 1 &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>(),T>,
recursive_unwrap_type_t<recursive_depth<T>(), T>>
)
constexpr auto recursive_reduce_all(const T& input, TI init, BinaryOp binary_op)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op);
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with initial value and specified operation, overload for std::array
template<template<class, std::size_t> class Container,
typename T,
std::size_t N,
class TI,
class BinaryOp>
requires (arithmeticable<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> &&
recursive_depth<Container<T, N>>() == 1 &&
std::regular_invocable<
BinaryOp,
recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>,
recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>>
)
constexpr auto recursive_reduce_all(const Container<T, N>& input, TI init, BinaryOp binary_op)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op);
}
template<std::ranges::input_range T, class TI, class BinaryOp>
requires (arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>(),T>,
recursive_unwrap_type_t<recursive_depth<T>(), T>>
)
constexpr auto recursive_reduce_all(const T& input, TI init, BinaryOp binary_op)
{
auto result = init + recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
input,
[&](auto&& element){ return recursive_reduce_all(element, init, binary_op); })
);
return result;
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with execution policy, initial value and specified operation
template<class ExPo, arithmeticable T, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
std::regular_invocable<BinaryOp, T, T>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input1, const T& input2, BinaryOp binary_op)
{
return std::invoke(binary_op, input1, input2);
}
template<class ExPo, std::ranges::input_range T, class TI, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
recursive_depth<T>() == 1 &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>(),T>,
recursive_unwrap_type_t<recursive_depth<T>(), T>>
)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init, BinaryOp binary_op)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op);
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with execution policy, initial value and specified operation, overload for std::array
template<class ExPo,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
class TI, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmeticable<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> &&
recursive_depth<Container<T, N>>() == 1 &&
std::regular_invocable<
BinaryOp,
recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>,
recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>>
)
constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input, TI init, BinaryOp binary_op)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op);
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class ExPo, std::ranges::input_range T, class TI, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmeticable<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>(),T>,
recursive_unwrap_type_t<recursive_depth<T>(), T>>
)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init, BinaryOp binary_op)
{
auto result = init + recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_all(execution_policy, element, init, binary_op); })
);
return result;
}
template<class T>
requires (std::ranges::input_range<T>)
constexpr auto recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<class T>
requires (std::ranges::input_range<T> &&
std::ranges::input_range<std::ranges::range_value_t<T>>)
constexpr T recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
} | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
void recursive_reduce_all_tests_vector()
{
auto test_vectors = n_dim_container_generator<std::vector, 4, double>(1, 4);
std::cout << "Play with test_vectors:\n\n";
std::cout << "Pure recursive_reduce_all function test: \n";
auto recursive_reduce_all_result1 = recursive_reduce_all(test_vectors);
std::cout << recursive_reduce_all_result1 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq): \n";
auto recursive_reduce_all_result2 = recursive_reduce_all(std::execution::seq, test_vectors);
std::cout << recursive_reduce_all_result2 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par): \n";
auto recursive_reduce_all_result3 = recursive_reduce_all(std::execution::par, test_vectors);
std::cout << recursive_reduce_all_result3 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq): \n";
auto recursive_reduce_all_result4 = recursive_reduce_all(std::execution::par_unseq, test_vectors);
std::cout << recursive_reduce_all_result4 << "\n\n";
std::cout << "recursive_reduce_all function test with initial value: \n";
auto recursive_reduce_all_result5 = recursive_reduce_all(test_vectors, static_cast<double>(1));
std::cout << recursive_reduce_all_result5 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq) and initial value: \n";
auto recursive_reduce_all_result6 = recursive_reduce_all(std::execution::seq, test_vectors, static_cast<double>(1));
std::cout << recursive_reduce_all_result6 << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par) and initial value: \n";
auto recursive_reduce_all_result7 = recursive_reduce_all(std::execution::par, test_vectors, static_cast<double>(1));
std::cout << recursive_reduce_all_result7 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq) and initial value: \n";
auto recursive_reduce_all_result8 = recursive_reduce_all(std::execution::par_unseq, test_vectors, static_cast<double>(1));
std::cout << recursive_reduce_all_result8 << "\n\n";
std::cout << "recursive_reduce_all function test with initial value and specified operation: \n";
auto recursive_reduce_all_result9 = recursive_reduce_all(test_vectors, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result9 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq), initial value and specified operation: \n";
auto recursive_reduce_all_result10 = recursive_reduce_all(std::execution::seq, test_vectors, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result10 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par), initial value and specified operation: \n";
auto recursive_reduce_all_result11 = recursive_reduce_all(std::execution::par, test_vectors, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result11 << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq), initial value and specified operation: \n";
auto recursive_reduce_all_result12 = recursive_reduce_all(std::execution::par_unseq, test_vectors, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result12 << "\n\n";
return;
}
void recursive_reduce_all_tests_array()
{
auto test_array = std::array<double, 4>{1, 1, 1, 1};
std::cout << "Play with test_array:\n\n";
std::cout << "Pure recursive_reduce_all function test: \n";
auto recursive_reduce_all_result1 = recursive_reduce_all(test_array);
std::cout << recursive_reduce_all_result1 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq): \n";
auto recursive_reduce_all_result2 = recursive_reduce_all(std::execution::seq, test_array);
std::cout << recursive_reduce_all_result2 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par): \n";
auto recursive_reduce_all_result3 = recursive_reduce_all(std::execution::par, test_array);
std::cout << recursive_reduce_all_result3 << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq): \n";
auto recursive_reduce_all_result4 = recursive_reduce_all(std::execution::par_unseq, test_array);
std::cout << recursive_reduce_all_result4 << "\n\n";
std::cout << "recursive_reduce_all function test with initial value: \n";
auto recursive_reduce_all_result5 = recursive_reduce_all(test_array, static_cast<double>(1));
std::cout << recursive_reduce_all_result5 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq) and initial value: \n";
auto recursive_reduce_all_result6 = recursive_reduce_all(std::execution::seq, test_array, static_cast<double>(1));
std::cout << recursive_reduce_all_result6 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par) and initial value: \n";
auto recursive_reduce_all_result7 = recursive_reduce_all(std::execution::par, test_array, static_cast<double>(1));
std::cout << recursive_reduce_all_result7 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq) and initial value: \n";
auto recursive_reduce_all_result8 = recursive_reduce_all(std::execution::par_unseq, test_array, static_cast<double>(1));
std::cout << recursive_reduce_all_result8 << "\n\n";
std::cout << "recursive_reduce_all function test with initial value and specified operation: \n";
auto recursive_reduce_all_result9 = recursive_reduce_all(test_array, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result9 << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq), initial value and specified operation: \n";
auto recursive_reduce_all_result10 = recursive_reduce_all(std::execution::seq, test_array, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result10 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par), initial value and specified operation: \n";
auto recursive_reduce_all_result11 = recursive_reduce_all(std::execution::par, test_array, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result11 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq), initial value and specified operation: \n";
auto recursive_reduce_all_result12 = recursive_reduce_all(std::execution::par_unseq, test_array, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result12 << "\n\n";
return;
}
int main()
{
auto start = std::chrono::system_clock::now();
recursive_reduce_all_tests_vector();
recursive_reduce_all_tests_array();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n';
return 0;
}
The output of the test code above:
Play with test_vectors:
Pure recursive_reduce_all function test:
256
recursive_reduce_all function test with execution policy (std::execution::seq):
256
recursive_reduce_all function test with execution policy (std::execution::par):
256 | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
recursive_reduce_all function test with execution policy (std::execution::par):
256
recursive_reduce_all function test with execution policy (std::execution::par_unseq):
256
recursive_reduce_all function test with initial value:
257
recursive_reduce_all function test with execution policy (std::execution::seq) and initial value:
257
recursive_reduce_all function test with execution policy (std::execution::par) and initial value:
257
recursive_reduce_all function test with execution policy (std::execution::par_unseq) and initial value:
257
recursive_reduce_all function test with initial value and specified operation:
65
recursive_reduce_all function test with execution policy (std::execution::seq), initial value and specified operation:
65
recursive_reduce_all function test with execution policy (std::execution::par), initial value and specified operation:
65
recursive_reduce_all function test with execution policy (std::execution::par_unseq), initial value and specified operation:
65
Play with test_array:
Pure recursive_reduce_all function test:
4
recursive_reduce_all function test with execution policy (std::execution::seq):
4
recursive_reduce_all function test with execution policy (std::execution::par):
4
recursive_reduce_all function test with execution policy (std::execution::par_unseq):
4
recursive_reduce_all function test with initial value:
5
recursive_reduce_all function test with execution policy (std::execution::seq) and initial value:
5
recursive_reduce_all function test with execution policy (std::execution::par) and initial value:
5
recursive_reduce_all function test with execution policy (std::execution::par_unseq) and initial value:
5
recursive_reduce_all function test with initial value and specified operation:
1
recursive_reduce_all function test with execution policy (std::execution::seq), initial value and specified operation:
1 | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
recursive_reduce_all function test with execution policy (std::execution::par), initial value and specified operation:
1
recursive_reduce_all function test with execution policy (std::execution::par_unseq), initial value and specified operation:
1
Computation finished at Sun Jul 9 17:26:04 2023
elapsed time: 0.00140964
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_reduce_all Template Function Implementation in C++.
What changes has been made in the code since last question?
I am trying to implement an arithmeticable concept in this post.
Why a new review is being asked for?
Please review the revised code and all suggestions are welcome. | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Why a new review is being asked for?
Please review the revised code and all suggestions are welcome.
Answer: Naming
The name arithmeticable sounds quite weird. arithmetic or is_arithmetic would be better, but of course the second is already taken and the first is easily confused with is_arithmetic. Maybe has_arithmetic_operations, if you don't mind its verbosity?
It doesn't check the return type of the operators
Your concept would accept any type which has math operators that return something completely different from T, including returning void. At first glance, you might want to check that it returns T or std::convertible_to<T>.
Algebraic structure
What you probably intended with this concept is not to test that some operators exist, but rather that the type T has an algebraic structure. In particular, with addition, subtraction, multiplication and division, you are trying to check if T is similar to a field.
In most of the algebraic structures, the result of a binary operation between two Ts is also a T. However, there are many types that have all the operations, but they work on two different types, and/or return a type that's not the same as the inputs. Consider for example subtracting two std::chrono::time_points: the result is a std::chrono::duration. And you cannot add two time_points, while you can add two durations (resulting in another duration) or add a duration and a time_point (resulting in a time_point). That brings me to:
Is this concept useful for your application?
If the application is recursive_reduce_all, I would say that your concept arithmeticable is not useful; it unnecessarily restricts the types that could be reduced over. In fact, only std::plus<>{} needs to be checked if you don't provide a custom reduction function F, and if the caller does specify a reduction function, you should not use any concept at all. | {
"domain": "codereview.stackexchange",
"id": 44899,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, error-handling
Title: Outcome error handler, inspired by boost's outcome namespace
Question: I'm creating a little library for my pet project that is inspired by Boost's outcome namespace. The main reason why I didn't want to use the Boost version is that I don't like the overhead of including something so massive just for something small like this.
Source code:
using u64 = uint64_t;
using i32 = int32_t;
/**
* \brief Base error class
*/
class error {
static inline std::unordered_map<u64, std::string> m_error_templates = {
{ 100, "error occurred while creating 'Hello', today's date is: {:%Y-%m-%d}"},
{ 200, "something messed up in the 'world!' creation process, system has {} threads"}
};
error() = delete;
error(
u64 error_code,
std::string message
) : m_code(error_code),
m_message(std::move(message)) {}
public:
/**
* \brief Emits a new error using the given \a error code.
* \tparam error_code Error code of the error to emit
* \tparam argument_types Argument list types
* \param arguments Argument list that will be passed to the error template
* \return \a Error with the given error code and generated error message.
*/
template<u64 error_code, typename... argument_types>
static error emit(
argument_types&&... arguments
) {
const auto iterator = m_error_templates.find(error_code);
if (iterator == m_error_templates.end()) {
throw std::invalid_argument(std::format("invalid error code used ({})", error_code));
}
return error(error_code, std::vformat(
iterator->second,
std::make_format_args(std::forward<argument_types>(arguments)...)
));
}
/**
* \brief Prints the given error.
*/
void print() const {
std::cout << "error (" << m_code << "): " << m_message << '\n';
}
private:
u64 m_code;
std::string m_message;
}; | {
"domain": "codereview.stackexchange",
"id": 44900,
"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++, error-handling",
"url": null
} |
c++, error-handling
/**
* \brief Outcome namespace, contains containers for handling and propagating errors.
*/
namespace outcome {
/**
* \brief Base \a failure class, can be emitted with an \a error.
*/
class failure {
public:
failure() = delete;
/**
* \brief Creates a new failure case containing the given \a error.
* \param error Error to use as the reason for failure
*/
failure(
const error& error
) : m_error(error) {}
/**
* \brief Returns the contained error.
*/
const error& get_error() const {
return m_error;
}
private:
error m_error;
};
/**
* \brief Base success class, used for handling success cases with no success return types.
*/
class success {};
/**
* \brief Base result class, contains information about the outcome of an operation.
* \tparam type Type of the successful outcome
*/
template<typename type>
class result {
public:
/**
* \brief Move constructor.
*/
constexpr result(
result&& other
) noexcept {
m_value = other.m_value;
}
/**
* \brief Constructs a result from a failure.
*/
constexpr result(
failure&& failure
) : m_value(std::unexpected(failure.get_error())) {}
/**
* \brief Constructs a result from a success.
*/
constexpr result(
success&& success
) : m_value() {}
/**
* \brief Constructs a result from a given value.
*/
template<typename current_type>
constexpr result(
current_type&& value
) : m_value(std::forward<current_type>(value)) {}
/**
* \brief Checks if the result contains an error.
*/
bool has_error() const {
return !m_value.has_value();
} | {
"domain": "codereview.stackexchange",
"id": 44900,
"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++, error-handling",
"url": null
} |
c++, error-handling
/**
* \brief Checks if the result contains a value.
*/
bool has_value() const {
return m_value.has_value();
}
/**
* \brief Returns the encapsulated value.
*/
const type& get_value() const {
return m_value.value();
}
/**
* \brief Returns the encapsulated error.
*/
const error& get_error() const {
return m_value.error();
}
private:
std::expected<type, error> m_value;
};
/**
* \brief Specialization of the \a result class for void type.
*/
template<>
class result<void> {
public:
constexpr result(
result&& other
) noexcept {
m_value = other.m_value;
}
constexpr result(
failure&& failure
) : m_value(std::unexpected(failure.get_error())) {}
constexpr result(
success&& success
) : m_value() {}
bool has_error() const {
return !m_value.has_value();
}
bool has_value() const {
return m_value.has_value();
}
const error& get_error() const {
return m_value.error();
}
private:
std::expected<void, error> m_value;
};
}
#define CONCATENATE(x, y) _CONCATENATE(x, y)
#define _CONCATENATE(x, y) x ## y | {
"domain": "codereview.stackexchange",
"id": 44900,
"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++, error-handling",
"url": null
} |
c++, error-handling
#define CONCATENATE(x, y) _CONCATENATE(x, y)
#define _CONCATENATE(x, y) x ## y
/**
* \brief Attempts to call the given \a __function, if the outcome of the
* function call is erroneous immediately returns from the parent function/method.
* \param __success Variable declaration used for storing the successful result
* \param __function Function to execute
*/
#define OUTCOME_TRY(__success, __function) \
auto CONCATENATE(result, __LINE__) = __function; \
if(CONCATENATE(result, __LINE__).has_error()) \
return outcome::failure((CONCATENATE(result, __LINE__)).get_error()); \
__success = CONCATENATE(result, __LINE__).get_value()
Example usage:
outcome::result<std::string> generate_hello(
bool emit_error
) {
if(emit_error) {
return outcome::failure(
error::emit<100>(std::chrono::system_clock::now())
);
}
return "Hello";
}
outcome::result<std::string> generate_world(
bool emit_error
) {
if (emit_error) {
return outcome::failure(
error::emit<200>(std::thread::hardware_concurrency())
);
}
return " world!";
}
outcome::result<std::string> test() {
OUTCOME_TRY(const auto& hello, generate_hello(false));
OUTCOME_TRY(const auto& world, generate_world(false));
return hello + world;
}
i32 main() {
// capture propagated errors
const auto& result = test();
if(result.has_value()) {
std::cout << "value: " << result.get_value() << '\n';
}
else {
result.get_error().print();
}
return 0;
}
Answer: Unnecessary code
Your classes are actually just very thin wrappers over std::expected and std::unexpected. With some minor changes (like replacing get_value() with value(), has_error() with !has_value()), you can just do:
namespace outcome {
template<typename T>
using failure = std::unexpected<T>; | {
"domain": "codereview.stackexchange",
"id": 44900,
"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++, error-handling",
"url": null
} |
c++, error-handling
template<typename T>
using result = std::expected<T, error>;
}
And the rest of your code will compile and do the same thing!
Unnecessary templating of error::emit()
I don't see any point in passing error_code as a template parameter to error::emit(). Nothing is constexpr here. If the compiler can somehow specialize and optimize based on the error_code, it can still do that if it's passed as a regular function parameter.
If you really want to make use of the template parameter, then instead of storing the error messages in a std::unordered_map, use variable templates and template specialization instead:
class error {
template<u64 error_code>
static const char* error_template{};
…
public:
template<u64 error_code, …>
static error emit(…) {
return {error_code, std::vformat(error_template<error_code>, …)};
}
…
};
template<> const char* error::error_template<100> = "error occured while creating 'Hello', today's date is: {:%Y-%m-%d}";
template<> const char* error::error_template<200> = "something messed up in the 'world!' creation process, system has {} threads"; | {
"domain": "codereview.stackexchange",
"id": 44900,
"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++, error-handling",
"url": null
} |
c++, error-handling
Consider using std::error_code instead of class error
Your class error looks very similar to std::error_code. I would use the latter instead of reinventing the wheel. You can create a custom error category (derived from std::error_category) for your own errors.
Avoid creating aliases for built-in types
It might save a little bit of typing, but I recommend you don't create u64 and i32 aliases. In particular, don't declare those aliases in a header file in the global namespace. Just write std::uint64_t and std::int32_t. If you have a project that includes multiple libraries, it's easy to get lots of different aliases for the same type (making grepping harder), and adds potential for conflicts.
main() returns int, not i32
There is only one valid return type for main(), and that is int. While i32 might be an alias for int on some platforms, there are other platforms where this is not the case, and thus would probably cause a compile error.
Don't use const references to hold returned values
In main() you wrote:
const auto& result = test();
However, test() returns an outcome by value. The const auto reference will cause the temporary return value's lifetime to be extended, so it still works fine, but I would just write:
auto result = test();
You wouldn't write this either, even though it compiles:
const auto& pi = 3.1415; | {
"domain": "codereview.stackexchange",
"id": 44900,
"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++, error-handling",
"url": null
} |
beginner, rust
Title: Find Ramanujan-Hardy numbers smaller than N
Question: Problem statement: Write a program that takes a command-line argument n and prints all integers less than n that can be expressed as the sum of two cubes in two different ways i.e. distinct positive integers \$a\$, \$b\$, \$c\$, and \$d\$ such that \$a^3 + b^3 = c^3 + d^3\$.
This is one of my self-imposed challenges in Rust to become better at it. The problem was taken from Sedgewick Exercise 1.3.34.
Here is my code:
use clap::Parser;
#[derive(Debug, Parser)]
struct Arguments {
#[arg(index = 1)]
n: usize,
}
fn main() {
let arguments = Arguments::parse();
let mut ramanujan_numbers = Vec::new();
for a in 1..arguments.n {
if a.pow(3) > arguments.n {
break;
}
for b in (a + 1)..arguments.n {
if b.pow(3) > arguments.n {
break;
}
for c in (b + 1)..arguments.n {
if c.pow(3) > arguments.n {
break;
}
for d in (c + 1)..arguments.n {
if d.pow(3) > arguments.n {
break;
}
let first_condition = a.pow(3) + b.pow(3) == c.pow(3) + d.pow(3);
let second_condition = a.pow(3) + c.pow(3) == b.pow(3) + d.pow(3);
let third_condition = a.pow(3) + d.pow(3) == b.pow(3) + c.pow(3);
if first_condition {
let ramanujan_number = a.pow(3) + b.pow(3);
if ramanujan_number < arguments.n {
ramanujan_numbers.push(ramanujan_number);
}
} else if second_condition {
let ramanujan_number = a.pow(3) + c.pow(3); | {
"domain": "codereview.stackexchange",
"id": 44901,
"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, rust",
"url": null
} |
beginner, rust
if ramanujan_number < arguments.n {
ramanujan_numbers.push(ramanujan_number);
}
} else if third_condition {
let ramanujan_number = a.pow(3) + d.pow(3);
if ramanujan_number < arguments.n {
ramanujan_numbers.push(ramanujan_number);
}
}
}
}
}
}
ramanujan_numbers.sort();
match ramanujan_numbers.len() {
0 => println!(
"No Ramanujan number smaller than {} was found.",
arguments.n
),
1 => println!(
"The Ramanujan number smaller than {} is {:?}.",
arguments.n, ramanujan_numbers
),
_ => println!(
"The Ramanujan numbers smaller than {} are {:?}.",
arguments.n, ramanujan_numbers
),
}
}
Is there any way that I can improve my code?
Answer: Coding Style
Factor the Algorithm into Helper Functions
Right now, you’ve got two levels of nested if, several with else blocks, nested inside five levels of loops.
This could really benefit from some helper functions. Let’s say I’m giving you the code review and I say, “Oh, we have a function like this already. Maybe you could use that in your algorithm.”
/* Finds all pairs (a,b) such that a**3 + b**3 = sum.
*/
fn taxicab_pairs(sum: usize) -> Vec<(usize, usize)>
The code would get a whole lot simpler now, right? For example, your loop might now look something like
for i in 1..arguments.n {
let cube_pairs = taxicab_pairs(i);
if cube_pairs.len() > 1 {
// Print the pairs out.
}
}
Or if you just want a list of Ramanujan-Hardy numbers like you have now, you might do something like that with iterators.
Prefer Iterator Expressions to Mutable Objects
You currently initialize
let mut ramanujan_numbers = Vec::new(); | {
"domain": "codereview.stackexchange",
"id": 44901,
"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, rust",
"url": null
} |
beginner, rust
and push numbers onto it, one at a time.
But you could also build this list of numbers at once, with a bit of functional programming, and make it immutable. That not only prevents entire categories of bugs, the compiler converts everything into static single assignments during its optimization passes, so you’re making the code easier to optimize, too.
That might look something like
let ramunujan_numbers: Vec<usize> = (1..arguments.n)
.filter(is_taxicab_number)
.collect();
Or if we have taxicab_pairs, maybe we’d rather keep the list of (a, b) and (c, d) pairs we calculate with that, instead of sending it to a print loop.
let sets_of_pairs: Vec<Vec<(usize, usize)>> = (1..arguments.n)
.map(taxicab_pairs) // Gives us a sequence of Vec<(usize, usize)>
.filter(move |v| v.len() > 1) // Removes all with fewer than two pairs
.collect();
Then we can keep the code at the end to handle the case where there aren’t any taxicab numbers in range.
You might also choose to remove the .collect() lines, and let the compiler infer the type, to obtain lazily-evaluated iterators instead of a strictly-evaluated Vec. This lets you generate the sequence as you calculate, and print each output immediately, rather than waiting for all the output to begin printing anything. You would then need to use a different method to see if there are any taxicab numbers in range (such as making it Peekable and peeking ahead to see whether the iterator immediately returns None).
let mut sets_of_pairs = (1..n)
.map(taxicab_pairs) // Gives us a sequence of Vec<(usize, usize)>
.filter(move |v| v.len() > 1) // Removes all with fewer than two pairs
.peekable();
if sets_of_pairs.peek().is_none() {
println!("No taxicab numbers less than {}.", n);
}
// No need for an else; the loop will just fall through in that case.
Make the Type of Each Variable Obvious
Right now, you declare a list like
let mut ramanujan_numbers = Vec::new(); | {
"domain": "codereview.stackexchange",
"id": 44901,
"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, rust",
"url": null
} |
beginner, rust
One way this could be improved is that we can’t tell what’s in the vector. The compiler tries to infer it from elsewhere, but that’s very fragile to refactoring. Maybe the line that sets this tells the compiler the type moves out of scope, or maybe it also tries to infer the type out of context, or maybe there are multiple places this gets updated, and not all of them agree.
Even if the compiler can tell what the type of ramanujan_numbers is, it’s needlessly complicated for a human maintaining the code. So, annotate it when it’s declared, or (if you aren’t replacing this with a static single assignment) call Vec::<usize>::new() with the turbofish operator, or something else that makes it clear.
Simplify the Conditionals
The first_condition, second_condition and third_comdition block is unwieldy, although it can be factored out entirely.
The Command-Line Arguments
You might have chosen the way you did intentionally, but there is support for this in the standard library. You could use that to check for runtime errors and choose which message to print.
Performance
Prune the Search Space with Some Easy (Really!) Number Theory
Okay, let’s say we have two whole numbers, a and b. One thing we know about them already is that either a is bigger, b is bigger, or they’re equal. You already noticed that you can throw out all the cases where b > a, and cut your search time nearly in half. That’s a great idea, so let’s stick with it.
Here, we’re interested in an x and a y that add up to some number z. If x and y are equal, they’re both half of z. They can’t both be bigger than half of z, or they wouldn’t add up to z. So one is bigger than z/2 and one is smaller. If they aren’t equal to each other, and we just said that x isn’t bigger than y either, x must be the one that’s smaller than z/2 and y the one that’s bigger. | {
"domain": "codereview.stackexchange",
"id": 44901,
"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, rust",
"url": null
} |
beginner, rust
But, for this problem, we actually want x and y to be perfect cubes! So, x = a³ ≤ z/2 and y = b³ ≥ z/2. The most interesting part of that is a³ ≤ z/2. Since a is positive, we can take the cube root of both sides and solve for a. In other words, we only need to search up to the cube root of half of the target number for a, and we’ll be sure we’ve found every possible smaller cube that adds up with another to the right number.
Now, if we have a, we have x = a³, and we started with z, we can solve x + y = z for y = z - x. If y is also a perfect cube, we’re done. There are a few ways we chan check this, but one is to convert to floating-point, find the cube root, round off to an integer, and see if its cube is actually the right number.
Since the program specified that we only need to find out whether a number is the sum of two different pairs of positive cubes, not what all those pairs are, we could optimize further. (For example, we can prove that a+b is congruent to z, modulo 3, reducing the search space further.) But I’ll leave it there.
Putting It All Together
use std::{env, process}; | {
"domain": "codereview.stackexchange",
"id": 44901,
"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, rust",
"url": null
} |
beginner, rust
/* Finds all pairs (a,b) such that a**3 + b**3 = sum.
*/
fn taxicab_pairs(sum: usize) -> Vec<(usize, usize)> {
/* If positive integers a**3 + b**3 = i, and WLOG a <= b,
* a <= pivot and b >= pivot.
*/
let pivot: usize = f64::floor(f64::powf(sum as f64 / 2.0, 1.0 / 3.0) + f64::EPSILON) as usize;
(1..=pivot)
.map(move |a| (a, sum - a * a * a))
.map(move |(a, b_cubed)| {
(
a,
f64::round(f64::powf(b_cubed as f64, 1.0 / 3.0)) as usize,
b_cubed,
)
})
.filter(move |&(_, b, b_cubed)| b * b * b == b_cubed)
.map(move |(a, b, _)| (a, b))
.collect()
}
pub fn main() {
const USAGE_MSG: &str = "Call this program with one command-line argument, N.\n";
let args: Vec<String> = env::args().collect();
let n: usize = if args.len() == 2 {
match args[1].parse::<usize>() {
Ok(n) => n,
_ => {
eprintln!("{}", USAGE_MSG);
process::exit(1)
}
}
} else {
eprintln!("{}", USAGE_MSG);
process::exit(1)
};
let sets_of_pairs: Vec<Vec<(usize, usize)>> = (1..n)
.map(taxicab_pairs) // Gives us a sequence of Vec<(usize, usize)>
.filter(move |v| v.len() > 1) // Removes all with fewer than two pairs
.collect();
if sets_of_pairs.is_empty() {
println!("No taxicab numbers less than {}.", n);
}
// No need for an else; the loop will just fall through in that case.
for cube_pairs in sets_of_pairs {
let (a, b) = cube_pairs[0]; // Safe, because we only added sets of at least two pairs.
let i = a * a * a + b * b * b;
let residue = i % 3; | {
"domain": "codereview.stackexchange",
"id": 44901,
"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, rust",
"url": null
} |
beginner, rust
print!("{}", i);
for (a, b) in cube_pairs {
assert_eq!(i, a * a * a + b * b * b);
assert_eq!(residue, (a + b) % 3); // You might prove this congruence.
print!(" = {}³ + {}³", a, b);
}
println!(".");
}
}
Links to the code on Godbolt,, and the OLIS sequence.
You might prefer the use of a helper function to a chain of map calls:
/* Finds all pairs (a,b) such that a**3 + b**3 = sum.
*/
fn taxicab_pairs(sum: usize) -> Vec<(usize, usize)> {
/* Given a and sum, finds b such that a**3 + b**3 == sum, if b exists.
* Returns either Some((a,b)) or None.
*/
fn find_dual(sum: usize, a: usize) -> Option<(usize, usize)> {
let b_cubed = sum - a*a*a;
let b = f64::round(f64::powf(b_cubed as f64, 1.0 / 3.0)) as usize;
if b*b*b == b_cubed {
Some((a, b))
} else {
None
}
}
/* If positive integers a**3 + b**3 = i, and WLOG a <= b,
* a <= pivot and b >= pivot.
*/
let pivot: usize = f64::floor(f64::powf(sum as f64 / 2.0, 1.0 / 3.0) + f64::EPSILON) as usize;
(1..=pivot)
.filter_map(move|a| find_dual(sum, a))
.collect()
} | {
"domain": "codereview.stackexchange",
"id": 44901,
"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, rust",
"url": null
} |
sql, sql-server, t-sql
Title: What is the percentage of customers who increase their closing balance by more than 5%?
Question: The Question
What is the percentage of customers who increase their closing balance by more than 5%?
Source Code
The database and all details can be found here.
ERD
My Proposed Solution
Select TOP 1
Format(Cast(Count(Distinct Y.customer_id) AS Decimal) /
(Select Count(Distinct customer_id) From customer_transactions), 'P1') As PercentageOfCutomer
From(
Select
X.customer_id
,X.RowNum
,CAST(BalanceAccumSum - LAG(BalanceAccumSum, 1, 0)
OVER(Partition By X.customer_id Order By X.RowNum ASC) AS DECIMAL) / NULLIF(LAG(BalanceAccumSum, 1, 0)
OVER(Partition By X.customer_id Order By X.RowNum ASC),0) As ClosingBalance
From
(
Select
A.customer_id
,A.RowNum
,Sum(A.signedTxnAmount) Over(Partition By A.customer_id Order By A.RowNum) As BalanceAccumSum
From (
Select
customer_id
,CASE
When txn_type = 'deposit' Then txn_amount
When txn_type in ('purchase', 'withdrawal') Then txn_amount * -1
Else txn_amount
END As signedTxnAmount
,ROW_NUMBER() OVER(Partition By customer_id Order By txn_date) AS RowNum
From customer_transactions) A
) X
) Y
Where Y.ClosingBalance > 0.05
Group By Y.customer_id, Y.RowNum
Output
My Query
Assuming that my understanding of the question is correct. That is: Get the Percentage of Customers whose closing balance is > 5% compared to the previous balance before the latest.
Is my solution overcomplicated with these subqueries, or is it OK? Am I missing anything to make it better? | {
"domain": "codereview.stackexchange",
"id": 44902,
"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": "sql, sql-server, t-sql",
"url": null
} |
sql, sql-server, t-sql
Answer: The Good
Using subqueries instead of CTEs (which would impose an optimization boundary).
The Bad
You form a window in three different subqueries; it should only be needed in one.
When txn_type = 'deposit' Then txn_amount is redundant.
This query does not call for formatting. In real life, essentially all queries are consumed by applications and not by people, so the output should be a single floating-point fraction from 0 to 1.
You should not need top 1 with a properly-written count. You should not count distinct.
Never label subqueries A, X etc.; always give them meaningful names.
txn_amount * -1 is just -txn_amount.
More broadly, your approach needs to be re-thought. Instead of going through all of the trouble to calculate the actual close-balance change (which is not needed), all you need is a boolean indicating whether that change was high enough. This interpretation has significant benefits, including that you don't need to care about divide-by-zero for the first-row edge case within a window since you don't need to divide at all, only compare.
Your results are incorrect. At least one bug: if there are only deposits and no withdrawals or purchases, the fraction should be 1.0 but your query does not produce any rows.
After a bunch of work, I believe all three methods below to be equivalent and correct. But you'll find that they all return slightly different results! This is explained by the fact that the test data are ambiguous: there is no clear "last transaction" since many transactions overlap and only have dates set, not times. This is the fault of the course, which should have used unique timestamps instead of overlapping dates. | {
"domain": "codereview.stackexchange",
"id": 44902,
"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": "sql, sql-server, t-sql",
"url": null
} |
sql, sql-server, t-sql
Critically, this calls for unit tests (which are certainly possible, especially in PostgreSQL). If you do not unit test with small, well-defined, repeatable cases, there is no way to know whether your output percentage is correct. As a matter of practice and diligence, any non-trivial queries like this should get unit tests. For instance, with these data:
INSERT INTO customer_transactions
(customer_id, txn_date, txn_type, txn_amount)
VALUES
('429', '2020-01-01', 'deposit', '500'),
('429', '2020-01-02', 'deposit', '500'),
('429', '2020-01-03', 'deposit', '49'),
('622', '2020-01-01', 'deposit', '1'),
('622', '2020-01-02', 'deposit', '1'),
('622', '2020-01-03', 'deposit', '-1'),
('266', '2020-01-01', 'deposit', '1'),
('266', '2020-01-02', 'deposit', '1'),
('266', '2020-01-03', 'deposit', '-1'); | {
"domain": "codereview.stackexchange",
"id": 44902,
"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": "sql, sql-server, t-sql",
"url": null
} |
sql, sql-server, t-sql
your query should produce 0, but replacing the 49 with a 51 should produce 0.333. Without running more such tests it will be difficult to figure out why your query produces 0.2% and mine 41.6%.
Format() is not a SQL-standard function. This makes me guess that you're using TSQL, which is not as good of an idea as using the course's PostgreSQL.
The course should not have taught you to use a string for a transaction type. You should be using an enum instead.
The course has a poor table definition. It should be closer to something like:
CREATE TABLE customer_transactions (
customer_id INTEGER not null,
txn_date DATE not null,
txn_type VARCHAR(10) not null check(txn_type in ('deposit', 'purchase', 'withdrawal')),
txn_amount INTEGER check (txn_amount >= 0)
);
It's also missing a foreign key.
The Ugly
Standard practice for SQL keywords is to CAPITALIZE them. You use a random mix of CAPITALS and TitleCase. I personally don't like either and prefer lowercase, but you should be consistent. Also keep in mind that your identifiers like BalanceAccumSum lose their case in many systems (PostgreSQL included), and so balance_accum_sum stands a better chance at its legibility surviving.
Moving commas to be a prefix on the following line is deeply bizarre and I find illegible. Any small benefit of "some commas lining up on the same column" is thoroughly outweighed by the loss of legibility.
Your indentation ranges from 4 (pretty reasonable) to 8 (not reasonable).
Suggested Query
Again, please test this with small, well-understood cases, comparing your own results to mine (also see fiddle).
set search_path = data_bank; | {
"domain": "codereview.stackexchange",
"id": 44902,
"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": "sql, sql-server, t-sql",
"url": null
} |
sql, sql-server, t-sql
select (
count(*) filter (where big_gain)
) / cast(count(*) as real) as customers_with_gain_frac
from (
select distinct on (customer_id) customer_id, big_gain
from (
select customer_id,
-- curr/(cumsum - curr) > 0.05
-- curr > cumsum*0.05/1.05
signed_amount > 0.05/1.05*abs(
sum(signed_amount) over cust_window
) as big_gain,
row_number() over cust_window as idx
from (
select
customer_id, txn_date,
case
when txn_type in ('purchase', 'withdrawal') then -txn_amount
else txn_amount
end as signed_amount
from customer_transactions
) transactions_with_sign
window cust_window as (partition by customer_id order by txn_date)
) transactions_with_change
order by customer_id, idx desc
) customers_with_gains;
For a quite different take, this is also possible with no windowing:
with transactions_with_sign as (
select customer_id, txn_date,
case
when txn_type in ('purchase', 'withdrawal') then -txn_amount
else txn_amount
end as signed_amount
from customer_transactions
)
select
count(*) filter (
where last_transactions.signed_amount > 0.05/1.05*abs(accounts.balance)
) / cast(count(*) as real) as customers_with_gain_frac
from
(
select distinct on (customer_id) customer_id, signed_amount
from transactions_with_sign
order by customer_id, txn_date desc
) last_transactions
join (
select customer_id, sum(signed_amount) as balance
from transactions_with_sign
group by customer_id
) accounts on accounts.customer_id = last_transactions.customer_id;
Or, even, with no CTE: | {
"domain": "codereview.stackexchange",
"id": 44902,
"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": "sql, sql-server, t-sql",
"url": null
} |
sql, sql-server, t-sql
Or, even, with no CTE:
select
count(*) filter (
where last_transactions.txn_amount > 0.05/1.05*abs(accounts.balance)
and last_transactions.txn_type = 'deposit'
) / cast(count(*) as real) as customers_with_gain_frac
from
(
select customer_id,
sum(
case
when txn_type in ('purchase', 'withdrawal') then -txn_amount
else txn_amount
end
) as balance
from customer_transactions
group by customer_id
) accounts
left join (
select distinct on (customer_id) customer_id, txn_type, txn_amount
from customer_transactions
order by customer_id, txn_date desc
) last_transactions
on last_transactions.customer_id = accounts.customer_id; | {
"domain": "codereview.stackexchange",
"id": 44902,
"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": "sql, sql-server, t-sql",
"url": null
} |
python, python-3.x
Title: Pythonic and mypy compatible way to map str to Enum
Question: my goal is to have a user input a string that is checked to be valid - by defining a dict of allowed strings - and mapped to another string to be stored in a list.
Another function is supposed to map these stored strings to Enums and work with those.
Here's the code I have:
from __future__ import annotations
from enum import Enum
from typing import List, Type
ONG_SPS_STATES = {
"pre": "PreReleased",
"rel": "Released",
"ret": "Retired",
"tgt": "Target"
}
sps_states: List[str] = []
def str_to_state(input: str) -> None:
if (input in ONG_SPS_STATES.keys()):
sps_states.append(ONG_SPS_STATES[input])
else:
print('Invalid input')
SpsState = Enum('SpsState', list(ONG_SPS_STATES.values()))
def get_sps_state(index: int) -> Type[Enum]:
if (len(sps_states) > index):
return SpsState[sps_states[index]]
raise Exception('Invalid index')
if (__name__ == '__main__'):
cont = True
while cont:
inp = input('State: ')
if (inp.lower() != 'e'):
str_to_state(inp)
else:
cont = False
cont = True
while cont:
inp = input('Index: ')
if (inp.lower() != 'e'):
print(get_sps_state(int(inp)))
else:
cont = False
The problem is that mypy complains about line 21 (SpsState = Enum('SpsState', list(ONG_SPS_STATES.values()))) with error: Enum() expects a string, tuple, list or dict literal as the second argument [misc] and line 25 (return SpsState[sps_states[index]]) with error: Incompatible return value type (got "SpsState", expected "Type[Enum]") [return-value]
How can the existing code with the described "ease of use" be rewritten to be pythonic (Python 3.9 if that is important) and compatible with mypy at the same time? | {
"domain": "codereview.stackexchange",
"id": 44903,
"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, python-3.x",
"url": null
} |
python, python-3.x
Answer: Your enum setup is kind of inside-out and backwards. Don't make a dictionary and don't define an enum via sequence; make a normal Enum subclass. Its values will be your current keys, and its names will be your current values.
Don't surround if predicates with parens in Python.
Don't use a cont loop flag when you can just break.
Suggested
from enum import Enum
class SpsState(Enum):
PreReleased = 'pre'
Release = 'rel'
Retired = 'ret'
Target = 'tgt'
@classmethod
def from_index(cls, idx: int) -> 'SpsState':
return tuple(cls)[idx]
def input_state_str() -> None:
while True:
command = input('State, or "e" to end: ').lower()
if command == 'e':
break
try:
print(SpsState(command))
except ValueError as e:
print('Invalid input:', e)
def input_state_int() -> None:
while True:
command = input('Index, or "e" to end: ').lower()
if command == 'e':
break
try:
print(SpsState.from_index(int(command)))
except (ValueError, IndexError) as e:
print('Invalid input:', e)
def main() -> None:
input_state_str()
input_state_int()
if __name__ == '__main__':
main()
State, or "e" to end: 3
Invalid input: '3' is not a valid SpsState
State, or "e" to end: pre
SpsState.PreReleased
State, or "e" to end: e
Index, or "e" to end: 9
Invalid input: tuple index out of range
Index, or "e" to end: 1
SpsState.Release
Index, or "e" to end: e
mypy is OK with it:
Success: no issues found in 1 source file | {
"domain": "codereview.stackexchange",
"id": 44903,
"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, python-3.x",
"url": null
} |
beginner, rust
Title: Convert 9-digit integers to ISBNs
Question: Problem statement: The International Standard Book Number (ISBN) is a 10 digit code that uniquely specifies a book. The rightmost digit is a checksum digit which can be uniquely determined from the other 9 digits from the condition that \$d_1 + 2d_2 + 3d_3 + ... + 10d_{10}\$ must be a multiple of 11 (here \$d_i\$ denotes the \$\text{i}_{\text{th}}\$ digit from the right). The checksum digit \$d_1\$ can be any value from 0 to 10: the ISBN convention is to use the value X to denote 10. Write a program that takes a 9-digit integer digits as a command-line argument, computes the checksum, and prints the 10-digit ISBN number.
This is one of my self-imposed challenges in Rust to become better at it. The problem was taken from Sedgewick Exercise 1.3.35.
Here is my code:
use clap::Parser;
#[derive(Debug, Parser)]
struct Arguments {
#[arg(index = 1)]
digits: String,
}
fn main() {
let arguments = Arguments::parse();
let isbn = calculate_isbn(&arguments.digits);
println!("{}", isbn);
}
fn calculate_isbn(digits_string: &String) -> String {
let checksum = calculate_checksum(&digits_string);
let mut isbn = digits_string.clone();
match checksum {
10 => isbn.push_str("X"),
_ => isbn.push_str(&checksum.to_string()),
}
isbn
}
fn calculate_checksum(digits_string: &String) -> u32 {
let digits_vector = convert_string_to_vector(digits_string);
let checksum_vector = vec![10, 9, 8, 7, 6, 5, 4, 3, 2];
let dot_product: u32 = digits_vector
.iter()
.zip(checksum_vector.iter())
.map(|(x, y)| x * y)
.sum();
let mut checksum: u32 = 0;
for index in 0..=10 {
if (dot_product + index) % 11 == 0 {
checksum = index as u32;
break;
}
}
checksum
} | {
"domain": "codereview.stackexchange",
"id": 44904,
"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, rust",
"url": null
} |
beginner, rust
checksum
}
fn convert_string_to_vector(digits_string: &String) -> Vec<u32> {
let digits_vector = digits_string
.chars()
.map(|character| character.to_digit(10).unwrap())
.collect();
digits_vector
}
Is there any way that I can improve my code?
Answer: Don't use &String
in function parameters. It has virtually no use. Instead use &str, since it can be implicitly converted from &String, but not the other way around.
Handle errors
You currently happily unwrap every character.to_digit(10), though this may fail if e.g. letters are provided.
Check for valid input
The input should be a string of exactly 9 digits.
Your code happily accepts any amount of digits, though the result of their processing will not constitute a valid ISBN.
Represent the ISBN as a struct
So you can have an object that guarantees the representation of a valid ISBN.
Suggested:
Cargo.toml
[package]
name = "isbn"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "4.3.8", features = ["derive"] }
src/main.rs
use clap::Parser;
use isbn::Isbn;
use std::str::FromStr;
#[derive(Debug, Parser)]
struct Arguments {
#[arg(index = 1)]
digits: String,
}
fn main() {
let arguments = Arguments::parse();
match Isbn::from_str(arguments.digits.as_str()) {
Ok(isbn) => println!("The ISBN is: {isbn}"),
Err(error) => eprintln!("{error}"),
}
}
src/lib.rs
use std::fmt::{Display, Formatter};
use std::str::FromStr;
const FACTORS: [u8; 9] = [10, 9, 8, 7, 6, 5, 4, 3, 2];
#[derive(Debug)]
pub enum Error {
InvalidDigit(char),
InvalidLength(usize),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidDigit(chr) => write!(f, "Invalid digit: {chr}"),
Self::InvalidLength(len) => write!(f, "Invalid length: {len}"),
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44904,
"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, rust",
"url": null
} |
beginner, rust
#[derive(Debug)]
pub struct Isbn([u8; 10]);
impl Display for Isbn {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for digit in self.0 {
if digit == 10 {
write!(f, "X")?;
} else {
write!(f, "{digit}")?;
}
}
Ok(())
}
}
impl From<[u8; 9]> for Isbn {
fn from(value: [u8; 9]) -> Self {
Self([
value[0],
value[1],
value[2],
value[3],
value[4],
value[5],
value[6],
value[7],
value[8],
calculate_checksum(&value),
])
}
}
impl FromStr for Isbn {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::new();
for c in s.chars() {
if let Some(digit) = c.to_digit(10).and_then(|digit| u8::try_from(digit).ok()) {
digits.push(digit);
} else {
return Err(Error::InvalidDigit(c));
}
}
let array: [u8; 9] = match digits.try_into() {
Ok(array) => array,
Err(error) => return Err(Error::InvalidLength(error.len())),
};
Ok(Self::from(array))
}
}
fn calculate_checksum(digits: &[u8; 9]) -> u8 {
let dot_product: u32 = digits
.iter()
.zip(FACTORS)
.map(|(&x, y)| u32::from(x) * u32::from(y))
.sum();
for checksum in 0..=10u8 {
if (dot_product + u32::from(checksum)) % 11 == 0 {
return checksum;
}
}
0
}
Or, alternatively, if you want to only store the first 9 digits of the ISBN and calculate its checksum on the fly:
src/lib.rs
use std::fmt::{Display, Formatter};
use std::str::FromStr;
const FACTORS: [u8; 9] = [10, 9, 8, 7, 6, 5, 4, 3, 2];
#[derive(Debug)]
pub enum Error {
InvalidDigit(char),
InvalidLength(usize),
} | {
"domain": "codereview.stackexchange",
"id": 44904,
"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, rust",
"url": null
} |
beginner, rust
#[derive(Debug)]
pub enum Error {
InvalidDigit(char),
InvalidLength(usize),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidDigit(chr) => write!(f, "Invalid digit: {chr}"),
Self::InvalidLength(len) => write!(f, "Invalid length: {len}"),
}
}
}
#[derive(Debug)]
pub struct Isbn([u8; 9]);
impl Isbn {
#[must_use]
pub fn checksum(&self) -> u8 {
let dot_product: u32 = self
.0
.iter()
.zip(FACTORS)
.map(|(&x, y)| u32::from(x) * u32::from(y))
.sum();
for checksum in 0..=10u8 {
if (dot_product + u32::from(checksum)) % 11 == 0 {
return checksum;
}
}
0
}
}
impl Display for Isbn {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for digit in self.0 {
write!(f, "{digit}")?;
}
match self.checksum() {
10 => write!(f, "X"),
checksum => write!(f, "{checksum}"),
}
}
}
impl From<[u8; 9]> for Isbn {
fn from(value: [u8; 9]) -> Self {
Self(value)
}
}
impl FromStr for Isbn {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::new();
for c in s.chars() {
if let Some(digit) = c.to_digit(10).and_then(|digit| u8::try_from(digit).ok()) {
digits.push(digit);
} else {
return Err(Error::InvalidDigit(c));
}
}
let array: [u8; 9] = match digits.try_into() {
Ok(array) => array,
Err(error) => return Err(Error::InvalidLength(error.len())),
};
Ok(Self::from(array))
}
} | {
"domain": "codereview.stackexchange",
"id": 44904,
"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, rust",
"url": null
} |
beginner, rust
Ok(Self::from(array))
}
}
You can even optimize the storage space of the Isbn further by just storing its numerical value, which maxes out at 999999999 and thus fits into a u32:
src/lib.rs
use std::fmt::{Display, Formatter};
use std::str::FromStr;
const FACTORS: [u8; 9] = [10, 9, 8, 7, 6, 5, 4, 3, 2];
#[derive(Debug)]
pub enum Error {
InvalidDigit(char),
InvalidLength(usize),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidDigit(chr) => write!(f, "Invalid digit: {chr}"),
Self::InvalidLength(len) => write!(f, "Invalid length: {len}"),
}
}
}
#[derive(Debug)]
pub struct Isbn(u32);
impl Isbn {
#[must_use]
pub fn digits(&self) -> String {
self.0.to_string()
}
#[must_use]
pub fn checksum(&self) -> u8 {
let dot_product: u32 = self
.digits()
.chars()
.map(|c| c.to_digit(10).unwrap_or_else(|| unreachable!()))
.zip(FACTORS)
.map(|(x, y)| x * u32::from(y))
.sum();
for checksum in 0..=10u8 {
if (dot_product + u32::from(checksum)) % 11 == 0 {
return checksum;
}
}
0
}
fn from_digits(digits: &[u8]) -> Result<Self, Error> {
if digits.len() != 9 {
return Err(Error::InvalidLength(digits.len()));
}
Ok(Self(
digits
.iter()
.rev()
.enumerate()
.map(|(exponent, digit)| {
u32::from(*digit)
* 10u32.pow(u32::try_from(exponent).unwrap_or_else(|_| unreachable!()))
})
.sum(),
))
}
}
impl Display for Isbn {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.digits())?; | {
"domain": "codereview.stackexchange",
"id": 44904,
"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, rust",
"url": null
} |
beginner, rust
match self.checksum() {
10 => write!(f, "X"),
checksum => write!(f, "{checksum}"),
}
}
}
impl FromStr for Isbn {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::new();
for c in s.chars() {
if let Some(digit) = c.to_digit(10).and_then(|digit| u8::try_from(digit).ok()) {
digits.push(digit);
} else {
return Err(Error::InvalidDigit(c));
}
}
Self::from_digits(digits.as_slice())
}
}
Here I implemented from_digits() as a private method of Isbn and not via a TryFrom<&[u8]> implementation, since it would need additional checks to guarantee that each digit is in {0..=9} if it was exposed publicly where this prerequisite is not guaranteed. | {
"domain": "codereview.stackexchange",
"id": 44904,
"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, rust",
"url": null
} |
python, rust
Title: Verifying Why Python Rust Module is Running Slow
Question: I am working on converting some python code over to Rust, and I have come across a bit of a peculiarity in the way that my code is behaving. Namely, the module that I have written in Rust is much slower than the same code written in Python. I originally thought that this was due to the fact that the module that I was writing had a lot of overhead from converting the Python list object to a Rust vector but now I am not so sure. Even when I scale this for large grid graphs (400x400 or larger), the overhead seems to just scale with it, so there might be something else wrong with the code. Here is the bit that appears to be causing the issue:
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use rand::seq::SliceRandom;
use rand::thread_rng;
use std::collections::HashMap;
use pyo3::types::PyList;
fn current_component(n: usize, component_merge_dict: &mut HashMap<usize, usize>) -> usize
{
let mut nodeid = n;
let mut nodeids_to_update = Vec::with_capacity(component_merge_dict.len());
while let Some(&next_nodeid) = component_merge_dict.get(&nodeid)
{
if nodeid == next_nodeid { break; }
nodeids_to_update.push(nodeid);
nodeid = next_nodeid;
}
for nid in nodeids_to_update
{
component_merge_dict.insert(nid, nodeid);
}
nodeid
}
#[pyfunction]
fn rand_kruskal_memo(_py: Python,
py_node_list: &PyList,
py_edge_list: &PyList) -> PyResult<Vec<((i32, i32), (i32, i32))>>
{
let node_list: Vec<(i32, i32)> = py_node_list.extract()?;
let edge_list: Vec<((i32, i32), (i32, i32))> = py_edge_list.extract()?;
let mut tree_edge_list: Vec<((i32, i32), (i32, i32))> = Vec::with_capacity(node_list.len() - 1);
let mut edge_indices: Vec<usize> = (0..edge_list.len()).collect(); | {
"domain": "codereview.stackexchange",
"id": 44905,
"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, rust",
"url": null
} |
python, rust
let mut edge_indices: Vec<usize> = (0..edge_list.len()).collect();
edge_indices.shuffle(&mut rand::thread_rng());
let mut nodes_to_components_dict: HashMap<&(i32, i32), usize> = HashMap::new();
let mut component_merge_dict: HashMap<usize, usize> = HashMap::new();
node_list.iter().enumerate().into_iter().for_each(|(index, node)| {
nodes_to_components_dict.insert(node, index);
component_merge_dict.insert(index, index);
});
let mut num_components: usize = node_list.len();
let mut curr: usize = 0;
while num_components > 1
{
let this_edge: ((i32, i32), (i32, i32)) = edge_list[edge_indices[curr]];
curr += 1;
let component_1: &usize = nodes_to_components_dict.get(&this_edge.0).unwrap();
let component_num_1: usize = current_component(*component_1, &mut component_merge_dict);
let component_2: &usize = nodes_to_components_dict.get(&this_edge.1).unwrap();
let component_num_2: usize = current_component(*component_2, &mut component_merge_dict);
if component_num_1 != component_num_2
{
component_merge_dict.insert(component_num_1, component_num_2);
tree_edge_list.push(this_edge);
num_components -= 1;
}
}
Ok(tree_edge_list)
}
#[pymodule]
fn rusty_tree(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(rand_kruskal_memo, m)?)?;
Ok(())
} | {
"domain": "codereview.stackexchange",
"id": 44905,
"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, rust",
"url": null
} |
python, rust
I have also implemented a Union-Find method that seems to be suffering from the same issue, and I don't understand it. I also implemented both of these methods in C++ using Pybind11, and that code does not seem to have the conversion overhead issue that I am seeing here, so I am a bit confused as to what is going on. Admittedly, I am mainly a Python and C++ developer, so it is possible that I am just not accustomed to working with Rust quite yet and there is a simple fix that I am not aware of. Regardless, if someone wouldn't mind going over this and either telling me where I went wrong or telling me a more efficient way to define the bindings between Rust and python objects, I would greatly appreciate it. Thank you!
Answer: Rust defaults to a safer but slower hash function implementation. This page discusses the issue. Basically, Rust's function is designed to insure that you don't have too many collisions, even if a hostile party is trying to mess with your program. However, most of us aren't really in that situation and can benefit from a faster hash function. Python, on the other hand, relies really heavily on its hash function and makes sure that it is really fast. I suspect that your code spends almost all of its time looking up hashes and thus the hash lookup dominates the differences between Python and Rust.
You can solve this by using crates like rustc-hash, fnv, and ahash which provide alternatives to the standard hashmap which use faster hash functions. Alternately, you can try to restructure the algorithm to index into Vecs which will be much faster.
Also, make sure you are compiling in release mode. | {
"domain": "codereview.stackexchange",
"id": 44905,
"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, rust",
"url": null
} |
beginner, rust
Title: Simulate Monty Hall
Question: Problem statement: A contestant is presented with three doors. Behind one door is a valuable prize, behind the other two are gag gifts. After the contestant chooses a door, the host opens up one of the other two doors (never revealing the prize, of course). The contestant is then given the opportunity to switch to the other unopened door. Should the contestant do so? Write a program that takes an integer command-line argument number_of_trials, plays the game number_of_trials times using each of the two strategies (switch or do not switch) and print the chance of success for each strategy.
This is one of my self-imposed challenges in Rust to become better at it. The problem was taken from Sedgewick Exercise 1.3.42.
Here is my code:
use clap::Parser;
use rand::Rng;
use std::ops::RangeFrom;
use std::process;
const VALID_TRIAL_NUMBERS: RangeFrom<u32> = 1..;
#[derive(Debug, Parser)]
struct Arguments {
#[arg(index = 1)]
number_of_trials: u32,
}
fn main() {
let arguments = Arguments::parse();
if !VALID_TRIAL_NUMBERS.contains(&arguments.number_of_trials) {
eprintln!(
"Number of trials must be at least {}.",
VALID_TRIAL_NUMBERS.start,
);
process::exit(1);
}
let mut number_of_wins_with_change: u32 = 0;
let mut number_of_wins_without_change: u32 = 0;
for _ in 0..arguments.number_of_trials {
if simulate_with_change() {
number_of_wins_with_change += 1;
}
if simulate_without_change() {
number_of_wins_without_change += 1;
}
}
let win_probability_with_change: f64 =
(number_of_wins_with_change as f64) / (arguments.number_of_trials as f64);
let win_probability_without_change: f64 =
(number_of_wins_without_change as f64) / (arguments.number_of_trials as f64); | {
"domain": "codereview.stackexchange",
"id": 44906,
"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, rust",
"url": null
} |
beginner, rust
println!(
"Winning probabilities after {} trials:",
arguments.number_of_trials,
);
println!("With change: {}", win_probability_with_change);
println!("Without change: {}", win_probability_without_change);
}
fn simulate_with_change() -> bool {
let mut rng = rand::thread_rng();
let door_with_prize: u8 = rng.gen_range(1..=3);
let contestant_choice: u8 = rng.gen_range(1..=3);
if door_with_prize == contestant_choice {
false
} else {
true
}
}
fn simulate_without_change() -> bool {
let mut rng = rand::thread_rng();
let door_with_prize: u8 = rng.gen_range(1..=3);
let contestant_choice: u8 = rng.gen_range(1..=3);
if door_with_prize == contestant_choice {
true
} else {
false
}
}
Is there any way that I can improve my code?
Answer: Use linters
Use e.g. cargo clippy to lint your code.
Don't repeat yourself
simulate_without_change() and simulate_without_change() are nearly identical. They return the opposite boolean value. You can use this fact to make the one function return the inverse of the other:
fn simulate_with_change() -> bool {
!simulate_without_change()
}
fn simulate_without_change() -> bool {
let mut rng = rand::thread_rng();
let door_with_prize: u8 = rng.gen_range(1..=3);
let contestant_choice: u8 = rng.gen_range(1..=3);
if door_with_prize == contestant_choice {
true
} else {
false
}
}
Make use of boolean expressions
if door_with_prize == contestant_choice {
true
} else {
false
}
is redundant. You can rewrite it to:
door_with_prize == contestant_choice
Use variable interpolation
You can directly put variables in format strings:
println!("With change: {win_probability_with_change}");
println!("Without change: {win_probability_without_change}"); | {
"domain": "codereview.stackexchange",
"id": 44906,
"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, rust",
"url": null
} |
beginner, rust
Cast safely
Prefer from() and try_from() over casting via as.
In your current code casting u32 to f64 will work, but it may get lossy, if you change the types later on (e.g. to u64 or f32 respectively).
Using safe casting using from() will result in a compiler error if you'd do that instead of silently producing loss.
let win_probability_with_change: f64 =
f64::from(number_of_wins_with_change) / f64::from(arguments.number_of_trials);
let win_probability_without_change: f64 =
f64::from(number_of_wins_without_change) / f64::from(arguments.number_of_trials);
Outsource further
Currently your main() function actually runs the simulation.
Consider outsourcing that to an actual simulation function:
fn simulate_both(number_of_trials: u32) -> Result<(f64, f64), String> {
if !VALID_TRIAL_NUMBERS.contains(&number_of_trials) {
return Err(format!(
"Number of trials must be at least {}.",
VALID_TRIAL_NUMBERS.start
));
}
let mut number_of_wins_with_change: u32 = 0;
let mut number_of_wins_without_change: u32 = 0;
for _ in 0..number_of_trials {
if simulate_with_change() {
number_of_wins_with_change += 1;
}
if simulate_without_change() {
number_of_wins_without_change += 1;
}
}
let win_probability_with_change: f64 =
f64::from(number_of_wins_with_change) / f64::from(number_of_trials);
let win_probability_without_change: f64 =
f64::from(number_of_wins_without_change) / f64::from(number_of_trials);
Ok((win_probability_with_change, win_probability_without_change))
}
Putting it all together
We can put all of the above together and use simulate() in main() by using the let else syntax as introduced in Rust 1.65:
use clap::Parser;
use rand::Rng;
use std::ops::RangeFrom;
use std::process;
const VALID_TRIAL_NUMBERS: RangeFrom<u32> = 1..; | {
"domain": "codereview.stackexchange",
"id": 44906,
"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, rust",
"url": null
} |
beginner, rust
const VALID_TRIAL_NUMBERS: RangeFrom<u32> = 1..;
#[derive(Debug, Parser)]
struct Arguments {
#[arg(index = 1)]
number_of_trials: u32,
}
fn main() {
let arguments = Arguments::parse();
let Ok((win_probability_with_change, win_probability_without_change)) =
simulate_both(arguments.number_of_trials) else
{
eprintln!(
"Number of trials must be at least {}.",
VALID_TRIAL_NUMBERS.start,
);
process::exit(1);
};
println!(
"Winning probabilities after {} trials:",
arguments.number_of_trials,
);
println!("With change: {win_probability_with_change}");
println!("Without change: {win_probability_without_change}");
}
fn simulate_both(number_of_trials: u32) -> Result<(f64, f64), String> {
if !VALID_TRIAL_NUMBERS.contains(&number_of_trials) {
return Err(format!(
"Number of trials must be at least {}.",
VALID_TRIAL_NUMBERS.start
));
}
let mut number_of_wins_with_change: u32 = 0;
let mut number_of_wins_without_change: u32 = 0;
for _ in 0..number_of_trials {
if simulate_with_change() {
number_of_wins_with_change += 1;
}
if simulate_without_change() {
number_of_wins_without_change += 1;
}
}
let win_probability_with_change: f64 =
f64::from(number_of_wins_with_change) / f64::from(number_of_trials);
let win_probability_without_change: f64 =
f64::from(number_of_wins_without_change) / f64::from(number_of_trials);
Ok((win_probability_with_change, win_probability_without_change))
}
fn simulate_with_change() -> bool {
!simulate_without_change()
}
fn simulate_without_change() -> bool {
let mut rng = rand::thread_rng();
let door_with_prize: u8 = rng.gen_range(1..=3);
let contestant_choice: u8 = rng.gen_range(1..=3);
door_with_prize == contestant_choice
} | {
"domain": "codereview.stackexchange",
"id": 44906,
"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, rust",
"url": null
} |
beginner, rust
door_with_prize == contestant_choice
}
More optimization
You can outsource and use a single ThreadRng instance and pass it to the functions, so it does not need to be re-initialized on every function call:
use clap::Parser;
use rand::rngs::ThreadRng;
use rand::Rng;
use std::ops::RangeFrom;
use std::process;
const VALID_TRIAL_NUMBERS: RangeFrom<u32> = 1..;
#[derive(Debug, Parser)]
struct Arguments {
#[arg(index = 1)]
number_of_trials: u32,
}
fn main() {
let arguments = Arguments::parse();
let mut rng = rand::thread_rng();
let Ok((win_probability_with_change, win_probability_without_change)) =
simulate_both(arguments.number_of_trials, &mut rng) else
{
eprintln!(
"Number of trials must be at least {}.",
VALID_TRIAL_NUMBERS.start,
);
process::exit(1);
};
println!(
"Winning probabilities after {} trials:",
arguments.number_of_trials,
);
println!("With change: {win_probability_with_change}");
println!("Without change: {win_probability_without_change}");
}
fn simulate_both(number_of_trials: u32, rng: &mut ThreadRng) -> Result<(f64, f64), String> {
if !VALID_TRIAL_NUMBERS.contains(&number_of_trials) {
return Err(format!(
"Number of trials must be at least {}.",
VALID_TRIAL_NUMBERS.start
));
}
let mut number_of_wins_with_change: u32 = 0;
let mut number_of_wins_without_change: u32 = 0;
for _ in 0..number_of_trials {
if simulate_with_change(rng) {
number_of_wins_with_change += 1;
}
if simulate_without_change(rng) {
number_of_wins_without_change += 1;
}
}
let win_probability_with_change: f64 =
f64::from(number_of_wins_with_change) / f64::from(number_of_trials);
let win_probability_without_change: f64 =
f64::from(number_of_wins_without_change) / f64::from(number_of_trials); | {
"domain": "codereview.stackexchange",
"id": 44906,
"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, rust",
"url": null
} |
beginner, rust
Ok((win_probability_with_change, win_probability_without_change))
}
fn simulate_with_change(rng: &mut ThreadRng) -> bool {
!simulate_without_change(rng)
}
fn simulate_without_change(rng: &mut ThreadRng) -> bool {
rng.gen_range(1..=3) == rng.gen_range(1..=3)
}
Note that I also removed the redundant temporary variables in simulate_without_change().
Consider using filter and map functions
... instead of a for-loop.
This surely is opinionated, but I like this more:
fn simulate_both(number_of_trials: u32, rng: &mut ThreadRng) -> Result<(f64, f64), String> {
if !VALID_TRIAL_NUMBERS.contains(&number_of_trials) {
return Err(format!(
"Number of trials must be at least {}.",
VALID_TRIAL_NUMBERS.start
));
}
let Ok(number_of_wins_with_change) = u32::try_from(
(0..number_of_trials)
.map(|_| simulate_with_change(rng))
.filter(|b| *b)
.count(),
) else {
return Err("Amount of wins with change is out of bounds.".to_string());
};
let Ok(number_of_wins_without_change) = u32::try_from(
(0..number_of_trials)
.map(|_| simulate_without_change(rng))
.filter(|b| *b)
.count(),
) else {
return Err("Amount of wins without change is out of bounds.".to_string());
};
Ok((
f64::from(number_of_wins_with_change) / f64::from(number_of_trials),
f64::from(number_of_wins_without_change) / f64::from(number_of_trials),
))
}
It's also possible to reduce the code to one sole simulation function by inlining the now trivial test:
fn simulate_both(number_of_trials: u32, rng: &mut ThreadRng) -> Result<(f64, f64), String> {
if !VALID_TRIAL_NUMBERS.contains(&number_of_trials) {
return Err(format!(
"Number of trials must be at least {}.",
VALID_TRIAL_NUMBERS.start
));
} | {
"domain": "codereview.stackexchange",
"id": 44906,
"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, rust",
"url": null
} |
beginner, rust
let Ok(number_of_wins_with_change) = u32::try_from(
(0..number_of_trials)
.map(|_| rng.gen_range(1..=3) != rng.gen_range(1..=3))
.filter(|b| *b)
.count(),
) else {
return Err("Amount of wins with change is out of bounds.".to_string());
};
let Ok(number_of_wins_without_change) = u32::try_from(
(0..number_of_trials)
.map(|_| rng.gen_range(1..=3) == rng.gen_range(1..=3))
.filter(|b| *b)
.count(),
) else {
return Err("Amount of wins without change is out of bounds.".to_string());
};
Ok((
f64::from(number_of_wins_with_change) / f64::from(number_of_trials),
f64::from(number_of_wins_without_change) / f64::from(number_of_trials),
))
} | {
"domain": "codereview.stackexchange",
"id": 44906,
"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, rust",
"url": null
} |
python, image
Title: Analyzing Product Photography Quality: Metrics Calculation -python
Question: I am working on analyzing product photography data on the website and would like to gather feedback on my approach. The goal is to calculate various image metrics to assess the quality of product photos. I have written the following code to calculate these metrics and classify the image quality:
import pandas as pd
import numpy as np
from PIL import Image
from skimage.exposure import is_low_contrast
from sklearn.cluster import KMeans
from skimage.measure import shannon_entropy
import cv2
# Load the input image from disk
image = Image.open("blue_dress.JPG")
# Calculate the contrast using the low contrast function
low_contrast_threshold = 0.35
is_low_contrast_value = is_low_contrast(np.array(image), low_contrast_threshold)
# Calculate the image metrics
contrast = np.std(np.array(image))
brightness = np.mean(np.array(image))
sharpness = cv2.Laplacian(np.array(image), cv2.CV_64F).var()
entropy = shannon_entropy(np.array(image))
color_difference = np.max(np.array(image)) - np.min(np.array(image))
color_histogram = np.histogram(np.array(image), bins=256, range=(0, 255))
color_saturation = np.mean(color_histogram[0]) / 255
image_edge_detection = np.mean(cv2.Laplacian(np.array(image), cv2.CV_64F))
image_noise = np.var(np.array(image))
# Convert the image to numpy array
image_array = np.array(image)
# Reshape the image array
reshaped_image_array = image_array.reshape(-1, image_array.shape[-1])
# Perform K-means clustering
num_clusters = 2
kmeans = KMeans(n_clusters=num_clusters)
kmeans.fit(reshaped_image_array)
# Assign labels to each pixel in the image
labels = kmeans.labels_
# Calculate the centroid values for each cluster
cluster_centers = kmeans.cluster_centers_ | {
"domain": "codereview.stackexchange",
"id": 44907,
"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, image",
"url": null
} |
python, image
# Calculate the centroid values for each cluster
cluster_centers = kmeans.cluster_centers_
# Calculate the foreground/background similarity
foreground_label = np.argmax(np.bincount(labels))
foreground_background_similarity = np.mean(np.abs(cluster_centers[foreground_label] - cluster_centers[1 - foreground_label]))
# Rescale the similarity value to the range of 0-100
foreground_background_similarity_rescaled = np.clip(foreground_background_similarity, 0, 100)
# Define thresholds for classification
contrast_thresholds = {'low': (0, 35), 'normal': (35, 60), 'high': (60, float('inf'))}
brightness_thresholds = {'low': (0, 100), 'normal': (100, 200), 'high': (200, 255)}
sharpness_thresholds = {'low': (0, 100), 'normal': (100, 200), 'high': (200, float('inf'))}
color_difference_thresholds = {'low': (0, 20), 'normal': (20, 40), 'high': (40, float('inf'))}
color_saturation_thresholds = {'low': (0.2, 0.5), 'normal': (0.5, 0.8), 'high': (0.8, 1)}
image_noise_thresholds = {'low': (20, 50), 'normal': (50, 80), 'high': (80, 100)}
def classify_value(value, thresholds):
for label, (lower, upper) in thresholds.items():
if lower <= value < upper:
return label
return 'Unknown'
# Create a dataframe with image metrics
data = {
'Contrast': [contrast],
'Brightness': [brightness],
'Sharpness': [sharpness],
'Entropy': [entropy],
'Color Difference': [color_difference],
'Color Saturation': [color_saturation],
'Foreground_Background_Similarity': [foreground_background_similarity_rescaled],
'Image Noise': [image_noise],
'Image Edge Detection': [image_edge_detection],
}
df = pd.DataFrame(data) | {
"domain": "codereview.stackexchange",
"id": 44907,
"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, image",
"url": null
} |
python, image
df = pd.DataFrame(data)
# Apply classification
classifications = {
'Contrast': (contrast_thresholds, 'Contrast_Classification'),
'Brightness': (brightness_thresholds, 'Brightness_Classification'),
'Sharpness': (sharpness_thresholds, 'Sharpness_Classification'),
'Color Difference': (color_difference_thresholds, 'Color_Difference_Classification'),
'Color Saturation': (color_saturation_thresholds, 'Color_Saturation_Classification'),
'Image Noise': (image_noise_thresholds, 'Image_Noise_Classification'),
}
for column, (thresholds, classification_column) in classifications.items():
df[classification_column] = df[column].apply(lambda x: classify_value(x, thresholds))
def determine_image_quality(row):
if row['Contrast_Classification'] == 'Low' or \
row['Brightness_Classification'] == 'Low' or \
row['Sharpness_Classification'] == 'Low' or \
row['Entropy'] <= 1 or \
row['Foreground_Background_Similarity'] >= 90:
return 'Poor'
elif row['Contrast_Classification'] == 'High' and \
row['Brightness_Classification'] == 'High' and \
row['Sharpness_Classification'] == 'High' and \
row['Entropy'] > 3 and \
row['Foreground_Background_Similarity'] <= 30:
return 'Excellent'
else:
return 'Good'
df['Image_Quality_Label'] = df.apply(determine_image_quality, axis=1)
df | {
"domain": "codereview.stackexchange",
"id": 44907,
"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, image",
"url": null
} |
python, image
df['Image_Quality_Label'] = df.apply(determine_image_quality, axis=1)
df
In this code, I load an input image and calculate metrics such as contrast, brightness, sharpness, entropy, color difference, color saturation, foreground/background similarity, image noise, and image edge detection. Please have a look at the formulas.
I then create a dataframe to store these metrics and apply classifications based on defined thresholds.
Furthermore, I have added a function to determine the overall image quality based on the calculated metrics. The function assigns a label of "Poor," "Good," or "Excellent" depending on the thresholds and criteria defined.
I would appreciate any advice or suggestions on the following points:
Are the selected metrics appropriate for assessing product
photography quality?
Are there any additional metrics or factors that I should consider?
Are the thresholds and classifications reasonable? Should I adjust them?
Is there a more efficient or optimized way to perform these calculations?
Any other ideas, tips, or improvements you can suggest?
please see the test image
Thank you for your time and expertise. I look forward to your valuable input on this matter.
Answer: Since you already have a review of the code, I’ll look at the image processing specifics.
sharpness = cv2.Laplacian(np.array(image), cv2.CV_64F).var()
The variance of the Laplacian is not necessary related to sharpness. A noisy image will have a larger value than a noise-free image, even if equally sharp. An image with a larger (flat) background will have a lower value, even if perfectly in focus.
There is no good way to estimate sharpness without knowing what was imaged. What you have is a proxy that correlates with sharpness for sufficiently similar images, but is not valid in general as a measure of sharpness.
color_difference = np.max(np.array(image)) - np.min(np.array(image)) | {
"domain": "codereview.stackexchange",
"id": 44907,
"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, image",
"url": null
} |
python, image
I’m not sure how the name applies, you’re not looking at colors, you’re looking at the difference between the largest value and the smallest one, could be the large value of the green channel in a pixel, and the the small value of the red channel in the same pixel. For example an image that is completely green would have a large color difference according to this measure, even though all pixels have the same color.
If you want to compute the largest difference in colors, compute the Euclidean distance between each pair of pixels (n^2 comparisons if the image has n pixels), preferably in a color space such as Lab, then pick the largest result.
color_histogram = np.histogram(np.array(image), bins=256, range=(0, 255))
Again, this is a histogram of values where you combine all channels. I would expect you to compute three histograms (one for each channel), or a single 3D histogram (an actual color histogram).
color_saturation = np.mean(color_histogram[0]) / 255
The histogram contains counts of the pixels for each intensity. The mean of these counts is always the number of pixels divided by 256 (the number of bins). So this quantifies the image size.
To measure saturation, convert each pixel to a saturation value, for example by converting to HSV color space and taking the S channel, then compute the mean of these values.
image_edge_detection = np.mean(cv2.Laplacian(np.array(image), cv2.CV_64F))
The mean of the Laplacian I guess is close to 0 for an image with larger flat areas and transitions between them. Only thin lines (ridges) would increase or decrease the mean value, depending on their color — dark and bright lines would cancel out in this measure. I’m not sure what name you should give this, but it’s not related to edges.
Note that you are computing the Laplacian here again, you should re-use the earlier result.
image_noise = np.var(np.array(image)) | {
"domain": "codereview.stackexchange",
"id": 44907,
"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, image",
"url": null
} |
python, image
You computed the standard deviation earlier, and called it contrast. The variance is the square of the standard deviation, how is that noise?
To estimate noise, first identify flat regions in the image, then compute their variance. For example the function dip.EstimateNoiseVariance() in DIPlib does this (disclosure: I’m an author of DIPlib).
You look for two clusters using k-means, then:
foreground_label = np.argmax(np.bincount(labels))
foreground_background_similarity = np.mean(np.abs(cluster_centers[foreground_label] - cluster_centers[1 - foreground_label]))
First of all, that second line is quite long. Try to break it up across lines, or do part of the computation in a separate statement.
But more importantly, you first assume that the larger cluster is the foreground, even though in the example you give the background is clearly larger. Then you go through great lengths to find the other cluster, subtract the two centroids, and take the absolute value of the result. You’d get the same result no matter which order you pick for these centroids. So you can thus simply do:
diff = cluster_centers[0] - cluster_centers[1]
foreground_background_similarity = np.mean(np.abs(diff)) | {
"domain": "codereview.stackexchange",
"id": 44907,
"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, image",
"url": null
} |
c++, boost, cmake
Title: API Implementation guidance and improvement
Question: I have recently made significant progress in overcoming beginner barriers related to using Git, CMake, libraries, and successfully implementing an API in C++. Despite my achievements, I acknowledge that there is room for improvement and would greatly appreciate someone's opinion on my code. As a beginner, I am open to constructive criticism and value your expertise in identifying areas where I can enhance my implementation. Your feedback and guidance are invaluable to my growth as a programmer. Thank you in advance for your insights and recommendations!
main.cpp
#include <iostream>
#include <string>
#include <memory>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp>
#include "json.hpp"
namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = net::ip::tcp;
namespace ssl = net::ssl;
using json = nlohmann::json;
// Abstract HTTP Client
class HttpClient {
public:
virtual ~HttpClient() = default;
virtual void sendGetRequest(const std::string& apiEndpoint) = 0;
};
// Concrete HTTP Client implementation
class RiotHttpClient : public HttpClient {
public:
RiotHttpClient(const std::string& apiKey) : apiKey_(apiKey), ssl_context_(ssl::context::tlsv12_client) {}
void sendGetRequest(const std::string& apiEndpoint) override {
try {
net::io_context io_context;
tcp::resolver resolver(io_context);
auto endpoints = resolver.resolve("na1.api.riotgames.com", "https");
ssl::stream<tcp::socket> stream(io_context, ssl_context_);
net::connect(stream.next_layer(), endpoints);
stream.handshake(ssl::stream_base::client); | {
"domain": "codereview.stackexchange",
"id": 44908,
"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++, boost, cmake",
"url": null
} |
c++, boost, cmake
std::string requestUrl = apiEndpoint + "?api_key=" + apiKey_;
http::request<http::string_body> request{http::verb::get, requestUrl, 11};
request.set(http::field::host, "na1.api.riotgames.com");
request.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
http::write(stream, request);
beast::flat_buffer buffer;
http::response<http::dynamic_body> response;
http::read(stream, buffer, response);
json responseData = json::parse(beast::buffers_to_string(response.body().data()));
processResponse(responseData);
} catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
}
}
void processResponse(const json& response) {
// Process the JSON response according to the specific API endpoint
std::cout << "Processing JSON response: " << response.dump() << std::endl;
}
private:
std::string apiKey_;
ssl::context ssl_context_;
};
// Abstract API
class RiotApi {
protected:
std::shared_ptr<HttpClient> httpClient_;
public:
virtual ~RiotApi() = default;
virtual void makeRequest() = 0;
void setHttpClient(const std::shared_ptr<HttpClient>& httpClient) {
httpClient_ = httpClient;
}
};
// Concrete API implementation
class SummonerApi : public RiotApi {
public:
void makeRequest() override {
if (httpClient_) {
httpClient_->sendGetRequest("/lol/summoner/v4/summoners/by-name/");
}
}
};
class ChampionApi : public RiotApi {
public:
void makeRequest() override {
if (httpClient_) {
httpClient_->sendGetRequest("/lol/platform/v3/champion-rotations");
}
}
}; | {
"domain": "codereview.stackexchange",
"id": 44908,
"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++, boost, cmake",
"url": null
} |
c++, boost, cmake
int main() {
std::string apiKey = "";
// Create the API and HTTP client objects
//std::shared_ptr<RiotApi> summonerApi = std::make_shared<SummonerApi>();
//std::shared_ptr<HttpClient> httpClient = std::make_shared<RiotHttpClient>(apiKey);
// Associate the HTTP client with the API
//summonerApi->setHttpClient(httpClient);
// Make the API request
//summonerApi->makeRequest();
// Create the API and HTTP client objects
std::shared_ptr<RiotApi> championApi = std::make_shared<ChampionApi>();
std::shared_ptr<HttpClient> httpClient = std::make_shared<RiotHttpClient>(apiKey);
// Associate the HTTP client with the API
championApi->setHttpClient(httpClient);
// Make the API request
championApi->makeRequest();
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.26.4)
project (myproject)
find_package(Boost COMPONENTS system REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(main main.cpp)
target_link_libraries(main LINK_PUBLIC ${Boost_LIBRARIES} ws2_32 ssl crypto)
target_sources(main PRIVATE json.hpp)
I have been actively exploring the website "Refactoring Guru - Design Patterns in C++" to gain insights and ideas on how I can effectively utilize these design patterns in my specific use case. I have a set of features that I want to develop, but they rely on external libraries such as OpenCV. This aspect makes me feel like it might be overwhelming to tackle all of these components at once. Additionally, I'm interested in learning about best practices for CMakeLists.txt files and various techniques for linking libraries. With so much to explore and absorb, I sometimes feel a bit lost even after overcoming initial challenges.
Answer: cmake | {
"domain": "codereview.stackexchange",
"id": 44908,
"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++, boost, cmake",
"url": null
} |
c++, boost, cmake
Answer: cmake
Your cmake version is too high. If you are not using all the features of the newer version, consider downgrading the required version. I think 3.12 should work here. But, I would go with 3.4 and use some of the goodies to improve my CMakeLists.txt
Use modern cmake pattern, mainly use import targets that are namespaced. Check this example.
Architecture
You are over using dynamic polymorphism where a simple class or compile time polymorphism is needed.
HttpClient: Do you really need a class for RiotHttpClient that inherets from HttpClient? I would say no. The only difference between a Riot games http client and an Activision http clien (for example) is which server it connects to.
Similarly, you dont need runtime polymorphism in your RiotApi.In C++, you have different options for polymorphism. Dynamic polymorphism is a good idea when you dont know at compile time which object you are going to get. One example would be when a user can select a bunch of algorithms for a drop downlist. In case of a http requests, I guess the programmer knows what he has to call. For example, when writing the leaderboard code the programmer uses the champions api. In such cases, use compile time polymorphism.
Where is the processResponse function. Is it same for all the requests? If not is it same for a request regardless of where it was called from? I would suggest seperate the act of sending a get request and processing it. Why not have the sendGetRequest return the response and let the caller decide what to do with the request. In fact, I would just go ahead and rename the method to get.
Style | {
"domain": "codereview.stackexchange",
"id": 44908,
"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++, boost, cmake",
"url": null
} |
c++, boost, cmake
Style
Dont have the HttpClient in main.cpp. Create a seperate h/cpp file pair for that.
In constructors, take strings by value and move them into place, instead of taking them by const references.
Please dont have commented code blocks in your commits.
Comments should say why you are doing something not what you are doing. People who read your code know how to read code so its redudant.
Prefer auto variableName = Type{arguments} syntax for creating variables. This way it is hard to have uninitialized variables.
Updated Code
#include <iostream>
#include <string>
#include <memory>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp>
#include <nlohmann/json.hpp>
namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = net::ip::tcp;
namespace ssl = net::ssl;
using json = nlohmann::json;
class HttpClient {
public:
HttpClient(std::string const & serverName, std::string apiKey)
: apiKey_(apiKey)
, sslContext_(ssl::context::tlsv12_client)
, stream_(io_context_, sslContext_){
net::io_context io_context;
tcp::resolver resolver(io_context);
auto const endpoints = resolver.resolve(serverName, "https");
ssl::stream<tcp::socket> stream(io_context, sslContext_);
net::connect(stream.next_layer(), endpoints);
stream.handshake(ssl::stream_base::client);
}
template<typename GetRequest>
typename GetRequest::Response get() {
std::string requestUrl = std::string{GetRequest::endPoint} + "?api_key=" + apiKey_;
http::request<http::string_body> request{http::verb::get, requestUrl, 11};
request.set(http::field::host, "na1.api.riotgames.com");
request.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
http::write(stream_, request); | {
"domain": "codereview.stackexchange",
"id": 44908,
"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++, boost, cmake",
"url": null
} |
c++, boost, cmake
beast::flat_buffer buffer;
http::response<http::dynamic_body> response;
http::read(stream_, buffer, response);
auto json = json::parse(beast::buffers_to_string(response.body().data()));
return json.template get<typename GetRequest::Response>();
}
private:
net::io_context io_context_ = {};
std::string apiKey_;
ssl::context sslContext_;
ssl::stream<tcp::socket> stream_;
};
namespace RiotApi {
namespace Get {
struct Summoner {
static constexpr char endPoint[] = "/lol/summoner/v4/summoners/by-name/";
struct Response {
std::string name;
};
};
void from_json(json const & j, Summoner::Response& r){
r.name = j.at("name");
}
struct Champion {
static constexpr char endPoint[] = "/lol/platform/v3/champion-rotations";
struct Response {
std::vector<int> freeChampionIds;
std::vector<int> freeChampionIdsForNewPlayers;
int maxNewPlayerLevel;
};
};
void from_json(json const & j, Champion::Response& r){
j.at("freeChampionIds").get_to(r.freeChampionIds);
j.at("freeChampionIdsForNewPlayers").get_to(r.freeChampionIdsForNewPlayers);
j.at("maxNewPlayerLevel").get_to(r.maxNewPlayerLevel);
}
} // namespace Get
} // namespace RiotApi
int main() {
auto apiKey = std::string{""};
auto httpClient = HttpClient{"na1.api.riotgames.com", apiKey};
auto summonerResponse = httpClient.get<RiotApi::Get::Summoner>();
std::cout << "Summoned by" << summonerResponse.name << std::endl;
auto championResponse = httpClient.get<RiotApi::Get::Champion>();
return 0;
}
``` | {
"domain": "codereview.stackexchange",
"id": 44908,
"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++, boost, cmake",
"url": null
} |
c#, .net, hash-map
Title: A hierarchical dictionary for dotnet | {
"domain": "codereview.stackexchange",
"id": 44909,
"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, hash-map",
"url": null
} |
c#, .net, hash-map
Question: Is there an existing class in .Net for representing and querying hierarchical data; i.e. providing methods which allow you to test whether one item is an ancestor or descendant of another, or to provide a way to fetch all ancestors/descendants recursively from a given object?
Failing that, I've created a very basic example to illustrate the sort of thing I'm after... I've not done any optimisation as I'm hoping this is a common enough requirement that there's already something OOTB or a package I could use instead of rolling my own; though so far I haven't found one. I'd welcome feedback on this approach in case I've missed any good tricks which may improve this approach. Also, I realise this current approach allows the dictionary's key to be a mutable type, which may lead to issues with some use cases, so if there's a way to enforce the type to be immutable that would be helpful.
public class HierarchicalNode<T> where T : IComparable
{
public T Value {get;}
public HierarchicalNode<T> Parent {get;}
public List<HierarchicalNode<T>> Children {get;}
public HierarchicalNode(T value, HierarchicalNode<T> parent = null)
{
this.Children = new List<HierarchicalNode<T>>();
this.Value = value;
this.Parent = parent;
parent?.Children.Add(this);
}
public bool IsAncestorOf(HierarchicalNode<T> item, bool includeSelf = true)
{
return item != null
&& (
includeSelf && this.Value.CompareTo(item.Value) == 0
|| IsAncestorOf(item.Parent)
)
;
}
public bool IsDescendantOf(HierarchicalNode<T> item, bool includeSelf = true)
{
return item != null
&& (
includeSelf && this.Value.CompareTo(item.Value) == 0
|| (this.Parent?.IsDescendantOf(item) ?? false)
)
;
}
public bool IsRoot()
{
return this.Parent == null;
} | {
"domain": "codereview.stackexchange",
"id": 44909,
"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, hash-map",
"url": null
} |
c#, .net, hash-map
;
}
public bool IsRoot()
{
return this.Parent == null;
}
public IEnumerable<T> GetDescendants(bool includeSelf = false)
{
if (includeSelf)
{
yield return Value;
}
foreach (var child in Children)
{
yield return child.Value;
foreach (var descendant in child.GetDescendants())
{
yield return descendant;
}
}
}
public IEnumerable<T> GetAncestors(bool includeSelf = false)
{
if (includeSelf)
{
yield return Value;
}
foreach (var ancestor in this?.Parent?.GetAncestors(true) ?? Enumerable.Empty<T>())
{
yield return ancestor;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44909,
"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, hash-map",
"url": null
} |
c#, .net, hash-map
# Note: I'm including a dictionary so there's an easy way to get all values without having to traverse the graph / so we can represent islands of disconnected data; i.e. if there are several root nodes.
public class HierarchicalDictionary<Key, T>
where T : IComparable
where Key: class
{
private Dictionary<Key, HierarchicalNode<T>> dict = new Dictionary<Key, HierarchicalNode<T>>();
private Func<T, Key> getKey;
Func<T, Key> getParentKey;
public HierarchicalDictionary(Func<T, Key> getKey, Func<T, Key> getParentKey)
{
this.getKey = getKey;
this.getParentKey = getParentKey;
}
public void Add(T item) {
if (item == null) throw new ArgumentNullException(nameof(item));
var key = getKey(item);
var parentKey = getParentKey(item);
if (parentKey != null && !dict.Keys.Contains(parentKey)) {
throw new InvalidOperationException($"Parent must exist before child can be added. Key [{key}]. ParentKey [{parentKey}]");
}
if (dict.Keys.Contains(key)) {
throw new InvalidOperationException($"An object with the key [{key}] already exists");
}
var parent = parentKey == null ? null : dict[parentKey];
var node = new HierarchicalNode<T>(item, parent);
dict.Add(key, node);
}
public void AddRange(IEnumerable<T> item)
{
foreach (var i in item)
{
this.Add(i);
}
}
public bool IsAncestorOfByKey(Key a, Key b, bool includeSelf = true)
{
var objA = dict[a];
var objB = dict[b];
return objA.IsAncestorOf(objB);
}
public bool IsDescendantOfByKey(Key a, Key b, bool includeSelf = true)
{
var objA = dict[a];
var objB = dict[b];
return objA.IsDescendantOf(objB);
}
public IEnumerable<T> GetDescendantsOfByKey(Key key)
{
return dict[key].GetDescendants();
}
public IEnumerable<T> GetAncestorsOfByKey(Key key)
{ | {
"domain": "codereview.stackexchange",
"id": 44909,
"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, hash-map",
"url": null
} |
c#, .net, hash-map
}
public IEnumerable<T> GetAncestorsOfByKey(Key key)
{
return dict[key].GetAncestors();
}
} | {
"domain": "codereview.stackexchange",
"id": 44909,
"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, hash-map",
"url": null
} |
c#, .net, hash-map
Example Implementation: DotNet Fiddle
void Main()
{
var employees = new Employee[]
{
new ("bigcheese@example.com","Brie Emmental", null),
new ("assistant@example.com","Adrian Steward","bigcheese@example.com"),
new ("manager@example.com","Max Power", "bigcheese@example.com"),
new ("junior@example.com","Robert Ott","manager@example.com"),
new ("subordinate@example.com","Anne Droid","manager@example.com"),
new ("lackey@example.com","Simon Borg","subordinate@example.com"),
new ("personA@different.example.com","Person A",null),
new ("personB@different.example.com","Person B","personA@different.example.com"),
new ("personC@different.example.com","Person C","personB@different.example.com"),
new ("personX@different.example.com","Person X","personC@different.example.com"),
new ("personY@different.example.com","Person Y","personC@different.example.com"),
new ("personZ@different.example.com","Person Z","personC@different.example.com")
};
var roster = new HierarchicalDictionary<string, Employee>(x => x.Id, x => x.ManagerId);
roster.AddRange(employees);
foreach (var a in employees)
{
foreach (var b in employees)
{
var relationship = roster.IsAncestorOfByKey(a.Id, b.Id) ? "manages" : "does not manage";
Console.WriteLine($"[{a.Name}] {relationship} [{b.Name}]");
relationship = roster.IsDescendantOfByKey(a.Id, b.Id) ? "reports to" : "does not report to";
Console.WriteLine($"[{a.Name}] {relationship} [{b.Name}]");
}
}
Console.WriteLine();
foreach (var descendant in roster.GetDescendantsOfByKey("manager@example.com"))
{
Console.WriteLine($"Employees Of Max: [{descendant.Name}]");
}
Console.WriteLine();
foreach (var descendant in roster.GetAncestorsOfByKey("junior@example.com"))
{ | {
"domain": "codereview.stackexchange",
"id": 44909,
"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, hash-map",
"url": null
} |
c#, .net, hash-map
foreach (var descendant in roster.GetAncestorsOfByKey("junior@example.com"))
{
Console.WriteLine($"Managers Of Robert: [{descendant.Name}]");
}
Console.WriteLine("End of demo");
} | {
"domain": "codereview.stackexchange",
"id": 44909,
"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, hash-map",
"url": null
} |
c#, .net, hash-map
public class Employee: IComparable
{
public string Id {get;}
public string Name {get;}
public string ManagerId {get;}
public Employee (string id, string name, string managerId)
{
Id = id;
Name = name;
ManagerId = managerId;
}
public int CompareTo(object obj) {
return this.Id.CompareTo((obj as Employee)?.Id);
}
}
Answer: This is a nice implementation. Its written in a way that it is easy to read and understand.
That being said, let's face some issues :-)
HierarchicalDictionary<Key, T>
AddRange() here I would expect the parameter-name to be in the plural form because you add a range of items and the type of the parameter is IEnumerable. For my pesonal taste I would use T instead of var as well.
public void AddRange(IEnumerable<T> items)
{
foreach (T item in items)
{
this.Add(item);
}
}
Add()
Instead of checking if a key exists and later on accessing the key you should use TryGetValue() because using dict[key] is just doing this as well and hence is called twice.
Checking if the passed key exists should be done after the call to getKey() to return early. No need to do anything else if thekey is in the dictionary.
public void Add(T item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
var key = getKey(item);
if (dict.Keys.Contains(key))
{
throw new InvalidOperationException($"An object with the key [{key}] already exists");
}
var parentKey = getParentKey(item);
HierarchicalNode<T> parent = null;
if (parentKey != null && !dict.TryGetValue(parentKey, out parent)) //!dict.Keys.Contains(parentKey))
{
throw new InvalidOperationException($"Parent must exist before child can be added. Key [{key}]. ParentKey [{parentKey}]");
}
var node = new HierarchicalNode<T>(item, parent);
dict.Add(key, node);
} | {
"domain": "codereview.stackexchange",
"id": 44909,
"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, hash-map",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.