text stringlengths 1 2.12k | source dict |
|---|---|
algorithm, c, reinventing-the-wheel, image, numerical-methods
size_t clip(const size_t input, const size_t lowerbound, const size_t upperbound)
{
if (input < lowerbound)
{
return lowerbound;
}
if (input > upperbound)
{
return upperbound;
}
return input;
}
float clip_float(const float input, const float lowerbound, const float upperbound)
{
if (input < lowerbound)
{
return lowerbound;
}
if (input > upperbound)
{
return upperbound;
}
return input;
}
base.h
/* Develop by Jimmy Hu */
#ifndef BASE_H
#define BASE_H
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_PATH 256
#define FILE_ROOT_PATH "./"
#define True true
#define False false
typedef struct RGB
{
unsigned char channels[3];
} RGB;
typedef struct HSV
{
long double channels[3]; // Range: 0 <= H < 360, 0 <= S <= 1, 0 <= V <= 255
}HSV;
typedef struct BMPIMAGE
{
char FILENAME[MAX_PATH];
unsigned int XSIZE;
unsigned int YSIZE;
unsigned char FILLINGBYTE;
unsigned char *IMAGE_DATA;
} BMPIMAGE;
typedef struct RGBIMAGE
{
unsigned int XSIZE;
unsigned int YSIZE;
RGB *IMAGE_DATA;
} RGBIMAGE;
typedef struct HSVIMAGE
{
unsigned int XSIZE;
unsigned int YSIZE;
HSV *IMAGE_DATA;
} HSVIMAGE;
#endif
The full testing code
/* Develop by Jimmy Hu */
#include "base.h"
#include "imageio.h"
RGB* BicubicInterpolation(const RGB* const image, const int originSizeX, const int originSizeY, const int newSizeX, const int newSizeY);
unsigned char BicubicPolate(const unsigned char* ndata, const float fracx, const float fracy);
float CubicPolate(const float v0, const float v1, const float v2, const float v3, const float fracy);
size_t clip(const size_t input, const size_t lowerbound, const size_t upperbound);
float clip_float(const float input, const float lowerbound, const float upperbound); | {
"domain": "codereview.stackexchange",
"id": 45318,
"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": "algorithm, c, reinventing-the-wheel, image, numerical-methods",
"url": null
} |
algorithm, c, reinventing-the-wheel, image, numerical-methods
float clip_float(const float input, const float lowerbound, const float upperbound);
int main(int argc, char** argv)
{
char *FilenameString;
FilenameString = malloc( sizeof *FilenameString * MAX_PATH);
printf("BMP image input file name:(ex:test): ");
scanf("%s", FilenameString);
BMPIMAGE BMPImage1 = bmp_file_read(FilenameString, false);
RGBIMAGE RGBImage1;
RGBImage1.XSIZE = BMPImage1.XSIZE;
RGBImage1.YSIZE = BMPImage1.YSIZE;
RGBImage1.IMAGE_DATA = raw_image_to_array(BMPImage1.XSIZE, BMPImage1.YSIZE, BMPImage1.IMAGE_DATA);
RGBIMAGE RGBImage2;
RGBImage2.XSIZE = 1024;
RGBImage2.YSIZE = 1024;
RGBImage2.IMAGE_DATA = BicubicInterpolation(RGBImage1.IMAGE_DATA, RGBImage1.XSIZE, RGBImage1.YSIZE, RGBImage2.XSIZE, RGBImage2.YSIZE);
printf("file name for saving:(ex:test): ");
scanf("%s", FilenameString);
bmp_write(FilenameString, RGBImage2.XSIZE, RGBImage2.YSIZE, array_to_raw_image(RGBImage2.XSIZE, RGBImage2.YSIZE, RGBImage2.IMAGE_DATA));
free(FilenameString);
free(RGBImage1.IMAGE_DATA);
free(RGBImage2.IMAGE_DATA);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45318,
"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": "algorithm, c, reinventing-the-wheel, image, numerical-methods",
"url": null
} |
algorithm, c, reinventing-the-wheel, image, numerical-methods
RGB* BicubicInterpolation(const RGB* const image, const int originSizeX, const int originSizeY, const int newSizeX, const int newSizeY)
{
RGB* output;
output = malloc(sizeof *output * newSizeX * newSizeY);
if (output == NULL)
{
printf(stderr, "Memory allocation error!");
return NULL;
}
float ratiox = (float)originSizeX / (float)newSizeX;
float ratioy = (float)originSizeY / (float)newSizeY;
for (size_t y = 0; y < newSizeY; y++)
{
for (size_t x = 0; x < newSizeX; x++)
{
for (size_t channel_index = 0; channel_index < 3; channel_index++) {
float xMappingToOrigin = (float)x * ratiox;
float yMappingToOrigin = (float)y * ratioy;
float xMappingToOriginFloor = floor(xMappingToOrigin);
float yMappingToOriginFloor = floor(yMappingToOrigin);
float xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor;
float yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor;
unsigned char* ndata;
ndata = malloc(sizeof *ndata * 4 * 4);
if (ndata == NULL)
{
printf(stderr, "Memory allocation error!");
return NULL;
}
for (int ndatay = -1; ndatay < 2; ndatay++)
{
for (int ndatax = -1; ndatax < 2; ndatax++)
{
ndata[(ndatay + 1) * 4 + (ndatax + 1)] = image[
clip(yMappingToOriginFloor + ndatay, 0, originSizeY - 1) * originSizeX +
clip(xMappingToOriginFloor + ndatax, 0, originSizeX - 1)
].channels[channel_index];
}
} | {
"domain": "codereview.stackexchange",
"id": 45318,
"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": "algorithm, c, reinventing-the-wheel, image, numerical-methods",
"url": null
} |
algorithm, c, reinventing-the-wheel, image, numerical-methods
unsigned char result = BicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac);
output[ y * newSizeX + x ].channels[channel_index] = result;
free(ndata);
}
}
}
return output;
}
unsigned char BicubicPolate(const unsigned char* const ndata, const float fracx, const float fracy)
{
float x1 = CubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx );
float x2 = CubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx );
float x3 = CubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx );
float x4 = CubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx );
float output = clip_float(CubicPolate( x1, x2, x3, x4, fracy ), 0.0, 255.0);
return (unsigned char)output;
}
float CubicPolate(const float v0, const float v1, const float v2, const float v3, const float fracy)
{
float A = (v3-v2)-(v0-v1);
float B = (v0-v1)-A;
float C = v2-v0;
float D = v1;
return D + fracy * (C + fracy * (B + fracy * A));
}
size_t clip(const size_t input, const size_t lowerbound, const size_t upperbound)
{
if (input < lowerbound)
{
return lowerbound;
}
if (input > upperbound)
{
return upperbound;
}
return input;
}
float clip_float(const float input, const float lowerbound, const float upperbound)
{
if (input < lowerbound)
{
return lowerbound;
}
if (input > upperbound)
{
return upperbound;
}
return input;
}
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
Two dimensional bicubic interpolation implementation in Matlab and
Two dimensional gaussian image generator in C.
What changes has been made in the code since last question?
I am attempting to make a C version two dimensional bicubic interpolation function in this post.
Why a new review is being asked for?
If there is any possible improvement, please let me know. | {
"domain": "codereview.stackexchange",
"id": 45318,
"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": "algorithm, c, reinventing-the-wheel, image, numerical-methods",
"url": null
} |
algorithm, c, reinventing-the-wheel, image, numerical-methods
Why a new review is being asked for?
If there is any possible improvement, please let me know.
Answer: Avoid unnecesary allocation of temporary storage
In the innermost loop, you do this:
unsigned char* ndata;
ndata = malloc(sizeof *ndata * 4 * 4);
This is slow and completely unnecessary; you can just declare an array on the stack like so:
unsigned char ndata[4 * 4];
Possible improvements to the algorithm
It is likely that many of the intermediate values you are calculating in BicubicPolate() might be the same as those for neighbouring pixels. Also in CubicPolate(), none of the values of A to D depend on fracy, and some preprocessing of the image might allow you to avoid many of the operations.
Also consider that the ratio between the source and destination can be larger than 1 or smaller than 1, and different algorithms might be better for each case, and ratios of the form n or 1 / n, where n is an integer, might especially be candidates for algorithmic improvements. | {
"domain": "codereview.stackexchange",
"id": 45318,
"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": "algorithm, c, reinventing-the-wheel, image, numerical-methods",
"url": null
} |
python, python-3.x, comparative-review
Title: Compute the mean of a series of user-entered numbers
Question: Which is more elegant out of two methods as mentioned below mostly from memory prospective?
Both methods achieve the same result, but from a memory perspective, In Method1, we are storing the running total and count separately, using two variables. while In Method2, we are using a list to store all input values and then calculate the sum and length of the list to determine the average. However, I see Method2 abstracts the details of the accumulation process by utilizing built-in functions (sum and len), which can be considered more elegant?
Method 1:
total = 0
count = 0
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
value = float(user_input)
total += value
count += 1
average = total / count
print(f'Average: {average}')
Method 2:
numbers = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
value = float(user_input)
numbers.append(value)
if numbers:
average = sum(numbers) / len(numbers)
print(f'Average: {average}')
else:
print('No numbers entered.')
Answer: We're going to have a hard time applying adjectives like "elegant"
to code that intermixes computation with user input.
So let's address that first, with a generator:
def get_numbers():
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
return
yield float(user_input) | {
"domain": "codereview.stackexchange",
"id": 45319,
"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, comparative-review",
"url": null
} |
python, python-3.x, comparative-review
Feel free to replace this function
with get_numbers_from_csv or get_numbers_from_tcp_connection.
Ok, now that that
single responsibility
is packaged up inside a generator
we can turn to the alternative algorithms.
They do entirely different things.
In method 1 we consume O(1) constant memory,
and as a consequence cannot answer other questions
about the input (e.g. "what was the median value?").
This is a partial function over its possible inputs,
since it blows up with ZeroDivisionError
in the empty input case.
(There are also corner cases where user might
enter ±inf or NaN.)
In method 2 we accept the cost of allocation that is O(N) linear
with size of input.
So we're doing an entirely different thing.
And then we enjoy the flexibility of being able to conveniently compute sum(), min(),
and so on. We could even choose to sort and report a median figure.
I'm going to consider a different adjective: "fast".
Is this method fast?
Yes, once the numbers are all available,
method 2 is significantly faster than method 1.
But it's just an implementation detail of cPython,
a matter of looking at how many interpreted bytecode operations
are responsible for accomplishing the task,
contrasted with getting C code to do the same task more rapidly.
The sum() builtin is implemented in compiled C,
so it benchmarks quicker.
But what is that C code doing?
We made it chase N object references in the list,
and then go figure out if each object supports left or right addition,
and finally perform the FP operation and store it.
We could ask cPython to do less work.
Put each value in an
array
cell using numbers = array('d', get_numbers()), or perhaps prefer
numpy.
Now we no longer have N allocated object pointers to chase,
and we already know we're definitely talking about a FP number
rather than say, a
Fraction
or a non-numeric object like a str.
So the looping C code has less work to do, and it completes sooner.
If your use case allows switching from double to single-precision float | {
"domain": "codereview.stackexchange",
"id": 45319,
"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, comparative-review",
"url": null
} |
python, python-3.x, comparative-review
If your use case allows switching from double to single-precision float
then you can get away with doing just half the work.
There's multiple adjectives you might apply to such code.
Maybe "lazy"? | {
"domain": "codereview.stackexchange",
"id": 45319,
"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, comparative-review",
"url": null
} |
java, performance, memory-management, memory-optimization, set
Title: Comparison of two excel files ignoring line order | {
"domain": "codereview.stackexchange",
"id": 45320,
"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, performance, memory-management, memory-optimization, set",
"url": null
} |
java, performance, memory-management, memory-optimization, set
Question: Below is a simple method which compares contents of two excel files ignoring the line order.
This method is working as expected.
But, one of my peers in their code review mentioned that initializing and using 4 sets for this might not be the best way performance/memory-consumption wise and that the code can be optimized by using lesser number of sets.
I can't figure out how to reduce the number of sets though, to achieve the same functionality.
Do you have any clue and/or suggestions?
Code:
/** Compares contents of two excel files. Ignores line order of the contents.
* @param logger Logger instance
* @param actualFilePath Actual xlsx file
* @param baselineFilePath Baseline xlsx file
* @return true if the files match, false otherwise
* @throws Exception
*/
public boolean compareTwoXlsxFilesIgnoreLineOrder(Logger logger, String actualFilePath, String baselineFilePath) throws Exception {
File baselineFile = new File(baselineFilePath);
File actualFile = new File(actualFilePath);
FileInputStream baselineFileStream = null;
FileInputStream actualFileStream = null;
XSSFWorkbook baselineWorkbook = null;
XSSFWorkbook actualWorkbook = null;
XSSFExcelExtractor baselineExtractor = null;
XSSFExcelExtractor actualExtractor = null;
try {
if (!baselineFile.exists()) {
logger.severe("FAIL: Could not access the baseline file: " + baselineFile.getPath());
return false;
}
logger.info("baseline file: " + baselineFilePath);
if (!actualFile.exists()) {
logger.severe("FAIL: Could not access the actual file: " + actualFile.getPath());
return false;
}
logger.info("Actual file: " + actualFilePath);
baselineFileStream = new FileInputStream(baselineFile); | {
"domain": "codereview.stackexchange",
"id": 45320,
"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, performance, memory-management, memory-optimization, set",
"url": null
} |
java, performance, memory-management, memory-optimization, set
baselineFileStream = new FileInputStream(baselineFile);
actualFileStream = new FileInputStream(actualFile);
baselineWorkbook = new XSSFWorkbook(baselineFileStream);
actualWorkbook = new XSSFWorkbook(actualFileStream);
baselineExtractor = new XSSFExcelExtractor(baselineWorkbook);
actualExtractor = new XSSFExcelExtractor(actualWorkbook);
String baselineFileText = baselineExtractor.getText();
String actualFileText = actualExtractor.getText();
//Split by line break, trim whitespaces and remove empty lines.
Set<String> baselineLinesSet = Arrays.stream(baselineFileText.split("\\r?\\n")).map(String::trim).filter(line -> !line.isEmpty()).collect(Collectors.toSet());
Set<String> actualLinesSet = Arrays.stream(actualFileText.split("\\r?\\n")).map(String::trim).filter(line -> !line.isEmpty()).collect(Collectors.toSet());
Set<String> actualMinusbaseline = new HashSet<>(actualLinesSet);
actualMinusbaseline.removeAll(baselineLinesSet);
logger.fine("Size of actualMinusbaseline: " + actualMinusbaseline.size());
Set<String> baselineMinusActual = new HashSet<>(baselineLinesSet);
baselineMinusActual.removeAll(actualLinesSet);
logger.fine("Size of baselineMinusActual: " + baselineMinusActual.size()); | {
"domain": "codereview.stackexchange",
"id": 45320,
"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, performance, memory-management, memory-optimization, set",
"url": null
} |
java, performance, memory-management, memory-optimization, set
if (!actualMinusbaseline.isEmpty() || !baselineMinusActual.isEmpty()) {
logger.info("FAIL: Lines present in actual file but not in baseline file: " + actualMinusbaseline);
logger.info("FAIL: Lines present in baseline file but not in actual file: " + baselineMinusActual);
logger.info("**************** Mismatch info End *******************");
return false;
} else {
logger.info("VERIFIED: Actual file contents match with the baseline file contents.");
return true;
}
} catch (IOException e) {
logger.severe("Error while comparing files: " + e.getMessage());
throw e;
} finally {
if (baselineExtractor != null) {
baselineExtractor.close();
}
if (actualExtractor != null) {
actualExtractor.close();
}
if (baselineWorkbook != null) {
baselineWorkbook.close();
}
if (actualWorkbook != null) {
actualWorkbook.close();
}
if (baselineFileStream != null) {
baselineFileStream.close();
}
if (actualFileStream != null) {
actualFileStream.close();
}
}
}
Answer: Filtering the line sets while parsing the actualFileText, that is removing from baselineLinesSet the lines contained by actualFileText while also filtering them out from the actualLinesSet, at the end of parsing results two sets containing the difference between each other.
Set<String> baselineLinesSet = Arrays.stream(baselineFileText.split("\\r?\\n"))
.map(String::trim)
.filter(line -> !line.isEmpty())
.collect(Collectors.toSet()); | {
"domain": "codereview.stackexchange",
"id": 45320,
"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, performance, memory-management, memory-optimization, set",
"url": null
} |
java, performance, memory-management, memory-optimization, set
Set<String> actualLinesSet = Arrays.stream(actualFileText.split("\\r?\\n"))
.map(String::trim)
.filter(line -> !line.isEmpty())
.map(line -> {
if (baselineLinesSet.remove(line)) {
return null;
} else {
return line;
}
})
.filter(line -> line != null)
.collect(Collectors.toSet());
if ( actualLinesSet.size() == 0 && baselineLinesSet.size() == 0 ) {
. . .
return true;
} else {
. . .
return false;
} | {
"domain": "codereview.stackexchange",
"id": 45320,
"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, performance, memory-management, memory-optimization, set",
"url": null
} |
c, pointers
Title: "Smart" (ish) pointer in C
Question: I am a programmer with a primarily Rust-based background who has nonetheless taken an interest in C lately due to its simplicity and minimalism. However, one of the things I miss most from Rust is safe memory management. So I created a "smart pointer" of sorts to replicate that experience:
#include <stdio.h>
/*
This is a "smart" pointer that
uses Option types for safe memory management.
*/
typedef enum option {
Some,
None
} Option;
typedef struct OptionPointer {
void *content;
Option state;
int is_malloc;
} OptionPointer;
union internal_PointerType {
void *content;
int err;
};
typedef struct PointerType {
int choice;
union internal_PointerType internal;
} PointerType;
OptionPointer create_ptr(void *content, int is_malloc) {
OptionPointer p;
p.content = content;
p.state = Some;
p.is_malloc = is_malloc;
return p;
}
void set_ptr_invalid(OptionPointer *ptr) {
ptr->state = None;
// Only need to free memory
// if it was dynamically allocated,
// otherwise we only need to worry
// about dangling pointers
if (ptr->is_malloc) {
free(ptr->content);
}
}
PointerType get_ptr(OptionPointer *ptr) {
PointerType res;
res.choice = 0;
if (ptr->state == None) {
res.choice = 0;
res.internal.err = 1;
} else {
res.choice = 1;
res.internal.content = ptr->content;
}
return res;
}
// Example
int main() {
char *a = "This is some testing text";
OptionPointer ptr = create_ptr(a, 0);
// Imaginary scenario where the pointer becomes invalid
set_ptr_invalid(&ptr);
PointerType res = get_ptr(&ptr);
if (res.choice) {
char *content = (char*)res.internal.content;
printf("%s\n", content);
} else {
printf("Invalid pointer at %s:%d\n", __FILE__, __LINE__);
}
}
I can already see some notable problems: | {
"domain": "codereview.stackexchange",
"id": 45321,
"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, pointers",
"url": null
} |
c, pointers
I can already see some notable problems:
I literally just started programming in C a few days ago so I probably am not using recommended best practices
"Smart" only goes so far - you'd have to call set_ptr_invalid() every single time a pointer could become invalid as a result of an operation
This (possibly?) might not work well with malloc() and doesn't cover the case that malloc() wasn't successful
All feedback on this would be much appreciated!
Answer: Disclaimer: The next few lines are my opinion as a C programmer so take it with a grain of salt.
As a C programmer, I will never use this. The language is verbose enough already due to its lack of features. You are now erasing the type of the pointer by stuffing it in void making my job harder. Take the following example.
void do_something(PointerType * some_object);
What is the underlying type of some_object? There is no way of telling without documentation. If some idiot stuffs the wrong underlying type. I have a nice time figuring out access violations.
Let us say it is MyStruct.
typedef struct MyStruct {
char character;
int integer;
} MyStruct;
If I was implementing do_something. I could just do it like this with regular pointers.
void do_something(MyStruct * some_object){
if(some_object == NULL){
printf("Invalid pointer at %s:%d\n", __FILE__, __LINE__);
return;
}
printf("Value of my struct is {character : %c, integer : &d}", some_object->character, some_object->integer);
}
With your code I have to first get the underlying type and then cast it to MyStruct*, it adds quite a few lines.
OptionPointer also adds an overhead of an enum to my pointer. And is going potentially confuse the compiler optimizer generating suboptimal code.
Review | {
"domain": "codereview.stackexchange",
"id": 45321,
"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, pointers",
"url": null
} |
c, pointers
Add a check for NULL in create_ptr. Someone might easily stuff a NULL in there. This would also mean you have to have an error mechanism if create_ptr fails.
Use opaque ptr paradigm to hide the internals of OptionPointer otherwise there is no way of preventing a C programmer from just treating this as a struct and modify state and contents directly.
Using opaque ptr also means that you will have to add a function to check the value of choice.
There is only 1 way a pointer fails aka it is NULL. So you do not need a separate err code for that.
This is how I would write the same thing.
#include <stdio.h>
#include <stdbool.h>
/*---------- Pointer.h --------------*/
typedef struct Pointer Pointer;
Pointer create_ptr(void * ptr);
void set_ptr_invalid(Pointer *ptr);
bool is_ptr_valid(Pointer* ptr);
void* get_ptr(Pointer* ptr);
/*---------- Pointer.c ------------*/
typedef struct Pointer {
void* content;
} Pointer;
Pointer create_ptr(void * ptr){
Pointer p;
p.content = ptr;
return p;
}
void set_ptr_invalid(Pointer *ptr) {
ptr->content = NULL;
}
bool is_ptr_valid(Pointer* ptr){
return ptr->content != NULL;
}
void* get_ptr(Pointer* ptr){
return ptr->content;
}
/*------------ Main.c ---------- */
// Example
int main() {
char const * a = "This is some testing text";
Pointer ptr = create_ptr((void*)a);
if (is_ptr_valid(&ptr)) {
char *content = (char*)get_ptr(&ptr);
printf("%s\n", content);
} else {
printf("Invalid pointer at %s:%d\n", __FILE__, __LINE__);
}
set_ptr_invalid(&ptr);
if (is_ptr_valid(&ptr)) {
char *content = (char*)get_ptr(&ptr);
printf("%s\n", content);
} else {
printf("Invalid pointer at %s:%d\n", __FILE__, __LINE__);
}
}
``` | {
"domain": "codereview.stackexchange",
"id": 45321,
"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, pointers",
"url": null
} |
c++, multithreading, openmp, c++23
Title: Differential Evolution
Question: I have a PR implementing differential evolution. I'm a bit concerned about the implementation and would like some feedback:
The class could be a free function. However, there are so many parameters, the templates become unwieldy and getting arguments out of order seems so easy. So I split it between constructor and member function call. Is this a good idea?
One consequence of the split: I had to use the .template member function syntax; are people familiar with it?
I would like this to work with functions taking individual arguments like
double foo(double x, double y, double z);
but as it stands, I could only get it to work with functions taking in std::array or std::vector.
OpenMP does kinda feel like the right choice here, but it does introduce a dependency. Should I just use std::threads?
I'm currently targeting the newest C++ standard that I can get to compile, so any suggestions requiring C++23 are fine.
Code:
/*
* Copyright Nick Thompson, 2023
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_MATH_TOOLS_DIFFERENTIAL_EVOLUTION_HPP
#define BOOST_MATH_TOOLS_DIFFERENTIAL_EVOLUTION_HPP
#include <algorithm>
#include <array>
#include <atomic>
#include <cmath>
#if __has_include(<omp.h>)
#include <omp.h>
#endif
#include <random>
#include <stdexcept>
#include <sstream>
#include <thread>
#include <utility>
#include <vector>
namespace boost::math::tools {
template <class T>
concept subscriptable = requires(const T &c) { c[0]; }; | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
c++, multithreading, openmp, c++23
// Storn, R., & Price, K. (1997). Differential evolution–a simple and efficient heuristic for global optimization over
// continuous spaces. Journal of global optimization, 11, 341-359. See:
// https://www.cp.eng.chula.ac.th/~prabhas//teaching/ec/ec2012/storn_price_de.pdf
template <typename BoundsContainer>
requires subscriptable<BoundsContainer>
class differential_evolution {
public:
using BoundType = BoundsContainer::value_type;
using Real = BoundType::value_type;
differential_evolution(BoundsContainer bounds, Real F = 0.8, Real crossover_ratio = 0.5, size_t NP = 1000,
size_t max_generations = 1000)
: bounds_{bounds}, F_{F}, CR_{crossover_ratio}, NP_{NP}, max_generations_{max_generations} {
using std::isfinite;
std::ostringstream oss;
if (bounds_.size() == 0) {
oss << __FILE__ << ":" << __LINE__ << ":" << __func__;
oss << ": The dimension of the problem cannot be zero.";
throw std::domain_error(oss.str());
}
if (bounds_[0].size() != 2) {
oss << __FILE__ << ":" << __LINE__ << ":" << __func__;
oss << ": Each element of the bounds container must have two elements.";
throw std::invalid_argument(oss.str());
}
for (auto const &bound : bounds_) {
if (bound[0] > bound[1]) {
oss << __FILE__ << ":" << __LINE__ << ":" << __func__;
oss << ": The upper bound must be ≥ the lower bound, but the upper bound is "
<< bound[1] << " and the lower is " << bound[0] << ".";
throw std::domain_error(oss.str());
}
if (!isfinite(bound[0])) {
oss << __FILE__ << ":" << __LINE__ << ":" << __func__;
oss << ": The lower bound must be finite, but got " << bound[1] << ".";
oss << " For infinite bounds, emulate with std::numeric_limits<Real>::lower() or use a standard infinite->finite transform.";
throw std::domain_error(oss.str());
}
if (!isfinite(bound[1])) { | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
c++, multithreading, openmp, c++23
throw std::domain_error(oss.str());
}
if (!isfinite(bound[1])) {
oss << __FILE__ << ":" << __LINE__ << ":" << __func__;
oss << ": The upper bound must be finite, but got " << bound[1] << ".";
oss << " For infinite bounds, emulate with std::numeric_limits<Real>::max() or use a standard infinite->finite transform.";
throw std::domain_error(oss.str());
}
}
if (NP_ < 4) {
oss << __FILE__ << ":" << __LINE__ << ":" << __func__;
oss << ": The population size must be at least 4.";
throw std::invalid_argument(oss.str());
}
if (F_ > Real(2) || F_ <= Real(0)) {
oss << __FILE__ << ":" << __LINE__ << ":" << __func__;
oss << ": F in (0, 2] is required, but got F=" << F << ".";
throw std::domain_error(oss.str());
}
if (max_generations_ < 1) {
oss << __FILE__ << ":" << __LINE__ << ":" << __func__;
oss << ": There must be at least one generation.";
throw std::invalid_argument(oss.str());
}
} | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
c++, multithreading, openmp, c++23
template <typename ArgumentContainer, class Func, class URBG>
ArgumentContainer
minimize(const Func Phi, URBG &g,
std::atomic<bool> *cancellation =
nullptr, // a stop_token might be preferable when compiler support is more widespread.
size_t threads = std::thread::hardware_concurrency(),
std::vector<std::pair<ArgumentContainer, decltype(std::declval<Func>()(std::declval<ArgumentContainer>()))>>
*queries = nullptr) {
constexpr bool has_resize = requires(const ArgumentContainer &t) { t.resize(); };
using ResultType = decltype(std::declval<Func>()(std::declval<ArgumentContainer>()));
using std::clamp;
using std::round;
using Size_t = ArgumentContainer::size_type;
std::vector<ArgumentContainer> population(NP_);
for (size_t i = 0; i < population.size(); ++i) {
if constexpr (has_resize) {
// Resize it to same size as bounds_:
population[i].resize(bounds_.size());
} else {
// Argument type must be known at compile-time; like std::array:
assert(population[i].size() == bounds_.size());
}
}
std::vector<ResultType> fitness(NP_);
using std::uniform_real_distribution;
uniform_real_distribution<Real> dis(Real(0), Real(1));
for (size_t i = 0; i < population.size(); ++i) {
for (Size_t j = 0; j < bounds_.size(); ++j) {
auto const &bound = bounds_[j];
population[i][j] = bound[0] + dis(g) * (bound[1] - bound[0]);
}
}
for (size_t i = 0; i < fitness.size(); ++i) {
fitness[i] = Phi(population[i]);
if (queries) {
#pragma omp critical
queries->push_back(std::make_pair(population[i], fitness[i]));
}
} | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
c++, multithreading, openmp, c++23
const size_t dimension = bounds_.size();
const auto crossover_int = static_cast<decltype(g())>(round((g.max() - g.min()) * static_cast<double>(CR_)));
std::vector<URBG> generators(threads);
for (size_t i = 0; i < threads; ++i) {
generators[i].seed(g());
}
for (size_t generation = 0; generation < max_generations_; ++generation) {
if (cancellation && *cancellation) {
break;
}
#pragma omp parallel for num_threads(threads)
for (size_t i = 0; i < NP_; ++i) {
#if defined(_OPENMP)
size_t thread_idx = omp_get_thread_num();
#else
size_t thread_idx = 0;
#endif
auto& gen = generators[thread_idx];
size_t r1, r2, r3;
do {
r1 = gen() % NP_;
} while (r1 == i);
do {
r2 = gen() % NP_;
} while (r2 == i || r2 == r1);
do {
r3 = gen() % NP_;
} while (r3 == i || r3 == r2 || r3 == r1);
ArgumentContainer trial_vector;
if constexpr (has_resize) {
trial_vector.resize(bounds_.size());
}
for (size_t j = 0; j < dimension; ++j) {
// See equation (4) of the reference:
auto guaranteed_changed_idx = gen() % NP_;
if (gen() < crossover_int || j == guaranteed_changed_idx) {
auto tmp = population[r1][j] + F_ * (population[r2][j] - population[r3][j]);
trial_vector[j] = clamp(tmp, bounds_[j][0], bounds_[j][1]);
} else {
trial_vector[j] = population[i][j];
}
}
auto trial_fitness = Phi(trial_vector);
if (queries) {
#pragma omp critical
queries->push_back(std::make_pair(trial_vector, trial_fitness));
}
if (trial_fitness < fitness[i]) {
std::swap(population[i], trial_vector);
fitness[i] = trial_fitness;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
c++, multithreading, openmp, c++23
auto it = std::min_element(fitness.begin(), fitness.end());
auto idx = std::distance(fitness.begin(), it);
return population[idx];
}
private:
BoundsContainer bounds_;
Real F_;
Real CR_;
size_t NP_;
size_t max_generations_;
};
} // namespace boost::math::tools
#endif
Tests:
/*
* Copyright Nick Thompson, 2023
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include "math_unit_test.hpp"
#include <random>
#include <boost/math/constants/constants.hpp>
#include <boost/math/tools/differential_evolution.hpp>
#ifdef BOOST_HAS_FLOAT128
#include <boost/multiprecision/float128.hpp>
using boost::multiprecision::float128;
#endif
using boost::math::tools::differential_evolution;
using boost::math::constants::two_pi;
using boost::math::constants::e;
using std::cbrt;
using std::sqrt;
using std::cos;
using std::exp;
// Taken from: https://en.wikipedia.org/wiki/Test_functions_for_optimization
template<typename Real>
Real ackley(std::array<Real, 2> const & v) {
Real x = v[0];
Real y = v[1];
Real arg1 = -sqrt((x*x+y*y)/2)/5;
Real arg2 = cos(two_pi<Real>()*x) + cos(two_pi<Real>()*y);
return -20*exp(arg1) - exp(arg2/2) + 20 + e<Real>();
} | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
c++, multithreading, openmp, c++23
template<class Real>
void test_ackley()
{
std::vector<std::array<Real, 2>> bounds(2);
bounds[0] = {-5, 5};
bounds[1] = {-5, 5};
auto de = differential_evolution(bounds, 0.9);
std::random_device rd;
std::mt19937_64 gen(rd());
auto local_minima = de.template minimize<std::array<Real, 2>>(ackley<Real>, gen);
CHECK_LE(std::abs(local_minima[0]), 10*std::numeric_limits<Real>::epsilon());
CHECK_LE(std::abs(local_minima[1]), 10*std::numeric_limits<Real>::epsilon());
// Works with a lambda:
auto ack = [](std::array<Real, 2> const & x) { return ackley<Real>(x); };
local_minima = de.template minimize<std::array<Real, 2>>(ack, gen);
CHECK_LE(std::abs(local_minima[0]), 10*std::numeric_limits<Real>::epsilon());
CHECK_LE(std::abs(local_minima[1]), 10*std::numeric_limits<Real>::epsilon());
}
template<typename Real>
auto rosenbrock_saddle(std::array<Real, 2> const & v) {
auto x = v[0];
auto y = v[1];
return 100*(x*x - y)*(x*x - y) + (1 - x)*(1-x);
}
template<class Real>
void test_rosenbrock_saddle()
{
std::vector<std::array<Real, 2>> bounds(2);
bounds[0] = {-2.048, 2.048};
bounds[1] = {-2.048, 2.048};
auto de = differential_evolution(bounds, 0.9);
std::random_device rd;
std::mt19937_64 gen(rd());
auto local_minima = de.template minimize<std::array<Real, 2>>(rosenbrock_saddle<Real>, gen);
CHECK_ABSOLUTE_ERROR(local_minima[0], Real(1), 10*std::numeric_limits<Real>::epsilon());
CHECK_ABSOLUTE_ERROR(local_minima[1], Real(1), 10*std::numeric_limits<Real>::epsilon());
}
int main()
{
test_ackley<float>();
test_ackley<double>();
test_rosenbrock_saddle<double>();
return boost::math::test::report_errors();
}
Answer: About your concerns | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
c++, multithreading, openmp, c++23
Answer: About your concerns
The class could be a free function. However, there are so many parameters, the templates become unwieldy and getting arguments out of order seems so easy. So I split it between constructor and member function call. Is this a good idea?
You can always create a struct holding all the parameters needed by the function, and just pass a reference to that struct. Then you can use designated initializers to fill in the parameters in a safe way. Consider:
template<typename BoundsContainer, class Func, class URBG>
struct de_minimize_parameters {
using BoundType = BoundsContainer::value_type;
using Real = BoundType::value_type;
BoundsContainer bounds;
Real F = 0.8;
…
const Func Phi;
URBG &g;
…
};
template <typename ArgumentContainer, typename Parameters>
auto minimize(const Parameters& parameters) {
…
using ResultType = std::invoke_result_t<decltype(parameters.Phi), ArgumentContainer>;
…
}
…
template<class Real>
void test_ackley()
{
…
de_minimize_parameters params = {
.bounds = bounds,
.F = 0.9,
.Phi = ackley<Real>,
.g = gen,
};
…
auto local_minima = minimize<std::array<Real, 2>>(params);
…
}
One consequence of the split: I had to use the .template member function syntax; are people familiar with it?
C++ programmers used to writing templates probably are familiar with it. Many compilers will give a useful warning if you forget the template keyword here.
I would like this to work with functions taking individual arguments like
double foo(double x, double y, double z);
but as it stands, I could only get it to work with functions taking in std::array or std::vector. | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
c++, multithreading, openmp, c++23
but as it stands, I could only get it to work with functions taking in std::array or std::vector.
You can make this work by packing the arguments in a std::tuple and calling the function using std::apply(). You also might want to change how you pass the bounds then: it should just be two tuples, one for the lower bound and one for the upper bound.
template<…>
auto minimize(…) {
…
for (size_t i = 0; i < population.size(); ++i) {
population[i] = gen_sample(lower_bound_, upper_bound_, gen);
}
…
for (size_t i = 0; i < fitness.size(); ++i) {
fitness[i] = std::apply(Phi, population[i]);
…
}
…
}
…
Real foo(Real x, Real y, Real z) {
…
}
template<class Real>
void test_foo()
{
using vec3 = std::tuple<Real, Real, Real>;
vec3 lower_bound = {-5, -5, -5};
vec3 upper_bound = {+5, +5, +5};
…
auto local_minima = de.template minimize<vec3>(foo<Real>, gen);
…
}
The hard part will be creating gen_sample(), which takes two tuples, and has to iterate over them. C++ makes this particularly hard, you have to implement your own helper function that does this, for example like this one. If you have that, then you could write gen_sample() like so:
template<typename Tuple, typename URBG>
auto gen_sample(const Tuple& lower_bound, const Tuple& upper_bound, URBG& g) {
return tuple_for_each([&](auto lower_bound, auto upper_bound) {
return std::uniform_real_distribution(lower_bound, upper_bound)(g);
}, lower_bound, upper_bound);
}
OpenMP does kinda feel like the right choice here, but it does introduce a dependency. Should I just use std::threads? | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
c++, multithreading, openmp, c++23
It's not too hard to create your own thread pool and parallelize the loop this way. You could also consider using an existing thread pool implementation from Boost. It's hard for me to answer what you should do here, it depends on your target audience and how portable you want your code to be.
Avoid requiring the caller to specify the result type of minimize()
The bounds already contain enough information to deduce the result type of minimize(), so try to use that instead of requiring the caller to pass that in. If you store the bounds as two tuples, it is trivial, as then it will be the same as BoundType.
Use a callback for queries
Your minimize() function takes a pointer to a vector of queries. Maybe the caller doesn't want the results in a std::vector. Instead of forcing a container type here, consider passing a callback instead, so the caller can decide how to handle and store queries.
Avoid code duplication
The checks at the start of the constructor have a lot of duplicated code. Try to reduce that by creating a helper function that constructs the error message and then throws an exception of the required type. Note that you can also use std::source_location to avoid the __FILE__, __LINE__ and __func__ macros. | {
"domain": "codereview.stackexchange",
"id": 45322,
"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++, multithreading, openmp, c++23",
"url": null
} |
python, performance, time
Title: Efficient way to load Spacy model
Question: Here, is there any efficient way to load en_core_web_mdmodel without importing whole spacy module? It takes a significant amount of time to load the python program.
import spacy
from spacy import displacy
from spacy.matcher import Matcher, DependencyMatcher
nlp = spacy.load("en_core_web_md")
Answer: Loading a big module can be expensive.
I see elapsed times in the ballpark of four seconds to import spacy.
You could choose to cherry pick just the parts your app needs
and place them in a new module,
but that would involve lots of tedious testing.
from spacy import displacy
from spacy.matcher import Matcher, DependencyMatcher
Those two lines have essentially zero cost, so don't worry about them.
They certainly aren't introducing any inefficiency;
they simply rename existing objects.
Having imported the module once, we enjoy cache hits on
references to the loaded module.
And the medium-size en_core_web_md is what it is.
You apparently don't mind the extra delay
relative to loading a ..._sm small model,
so it must be pulling its weight in your use case.
strategy
There's some review context missing.
OP doesn't tell us how that nlp model will be used,
and what the interactive latency constraints are.
Some apps are going to have large startup cost,
and the usual strategy for coping with that
is to hang onto the initialized process,
recycling it for multiple requests.
So painful startup is amortized across a bunch of requests
which individually are satisfied with low latency.
In the data science community this approach shows up
most often in the form of
Jupyter notebooks.
You might choose to go that route for your natural language processing.
Load the model once and re-use it in many cells.
Alternatively, you might make your app availble via
Flask API endpoints.
Again, expensive startup of a webserver daemon happens once,
and then low latency responses are served up by the endpoints. | {
"domain": "codereview.stackexchange",
"id": 45323,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, time",
"url": null
} |
c++, image, template, c++20, constrained-templates
Title: Three dimensional gaussian image generator in C++
Question: This is a follow-up question for Two dimensional gaussian image generator in C++. Besides the two dimensional case, I am trying to implement three dimensional gaussian image generator which with additional zsize, centerz and standard_deviation_z parameters.
The experimental implementation
gaussianFigure3D Template Function Implementation
template<class InputT>
requires(std::floating_point<InputT> || std::integral<InputT>)
constexpr static auto gaussianFigure3D(
const size_t xsize, const size_t ysize, const size_t zsize,
const size_t centerx, const size_t centery, const size_t centerz,
const InputT standard_deviation_x, const InputT standard_deviation_y, const InputT standard_deviation_z)
{
auto output = std::vector<Image<InputT>>();
auto gaussian_image2d = gaussianFigure2D(xsize, ysize, centerx, centery, standard_deviation_x, standard_deviation_y);
for (size_t z = 0; z < zsize; ++z)
{
output.push_back(
multiplies(gaussian_image2d,
Image(xsize, ysize, normalDistribution1D(static_cast<InputT>(z) - static_cast<InputT>(centerz), standard_deviation_z)))
);
}
return output;
}
Image class
namespace TinyDIP
{
template <typename ElementT>
class Image
{
public:
Image() = default;
Image(const std::size_t width, const std::size_t height):
width(width),
height(height),
image_data(width * height) { }
Image(const std::size_t width, const std::size_t height, const ElementT initVal):
width(width),
height(height),
image_data(width * height, initVal) {} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight):
width(newWidth),
height(newHeight)
{
if (input.size() != newWidth * newHeight)
{
throw std::runtime_error("Image data input and the given size are mismatched!");
}
image_data = input;
}
Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight):
width(newWidth),
height(newHeight)
{
if (input.size() != newWidth * newHeight)
{
throw std::runtime_error("Image data input and the given size are mismatched!");
}
image_data = std::move(input); // Reference: https://stackoverflow.com/a/51706522/6667035
}
Image(const std::vector<std::vector<ElementT>>& input)
{
height = input.size();
width = input[0].size();
for (auto& rows : input)
{
image_data.insert(image_data.end(), std::ranges::begin(input), std::ranges::end(input)); // flatten
}
return;
}
constexpr ElementT& at(const unsigned int x, const unsigned int y)
{
checkBoundary(x, y);
return image_data[y * width + x];
}
constexpr ElementT const& at(const unsigned int x, const unsigned int y) const
{
checkBoundary(x, y);
return image_data[y * width + x];
}
constexpr std::size_t getWidth() const
{
return width;
}
constexpr std::size_t getHeight() const noexcept
{
return height;
}
constexpr auto getSize() noexcept
{
return std::make_tuple(width, height);
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data
void print(std::string separator = "\t", std::ostream& os = std::cout) const
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y) << separator;
}
os << "\n";
}
os << "\n";
return;
}
// Enable this function if ElementT = RGB
void print(std::string separator = "\t", std::ostream& os = std::cout) const
requires(std::same_as<ElementT, RGB>)
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
os << "( ";
for (std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y).channels[channel_index] << separator;
}
os << ")" << separator;
}
os << "\n";
}
os << "\n";
return;
}
friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs)
{
const std::string separator = "\t";
rhs.print(separator, os);
return os;
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
Image<ElementT>& operator+=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::plus<>{});
return *this;
}
Image<ElementT>& operator-=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::minus<>{});
return *this;
}
Image<ElementT>& operator*=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::multiplies<>{});
return *this;
}
Image<ElementT>& operator/=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::divides<>{});
return *this;
}
friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default;
friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default;
friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 += input2;
}
friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 -= input2;
}
Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign
Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign
Image(const Image<ElementT> &input) = default; // Copy Constructor
Image(Image<ElementT> &&input) = default; // Move Constructor
#ifdef USE_BOOST_SERIALIZATION
void Save(std::string filename)
{
const std::string filename_with_extension = filename + ".dat";
// Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c
std::ofstream ofs(filename_with_extension, std::ios::binary);
boost::archive::binary_oarchive ArchiveOut(ofs);
// write class instance to archive
ArchiveOut << *this;
// archive and stream closed when destructors are called
ofs.close();
}
#endif
private:
std::size_t width;
std::size_t height;
std::vector<ElementT> image_data;
void checkBoundary(const size_t x, const size_t y) const
{
if (x >= width)
throw std::out_of_range("Given x out of range!");
if (y >= height)
throw std::out_of_range("Given y out of range!");
}
};
template<typename T, typename ElementT>
concept is_Image = std::is_same_v<T, Image<ElementT>>;
}
Full Testing Code
The full testing code:
// Three dimensional gaussian image generator in C++
// Developed by Jimmy Hu
#include <algorithm>
#include <chrono> // for std::chrono::system_clock::now
#include <cmath> // for std::exp
#include <concepts>
#include <execution> // for std::is_execution_policy_v
#include <iostream> // for std::cout
#include <vector>
struct RGB
{
std::uint8_t channels[3];
};
using GrayScale = std::uint8_t; | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
struct RGB
{
std::uint8_t channels[3];
};
using GrayScale = std::uint8_t;
// image.h
namespace TinyDIP
{
template <typename ElementT>
class Image
{
public:
Image() = default;
Image(const std::size_t width, const std::size_t height):
width(width),
height(height),
image_data(width * height) { }
Image(const std::size_t width, const std::size_t height, const ElementT initVal):
width(width),
height(height),
image_data(width * height, initVal) {}
Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight):
width(newWidth),
height(newHeight)
{
if (input.size() != newWidth * newHeight)
{
throw std::runtime_error("Image data input and the given size are mismatched!");
}
image_data = input;
}
Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight):
width(newWidth),
height(newHeight)
{
if (input.size() != newWidth * newHeight)
{
throw std::runtime_error("Image data input and the given size are mismatched!");
}
image_data = std::move(input); // Reference: https://stackoverflow.com/a/51706522/6667035
}
Image(const std::vector<std::vector<ElementT>>& input)
{
height = input.size();
width = input[0].size();
for (auto& rows : input)
{
image_data.insert(image_data.end(), std::ranges::begin(input), std::ranges::end(input)); // flatten
}
return;
}
constexpr ElementT& at(const unsigned int x, const unsigned int y)
{
checkBoundary(x, y);
return image_data[y * width + x];
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
constexpr ElementT const& at(const unsigned int x, const unsigned int y) const
{
checkBoundary(x, y);
return image_data[y * width + x];
}
constexpr std::size_t getWidth() const
{
return width;
}
constexpr std::size_t getHeight() const noexcept
{
return height;
}
constexpr auto getSize() noexcept
{
return std::make_tuple(width, height);
}
std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data
void print(std::string separator = "\t", std::ostream& os = std::cout) const
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y) << separator;
}
os << "\n";
}
os << "\n";
return;
}
// Enable this function if ElementT = RGB
void print(std::string separator = "\t", std::ostream& os = std::cout) const
requires(std::same_as<ElementT, RGB>)
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
os << "( ";
for (std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y).channels[channel_index] << separator;
}
os << ")" << separator;
}
os << "\n";
}
os << "\n";
return;
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs)
{
const std::string separator = "\t";
rhs.print(separator, os);
return os;
}
Image<ElementT>& operator+=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::plus<>{});
return *this;
}
Image<ElementT>& operator-=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::minus<>{});
return *this;
}
Image<ElementT>& operator*=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::multiplies<>{});
return *this;
}
Image<ElementT>& operator/=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::divides<>{});
return *this;
}
friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default;
friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default;
friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 += input2;
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 -= input2;
}
Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign
Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign
Image(const Image<ElementT> &input) = default; // Copy Constructor
Image(Image<ElementT> &&input) = default; // Move Constructor
#ifdef USE_BOOST_SERIALIZATION
void Save(std::string filename)
{
const std::string filename_with_extension = filename + ".dat";
// Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c
std::ofstream ofs(filename_with_extension, std::ios::binary);
boost::archive::binary_oarchive ArchiveOut(ofs);
// write class instance to archive
ArchiveOut << *this;
// archive and stream closed when destructors are called
ofs.close();
}
#endif
private:
std::size_t width;
std::size_t height;
std::vector<ElementT> image_data;
void checkBoundary(const size_t x, const size_t y) const
{
if (x >= width)
throw std::out_of_range("Given x out of range!");
if (y >= height)
throw std::out_of_range("Given y out of range!");
}
};
template<typename T, typename ElementT>
concept is_Image = std::is_same_v<T, Image<ElementT>>;
}
namespace TinyDIP
{
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1};
}
template<std::size_t index = 1, typename Arg, typename... Args>
constexpr static auto& get_from_variadic_template(const Arg& first, const Args&... inputs)
{
if constexpr (index > 1)
return get_from_variadic_template<index - 1>(inputs...);
else
return first;
}
template<typename... Args>
constexpr static auto& first_of(Args&... inputs) {
return get_from_variadic_template<1>(inputs...);
}
template<std::size_t, typename, typename...>
struct get_from_variadic_template_struct { };
template<typename T1, typename... Ts>
struct get_from_variadic_template_struct<1, T1, Ts...>
{
using type = T1;
};
template<std::size_t index, typename T1, typename... Ts>
requires ( requires { typename get_from_variadic_template_struct<index - 1, Ts...>::type; })
struct get_from_variadic_template_struct<index, T1, Ts...>
{
using type = typename get_from_variadic_template_struct<index - 1, Ts...>::type;
};
template<std::size_t index, typename... Ts>
using get_from_variadic_template_t = typename get_from_variadic_template_struct<index, Ts...>::type;
// recursive_invoke_result_t implementation
template<std::size_t, typename, typename>
struct recursive_invoke_result { };
template<typename T, typename F>
struct recursive_invoke_result<0, F, T> { using type = std::invoke_result_t<F, T>; }; | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
template<std::size_t unwrap_level, std::copy_constructible F, template<typename...> typename Container, typename... Ts>
requires (std::ranges::input_range<Container<Ts...>> &&
requires { typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<unwrap_level, F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
template<std::size_t unwrap_level, std::copy_constructible F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<unwrap_level, F, T>::type;
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<std::copy_constructible 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>...>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
template<std::size_t unwrap_level, std::copy_constructible 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, std::copy_constructible F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
template<typename OutputIt, std::copy_constructible NAryOperation, typename InputIt, typename... InputIts>
OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) {
while (first != last) {
*d_first++ = op(*first++, (*rest++)...);
}
return d_first;
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
// recursive_transform for the multiple parameters cases (the version with unwrap_level)
template<std::size_t unwrap_level = 1, std::copy_constructible F, class Arg1, class... Args>
requires(unwrap_level <= recursive_depth<Arg1>())
constexpr auto recursive_transform(const F& f, const Arg1& arg1, const Args&... args)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, Arg1, Args...> output{};
transform(
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element1, auto&&... elements) { return recursive_transform<unwrap_level - 1>(f, element1, elements...); },
std::ranges::cbegin(arg1),
std::ranges::cend(arg1),
std::ranges::cbegin(args)...
);
return output;
}
else
{
return std::invoke(f, arg1, args...);
}
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, 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 (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
unwrap_level <= recursive_depth<T>())
constexpr auto recursive_transform(ExPo execution_policy, const F& f, const T& input)
{
if constexpr (unwrap_level > 0)
{
recursive_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, f, element);
});
return output;
}
else
{
return std::invoke(f, input);
}
}
}
namespace TinyDIP
{
template<std::size_t unwrap_level = 1, class... Args>
constexpr static auto pixelwiseOperation(auto op, const Args&... inputs)
{
auto output = Image(
recursive_transform<unwrap_level>(
[&](auto&& element1, auto&&... elements)
{
return op(element1, elements...);
},
inputs.getImageData()...),
first_of(inputs...).getWidth(),
first_of(inputs...).getHeight());
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
template<std::size_t unwrap_level = 1, class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static auto pixelwiseOperation(ExPo execution_policy, auto op, const Image<InputT>& input1)
{
auto output = Image(
recursive_transform<unwrap_level>(
execution_policy,
[&](auto&& element1)
{
return op(element1);
},
(input1.getImageData())),
input1.getWidth(),
input1.getHeight());
return output;
}
template<typename T>
requires(std::floating_point<T> || std::integral<T>)
T normalDistribution1D(const T x, const T standard_deviation)
{
return std::exp(-x * x / (2 * standard_deviation * standard_deviation));
}
template<typename T>
requires(std::floating_point<T> || std::integral<T>)
T normalDistribution2D(const T xlocation, const T ylocation, const T standard_deviation)
{
return std::exp(-(xlocation * xlocation + ylocation * ylocation) / (2 * standard_deviation * standard_deviation)) / (2 * std::numbers::pi * standard_deviation * standard_deviation);
}
// multiple standard deviations
template<class InputT>
requires(std::floating_point<InputT> || std::integral<InputT>)
constexpr static Image<InputT> gaussianFigure2D(
const size_t xsize, const size_t ysize,
const size_t centerx, const size_t centery,
const InputT standard_deviation_x, const InputT standard_deviation_y)
{
auto output = Image<InputT>(xsize, ysize);
auto row_vector_x = Image<InputT>(xsize, 1);
for (size_t x = 0; x < xsize; ++x)
{
row_vector_x.at(x, 0) = normalDistribution1D(static_cast<InputT>(x) - static_cast<InputT>(centerx), standard_deviation_x);
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
auto row_vector_y = Image<InputT>(ysize, 1);
for (size_t y = 0; y < ysize; ++y)
{
row_vector_y.at(y, 0) = normalDistribution1D(static_cast<InputT>(y) - static_cast<InputT>(centery), standard_deviation_y);
}
for (size_t y = 0; y < ysize; ++y)
{
for (size_t x = 0; x < xsize; ++x)
{
output.at(x, y) = row_vector_x.at(x, 0) * row_vector_y.at(y, 0);
}
}
return output;
}
// single standard deviation
template<class InputT>
requires(std::floating_point<InputT> || std::integral<InputT>)
constexpr static Image<InputT> gaussianFigure2D(
const size_t xsize, const size_t ysize,
const size_t centerx, const size_t centery,
const InputT standard_deviation)
{
return gaussianFigure2D(xsize, ysize, centerx, centery, standard_deviation, standard_deviation);
}
// multiple standard deviations
template<class InputT>
requires(std::floating_point<InputT> || std::integral<InputT>)
constexpr static auto gaussianFigure3D(
const size_t xsize, const size_t ysize, const size_t zsize,
const size_t centerx, const size_t centery, const size_t centerz,
const InputT standard_deviation_x, const InputT standard_deviation_y, const InputT standard_deviation_z)
{
auto output = std::vector<Image<InputT>>();
auto gaussian_image2d = gaussianFigure2D(xsize, ysize, centerx, centery, standard_deviation_x, standard_deviation_y);
for (size_t z = 0; z < zsize; ++z)
{
output.push_back(
multiplies(gaussian_image2d,
Image(xsize, ysize, normalDistribution1D(static_cast<InputT>(z) - static_cast<InputT>(centerz), standard_deviation_z)))
);
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
template<class InputT>
constexpr static Image<InputT> plus(const Image<InputT>& input1)
{
return input1;
}
template<class InputT, class... Args>
constexpr static Image<InputT> plus(const Image<InputT>& input1, const Args&... inputs)
{
return pixelwiseOperation(std::plus<>{}, input1, plus(inputs...));
}
template<class InputT, class... Args>
constexpr static auto plus(const std::vector<Image<InputT>>& input1, const Args&... inputs)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&&... inputs_element)
{
return plus(input1_element, inputs_element...);
}, input1, inputs...);
}
template<class InputT>
constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2)
{
check_size_same(input1, input2);
return pixelwiseOperation(std::minus<>{}, input1, input2);
}
template<class InputT>
constexpr static Image<InputT> subtract(const std::vector<Image<InputT>>& input1, const std::vector<Image<InputT>>& input2)
{
assert(input1.size() == input2.size());
return recursive_transform<1>(
[](auto&& input1_element, auto&& input2_element)
{
return subtract(input1_element, input2_element);
}, input1, input2);
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
template<class InputT = RGB>
requires (std::same_as<InputT, RGB>)
constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2)
{
check_size_same(input1, input2);
Image<InputT> output(input1.getWidth(), input1.getHeight());
for (std::size_t y = 0; y < input1.getHeight(); ++y)
{
for (std::size_t x = 0; x < input1.getWidth(); ++x)
{
for(std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
output.at(x, y).channels[channel_index] =
std::clamp(
input1.at(x, y).channels[channel_index] -
input2.at(x, y).channels[channel_index],
0,
255);
}
}
}
return output;
}
template<class InputT>
constexpr static Image<InputT> multiplies(const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(std::multiplies<>{}, input1, input2);
}
template<class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Image<InputT> multiplies(ExPo execution_policy, const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(execution_policy, std::multiplies<>{}, input1, input2);
}
template<class InputT, class... Args>
constexpr static Image<InputT> multiplies(const Image<InputT>& input1, const Args&... inputs)
{
return pixelwiseOperation(std::multiplies<>{}, input1, multiplies(inputs...));
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
template<class ExPo, class InputT, class... Args>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Image<InputT> multiplies(ExPo execution_policy, const Image<InputT>& input1, const Args&... inputs)
{
return pixelwiseOperation(execution_policy, std::multiplies<>{}, input1, multiplies(inputs...));
}
template<class InputT, class... Args>
constexpr static auto multiplies(const std::vector<Image<InputT>>& input1, const Args&... inputs)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&&... inputs_element)
{
return multiplies(input1_element, inputs_element...);
}, input1, inputs...);
}
template<class InputT>
constexpr static Image<InputT> divides(const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(std::divides<>{}, input1, input2);
}
template<class InputT>
constexpr static auto divides(const std::vector<Image<InputT>>& input1, const std::vector<Image<InputT>>& input2)
{
assert(input1.size() == input2.size());
return recursive_transform<1>(
[](auto&& input1_element, auto&& input2_element)
{
return divides(input1_element, input2_element);
}, input1, input2);
}
template<class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Image<InputT> divides(ExPo execution_policy, const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(execution_policy, std::divides<>{}, input1, input2);
}
template<class InputT>
constexpr static Image<InputT> modulus(const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(std::modulus<>{}, input1, input2);
} | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
template<class InputT>
constexpr static Image<InputT> negate(const Image<InputT>& input1)
{
return pixelwiseOperation(std::negate<>{}, input1);
}
}
template<typename T>
void gaussianFigure3DTest(const size_t size = 3)
{
auto gaussian_image3d = TinyDIP::gaussianFigure3D(
size,
size,
size,
1, 1, 1,
static_cast<T>(3), static_cast<T>(3), static_cast<T>(3));
for(auto each_plane : gaussian_image3d)
{
each_plane.print();
}
return;
}
int main()
{
auto start = std::chrono::system_clock::now();
gaussianFigure3DTest<double>();
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:
0.846482 0.894839 0.846482
0.894839 0.945959 0.894839
0.846482 0.894839 0.846482
0.894839 0.945959 0.894839
0.945959 1 0.945959
0.894839 0.945959 0.894839
0.846482 0.894839 0.846482
0.894839 0.945959 0.894839
0.846482 0.894839 0.846482
Computation finished at Sat Dec 23 13:00:22 2023
elapsed time: 0.00157651
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
Two dimensional gaussian image generator in C++
What changes has been made in the code since last question?
I am trying to implement gaussianFigure3D template function in this post.
Why a new review is being asked for?
Please review gaussianFigure3D template function implementation and all suggestions are welcome. | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
Answer: Structure of a 3D image
Your 2D Image class is not storing a vector of vectors, rather it stores a single vector with all the pixels in the 2D image. But instead of creating a 3D image type, your guassianFigure3D() just returns a std::vector<Image>. This is a less efficient way of storing the pixel data, and also lacks all of the properties of Image, like having an at() function that takes \$x\$, \$y\$ and \$z\$ coordinates, or an operator+() that can add two 3D images together.
Add a vector type to store coordinates
You have to pass 9 parameters to gaussianFigure3D(). That's quite a lot. The more parameters a function has, the easier it is to make mistakes and pass them in the wrong order. It would be much better if you had a type that stored 3D coordinates:
template<typename T>
struct Vec3D {
T x;
T y;
T z;
};
template<typename InputT>
requires(std::floating_point<InputT> || std::integral<InputT>)
constexpr static auto guassianfigure3D(
Vec3D<size_t> size,
Vec3D<size_t> center,
Vec3D<InputT> standard_deviation)
{
…
}; | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c++, image, template, c++20, constrained-templates
Make it more generic
You already had normalDistribution1D() and guassianFigure2D(), and now you added guassianFigure3D(). What if you want to make a four-dimensional Gaussian? A good excercise is to see if you can make the number of dimensions a parameter somehow. You already demonstrate in guassianFigure3D() that the way to construct a higher-dimensional Gaussian is to take one that has one dimension less, and then just do a Cartesian product with a normalDistribution1D(). So you have your generic case and your base case, and can thus write a recursive template function to create Gaussian images of any dimension.
You'll then also want to make Image a template that has a parameter for the number of dimensions it has. Alternatively, you can choose to make the 2D Gaussian the base case, and make higher dimension images just vectors of vectors of … of Image.
C++23 introduced std::mdspan. This might be a very helpful tool here.
Add a scalar multiplication operator
Your Image class can only multiply one image by another. But in guassianFigure3D(), you actually only need to multiply guassian_image2d by a scalar. You work around this by creating a full 2D Image with a uniform value everywhere, but that is just wasting memory and hinders optimization. Consider adding an operator*(ElementT rhs) to Image, then the loop in gaussianFigure3D() can look like:
for (size_t z = 0; z < zsize; ++z)
{
output.push_back(
gaussian_image2d * normalDistribution1D(z - centerz, standard_deviation_z)
);
}
Reserve space for output
You know zsize, so you can already reserve enough space for output. This prevents unnecessary copies and moves of Images. | {
"domain": "codereview.stackexchange",
"id": 45324,
"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++, image, template, c++20, constrained-templates",
"url": null
} |
c, primes
Title: C code for finding prime numbers
Question: I have created a program to find prime numbers up to the 32nd power of 2. It uses the sieve of Eratosthenes. I would appreciate it if you could let me know any bugs or improvements I can make.
/*
* prime32.c
*/
#include <stdio.h>
char isprime1[0x10000];
char isprime2[0x10000];
typedef unsigned int UINT;
void solve1() {
int i, j;
for (i = 0; i < 0x10000; ++i) {
isprime1[i] = 1;
}
isprime1[0] = 0;
for (i = 2; i <= 0x10000; ++i) {
if (!isprime1[i-1]) continue;
for (j = 2 * i - 1; j < 0x10000; j += i) {
isprime1[j] = 0;
}
}
}
void solve2(UINT start) {
long long int i, j, offset;
for (i = 0xFFFF; i >= 0; --i)
isprime2[i] = 1;
for (i = 1; i <= 0x10000; ++i) {
if (!isprime1[i-1]) continue;
offset = (start + 0xFFFF) % i;
for (j = 0xFFFF - offset; j >= 0; j -= i) {
isprime2[j] = 0;
}
}
}
void print1(FILE *fp) {
int i;
for (i = 0; i < 0x10000; ++i) {
if (!isprime1[i]) continue;
fprintf(fp, "%d\n", i + 1);
}
}
void print2(FILE *fp, UINT start) {
long long int i;
for (i = 0; i < 0x10000; ++i) {
if (!isprime2[i]) continue;
fprintf(fp, "%lld\n", start + i);
}
}
int main() {
FILE *fp;
UINT i;
solve1();
fp = fopen("prime32.out", "w");
print1(fp);
for (i = 0x10001; i != 1; i += 0x10000) {
solve2(i);
print2(fp, i);
}
fclose(fp);
return 0;
}
Answer:
int i, j;
for (i = 0; i < 0x10000; ++i) {
Largest int may be as small as 32767 (0x7FFF), so this loop may be infinite when targeting such platforms. I recommend you include <stdint.h> and use (e.g.) uint_fast32_t i.
fp = fopen("prime32.out", "w");
print1(fp); | {
"domain": "codereview.stackexchange",
"id": 45325,
"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, primes",
"url": null
} |
c, primes
fp = fopen("prime32.out", "w");
print1(fp);
When fopen() fails (as it may well do if this program is run with a working directory that is not writable by the user), then it returns a null pointer. We should test that fp is non-null before attempting to use it.
I recommend simply writing to standard output, rather than to a hard-coded file name - that's more flexible, as a user can connect that stream to anywhere they want - a different file, or input to another program, for example.
The isprime1[i] = 1 loop of each function would be more readable if replaced with memset(isprime1, 1, sizeof isprime1). memset() is declared in <string.h>.
I don't like the magic numbers 0x10000 and 0xFFFF sprinkled all over the place. If we changed one of these, would we easily know which others to change, and which to leave? Defining relevant constants would help with that.
There are more efficient implementations of the Sieve of Eratosthenes - for example, we only need to start marking off multiples of prime i beginning at i*i, as lower values have already been accounted for earlier in the process.
I don't really see the point of solve2() instead of simply making isprime1 larger - perhaps some explanatory comments would help? | {
"domain": "codereview.stackexchange",
"id": 45325,
"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, primes",
"url": null
} |
c++, game-of-life
Title: Conway's Game of Life In C++17
Question: I implemented Conway's Game of Life in C++17. To make it easy to copy paste. I have merged my .h and .cpp files. Any improvements or any C++20 features that I can leverage are greatly appreciated.
To run the code build it using cmake and run the following command
cat .<Path_to_life_file>/life.txt | .<Path_to_bin_dir>/Conway
The game is paused at boot. Press p to toggle play-pause. Left-click adds a new live cell. Right-click kills a cell.
src/main.cpp
// ------------ position.h ---------------------- //
#include <cstddef>
#include <cstdint>
#include <boost/functional/hash.hpp>
using Distance = int;
struct Position {
Distance x;
Distance y;
};
bool operator==(Position const & p1, Position const & p2){
return (p1.x == p2.x) && (p1.y == p2.y);
}
std::ostream& operator<<(std::ostream & os, Position const & p){
os << "[" << p.x << ", " << p.y << "]";
return os;
}
template <>
struct std::hash<Position>
{
std::size_t operator()(const Position& p) const noexcept {
auto seed = std::size_t{};
boost::hash_combine(seed, p.x);
boost::hash_combine(seed, p.y);
return seed;
}
};
[[nodiscard]]
std::array<Position, 8> get_neigbhors(Position const & position) noexcept {
return {{
{position.x - 1, position.y + 1},
{position.x - 0, position.y - 1},
{position.x + 1, position.y - 1},
{position.x + 1, position.y - 0},
{position.x + 1, position.y + 1},
{position.x + 0, position.y + 1},
{position.x - 1, position.y - 1},
{position.x - 1, position.y - 0},
}};
}
// ------------ game_of_life.h ---------------------- //
#include <algorithm>
#include <unordered_set>
#include <vector>
class GameOfLife {
public:
GameOfLife(std::vector<Position> const & live_cells)
: m_live_cells{cbegin(live_cells), cend(live_cells)} {} | {
"domain": "codereview.stackexchange",
"id": 45326,
"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++, game-of-life",
"url": null
} |
c++, game-of-life
void step(){
auto kill_set = std::unordered_set<Position>{};
for(auto const & cell : m_live_cells){
if(should_die(cell)){
kill_set.insert(cell);
}
}
auto born_set = std::unordered_set<Position>{};
for(auto const & cell : m_live_cells){
auto neighbors = get_neigbhors(cell);
for(auto const & neighbor : neighbors){
if(should_be_born(neighbor)){
born_set.insert(neighbor);
}
}
}
for(auto const & cell : kill_set){
m_live_cells.erase(cell);
}
for(auto const & cell : born_set){
m_live_cells.insert(cell);
}
}
[[nodiscard]]
std::unordered_set<Position> const & get_live_cells() const noexcept {
return m_live_cells;
}
void add_cell(Position position){
m_live_cells.insert(position);
}
void remove_cell(Position position){
m_live_cells.erase(position);
}
[[nodiscard]]
bool should_die(Position const & position) const noexcept {
auto const neighbors = get_neigbhors(position);
auto num_alive_neighbors = std::count_if(
cbegin(neighbors), cend(neighbors),
[&](auto const & neighbor) { return m_live_cells.count(neighbor); }
);
return num_alive_neighbors < 2 || num_alive_neighbors > 3;
}
[[nodiscard]]
bool should_be_born(Position const & position) const noexcept {
auto const neighbors = get_neigbhors(position);
auto num_alive_neighbors = std::count_if(
cbegin(neighbors), cend(neighbors),
[&](auto const & neighbor) { return m_live_cells.count(neighbor); }
);
return num_alive_neighbors == 3;
}
std::unordered_set<Position> m_live_cells;
};
// ------------ ui.h ---------------------- // | {
"domain": "codereview.stackexchange",
"id": 45326,
"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++, game-of-life",
"url": null
} |
c++, game-of-life
std::unordered_set<Position> m_live_cells;
};
// ------------ ui.h ---------------------- //
#include <SFML/Graphics.hpp>
template<typename AddCellCallback, typename RemoveCellCallback>
class UI {
public:
UI(AddCellCallback add_cell_callback, RemoveCellCallback remove_cell_callback)
: m_window{ { 1920u, 1080u }, "Conway Game Of Life" }
, m_add_cell_callback(add_cell_callback)
, m_remove_cell_callback(remove_cell_callback)
{
m_window.setFramerateLimit(144);
m_window.setKeyRepeatEnabled(false);
}
void handle_user_input(){
for (auto event = sf::Event{}; m_window.pollEvent(event);)
{
switch (event.type)
{
case sf::Event::Closed:
m_window.close();
break;
case sf::Event::KeyPressed:
if(sf::Keyboard::isKeyPressed(sf::Keyboard::P)){
m_is_playing = !m_is_playing;
}
case sf::Event::MouseButtonPressed:
{
auto click_position = sf::Mouse::getPosition(m_window);
auto game_position = Position{
static_cast<Distance>(click_position.x / m_scale),
static_cast<Distance>(click_position.y / m_scale)
};
if(sf::Mouse::isButtonPressed(sf::Mouse::Left)){
m_add_cell_callback(game_position);
} else if(sf::Mouse::isButtonPressed(sf::Mouse::Right)){
m_remove_cell_callback(game_position);
}
break;
}
default:
break;
}
}
}
[[nodiscard]]
bool is_running() const noexcept {
return m_window.isOpen();
}
[[nodiscard]]
bool is_playing() const noexcept {
return m_is_playing;
} | {
"domain": "codereview.stackexchange",
"id": 45326,
"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++, game-of-life",
"url": null
} |
c++, game-of-life
[[nodiscard]]
bool is_playing() const noexcept {
return m_is_playing;
}
void draw(std::unordered_set<Position> live_cells){
m_window.clear();
for(auto const & cell : live_cells){
auto rect = sf::RectangleShape{{m_scale, m_scale}};
rect.setFillColor({150, 150, 150});
rect.setPosition({
m_scale*cell.x,
m_scale*cell.y
});
m_window.draw(rect);
}
m_window.display();
}
private:
bool m_is_playing = false;
sf::RenderWindow m_window;
AddCellCallback m_add_cell_callback;
RemoveCellCallback m_remove_cell_callback;
static constexpr float m_scale = float{10.0};
};
// ------------ main.cpp ---------------------- //
#include <iostream>
#include <sstream>
#include <chrono>
int main()
{
auto game = std::invoke([](){
auto live_cells = std::vector<Position>{};
auto line = std::string{};
for(auto x = int{0}; std::getline(std::cin, line); ++x){
for(auto y = int{0}; y < line.size(); ++y){
if(line[y] == 'O'){
live_cells.push_back({x, y});
}
}
}
return GameOfLife{live_cells};
});
auto ui = UI{
[&](auto const & p) { game.add_cell(p); },
[&](auto const & p) { game.remove_cell(p); }
};
auto last_update_time = std::chrono::steady_clock::now();
while (ui.is_running())
{
ui.handle_user_input();
auto now = std::chrono::steady_clock::now();
if(now - last_update_time > std::chrono::milliseconds{100}){
last_update_time = now;
ui.draw(game.get_live_cells());
if(ui.is_playing()){
game.step();
}
}
}
}
CMakeList.txt
cmake_minimum_required(VERSION 3.16)
project(Conway LANGUAGES CXX) | {
"domain": "codereview.stackexchange",
"id": 45326,
"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++, game-of-life",
"url": null
} |
c++, game-of-life
CMakeList.txt
cmake_minimum_required(VERSION 3.16)
project(Conway LANGUAGES CXX)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
option(BUILD_SHARED_LIBS "Build shared libraries" OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include(FetchContent)
FetchContent_Declare(SFML
GIT_REPOSITORY https://github.com/SFML/SFML.git
GIT_TAG 2.6.x)
FetchContent_MakeAvailable(SFML)
find_package(Boost)
add_executable(Conway src/main.cpp)
target_link_libraries(Conway PRIVATE sfml-graphics)
target_compile_features(Conway PRIVATE cxx_std_17)
if(WIN32)
add_custom_command(
TARGET Conway
COMMENT "Copy OpenAL DLL"
PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${SFML_SOURCE_DIR}/extlibs/bin/$<IF:$<EQUAL:${CMAKE_SIZEOF_VOID_P},8>,x64,x86>/openal32.dll $<TARGET_FILE_DIR:Conway>
VERBATIM)
endif()
install(TARGETS Conway)
life.txt
.O.
OO.
O.O
..
..
..
.......O.
......OO.
......O.O
..
..
..
..
..
..
..
..
..
...................O.
..................OO.
..................O.O
..
..
..
.........................O.
........................OO.
........................O.O
..
..
..................O....................
.................O.OO..........O.......
.................O.OO.........OO.......
..................OO..........O.O......
.......................................
.......OO............OO................
.......OO............OO................
.....................................O.
....................................OO.
......O.O...........................O.O
.....O..................OO....
OO..O....O..........OO.O..O.OO
OO.O..O.OO..........OO..O....O
....OO...................O....
..........................O.O. | {
"domain": "codereview.stackexchange",
"id": 45326,
"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++, game-of-life",
"url": null
} |
c++, game-of-life
Answer: Consider using a library for vector math
You created your own 2D vector type Position. This is much better than passing x and y indiviually everywhere. However, consider using a library that provides such a type, because those libraries typically supply much more helpful functions and operator overloads for those types.
Container types
You store the positions of the live cells in a std::unordered_set. It has the advantage of being simple and handling a very sparse field efficiently, and you don't have to know the size of the grid beforehand. There are other ways to store the state with different trade-offs, but for this simple implementation it's fine.
However, there are other choices for containers that are not so great. For example, the kill_set should probably just be a std::vector<Position>s: there is no possibility of adding duplicates to them, and std::vector is much more efficient here. You could also consider using this for the born_set; while it might add some duplicates, this doesn't affect m_live_cells in the end.
In the constructor of GameOfLife you require the initial set of live cells to be passed as a std::vector. But what if you have the initial set in a different container? Consider making this a template so it accepts any type of range:
class GameOfLife {
public:
template<typename T>
GameOfLife(const T& live_cells)
: m_live_cells{std::begin(live_cells), std::end(live_cells)} {}
…
}; | {
"domain": "codereview.stackexchange",
"id": 45326,
"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++, game-of-life",
"url": null
} |
c++, game-of-life
Avoid unnecessary copies
UI::draw() takes the set of live cells by value, which is unnecessary. Just pass a const reference.
Avoid unnecessarily looping over the data
In step() you visit every live cell twice; once to check if it needs to be killed, and once to check if neighbors need to be born. Consider looping only once and handle both cases at the same time. Related to this:
Avoid code duplication
should_die() and should_be_born() are the same, except for the condition in the return statement. Consider writing a single function that calculates the number of live neighbors.
Avoid busy loops
You have a busy loop in main() waiting for 100 milliseconds to pass before calling ui.draw(). This will use 100% of one CPU core for no good reason. Unfortunately, SFML doesn't have the concept of timer events. The next best thing is to ensure vsync is enabled using:
m_window.setVerticalSyncEnabled(true);
This way, a call to m_window.display() will automatically wait until the next frame can be displayed on the screen. That will still not be ideal, since framerates vary depending on the monitor, and you might not want the game of life to run so fast. Still, you can just call ui.draw() unconditionally and only do a step if 100 milliseconds expired:
using clock = std::chrono::steady_clock;
auto interval = std::chrono::milliseconds{100};
auto last_update_time = clock::now();
while (ui.is_running()) {
ui.handle_user_input();
ui.draw();
auto now = clock::now();
if(now - last_update_time > interval) {
last_update_time += interval;
if(ui.is_playing()) {
game.step();
}
}
}
Questionable choices
I'm not sure why you use a lambda to create game inside main(). I would rather create a function that reads the input and returns a container of live cells, so that it looks like:
static auto read_live_cells() {
auto live_cells = std::vector<Position>{};
…
return live_cells;
} | {
"domain": "codereview.stackexchange",
"id": 45326,
"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++, game-of-life",
"url": null
} |
c++, game-of-life
int main() {
auto game = GameOfLive(read_live_cells());
…
}
You also don't need to use std::invoke() to directly invoke a lambda function, you can write [](){…}() instead. Although with that many brackets perhaps the explicit std::invoke() makes it more clear what is going on here.
Instead of making UI a template to handle the callbacks, consider using std::function instead. | {
"domain": "codereview.stackexchange",
"id": 45326,
"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++, game-of-life",
"url": null
} |
c++, image, template, classes, c++20
Title: Three dimensional data structure in C++
Question: This is a follow-up question for Three dimensional gaussian image generator in C++. Considering the suggestion from G. Sliepen:
Structure of a 3D image
Your 2D Image class is not storing a vector of vectors, rather it stores a single vector with all the pixels in the 2D image. But instead of creating a 3D image type, your guassianFigure3D() just returns a std::vector<Image>. This is a less efficient way of storing the pixel data, and also lacks all of the properties of Image, like having an at() function that takes \$x\$, \$y\$ and \$z\$ coordinates, or an operator+() that can add two 3D images together.
I am trying to create 3D data structure Cube in this post and there are several properties:
at() function that takes \$x\$, \$y\$ and \$z\$ coordinates for element access in Cube class.
print function to print values.
operator+=, operator-=, operator+(), operator-() for adding / subtracting two Cubes.
The experimental implementation
Cube Template Class (in file "cube.h")
namespace TinyDIP
{
template <typename ElementT>
class Cube
{
public:
Cube() = default;
Cube(const std::size_t newWidth, const std::size_t newHeight, const std::size_t newDepth):
width(width),
height(height),
depth(newDepth),
data(width * height * depth) { }
Cube(const int newWidth, const int newHeight, const int newDepth, ElementT initVal):
width(newWidth),
height(newHeight),
depth(newDepth),
data(width * height * depth, initVal) {} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
Cube(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight, const std::size_t newDepth):
width(newWidth),
height(newHeight),
depth(newDepth)
{
if (input.size() != newWidth * newHeight * newDepth)
{
throw std::runtime_error("Data input and the given size are mismatched!");
}
data = input;
}
Cube(const std::vector<Image<ElementT>>& input)
{
width = input[0].getWidth();
height = input[0].getHeight();
depth = input.size();
data.resize(width * height * depth);
for (std::size_t z = 0; z < input.size(); ++z)
{
auto image = input[z];
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
data[z * width * height + y * width + x] = image.at(x, y);
}
}
}
return;
}
constexpr ElementT& at(const unsigned int x, const unsigned int y, const unsigned int z)
{
checkBoundary(x, y, z);
return data[z * width * height + y * width + x];
}
constexpr ElementT const& at(const unsigned int x, const unsigned int y, const unsigned int z) const
{
checkBoundary(x, y, z);
return data[z * width * height + y * width + x];
}
constexpr auto getSizeX() const noexcept
{
return width;
}
constexpr auto getSizeY() const noexcept
{
return height;
}
constexpr auto getSizeZ() const noexcept
{
return depth;
}
constexpr auto getWidth() const noexcept
{
return width;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
constexpr auto getWidth() const noexcept
{
return width;
}
constexpr auto getHeight() const noexcept
{
return height;
}
constexpr auto getDepth() const noexcept
{
return depth;
}
std::vector<ElementT> const& getData() const noexcept { return data; } // expose the internal data
void print(std::string separator = "\t", std::ostream& os = std::cout) const
{
for(std::size_t z = 0; z < depth; ++z)
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y, z) << separator;
}
os << "\n";
}
os << "\n";
}
os << "\n";
return;
}
friend std::ostream& operator<<(std::ostream& os, const Cube<ElementT>& rhs)
{
const std::string separator = "\t";
rhs.print(separator, os);
return os;
}
Cube<ElementT>& operator+=(const Cube<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(data), std::ranges::cend(data), std::ranges::cbegin(rhs.data),
std::ranges::begin(data), std::plus<>{});
return *this;
}
Cube<ElementT>& operator-=(const Cube<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(data), std::ranges::cend(data), std::ranges::cbegin(rhs.data),
std::ranges::begin(data), std::minus<>{});
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
Cube<ElementT>& operator*=(const Cube<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(data), std::ranges::cend(data), std::ranges::cbegin(rhs.data),
std::ranges::begin(data), std::multiplies<>{});
return *this;
}
Cube<ElementT>& operator/=(const Cube<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(data), std::ranges::cend(data), std::ranges::cbegin(rhs.data),
std::ranges::begin(data), std::divides<>{});
return *this;
}
friend bool operator==(Cube<ElementT> const&, Cube<ElementT> const&) = default;
friend bool operator!=(Cube<ElementT> const&, Cube<ElementT> const&) = default;
friend Cube<ElementT> operator+(Cube<ElementT> input1, const Cube<ElementT>& input2)
{
return input1 += input2;
}
friend Cube<ElementT> operator-(Cube<ElementT> input1, const Cube<ElementT>& input2)
{
return input1 -= input2;
}
friend Cube<ElementT> operator*(Cube<ElementT> input1, ElementT input2)
{
return multiplies(input1, input2);
}
Cube<ElementT>& operator=(Cube<ElementT> const& input) = default; // Copy Assign
Cube<ElementT>& operator=(Cube<ElementT>&& other) = default; // Move Assign
Cube(const Cube<ElementT> &input) = default; // Copy Constructor
Cube(Cube<ElementT> &&input) = default; // Move Constructor
private:
std::size_t width;
std::size_t height;
std::size_t depth;
std::vector<ElementT> data; | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
void checkBoundary(const size_t x, const size_t y, const size_t z) const
{
if (x >= width)
throw std::out_of_range("Given x out of range!");
if (y >= height)
throw std::out_of_range("Given y out of range!");
if (z >= depth)
throw std::out_of_range("Given z out of range!");
}
};
}
Helper Functions for Cube (in file "cube_operations.h")
namespace TinyDIP
{
template<typename ElementT>
constexpr bool is_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
return x.getSizeX() == y.getSizeX();
}
template<typename ElementT>
constexpr bool is_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
return is_width_same(x, y) && is_width_same(y, z);
}
template<typename ElementT>
constexpr bool is_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
return x.getSizeY() == y.getSizeY();
}
template<typename ElementT>
constexpr bool is_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
return is_height_same(x, y) && is_height_same(y, z);
}
template<typename ElementT>
constexpr bool is_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
return x.getSizeZ() == y.getSizeZ();
}
template<typename ElementT>
constexpr bool is_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
return is_depth_same(x, y) && is_depth_same(y, z);
}
template<typename ElementT>
constexpr bool is_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
return is_width_same(x, y) && is_height_same(x, y) && is_depth_same(x, y);
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<typename ElementT>
constexpr bool is_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
return is_size_same(x, y) && is_size_same(y, z);
}
template<typename ElementT>
constexpr void assert_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
assert(is_width_same(x, y));
}
template<typename ElementT>
constexpr void assert_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
assert(is_width_same(x, y, z));
}
template<typename ElementT>
constexpr void assert_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
assert(is_height_same(x, y));
}
template<typename ElementT>
constexpr void assert_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
assert(is_height_same(x, y, z));
}
template<typename ElementT>
constexpr void assert_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
assert(is_depth_same(x, y));
}
template<typename ElementT>
constexpr void assert_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
assert(is_depth_same(x, y));
assert(is_depth_same(y, z));
}
template<typename ElementT>
constexpr void assert_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
assert_width_same(x, y);
assert_height_same(x, y);
assert_depth_same(x, y);
}
template<typename ElementT>
constexpr void assert_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
assert_size_same(x, y);
assert_size_same(y, z);
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<typename ElementT>
constexpr void check_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
if (!is_width_same(x, y))
throw std::runtime_error("Width mismatched!");
}
template<typename ElementT>
constexpr void check_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
if (!is_height_same(x, y))
throw std::runtime_error("Height mismatched!");
}
template<typename ElementT>
constexpr void check_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
if (!is_depth_same(x, y))
throw std::runtime_error("Depth mismatched!");
}
template<typename ElementT>
constexpr void check_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
check_width_same(x, y);
check_height_same(x, y);
check_depth_same(x, y);
}
// voxelwiseOperation template function implementation
template<std::size_t unwrap_level = 1, class... Args>
constexpr static auto voxelwiseOperation(auto op, const Args&... inputs)
{
auto output = Cube(
recursive_transform<unwrap_level>(
[&](auto&& element1, auto&&... elements)
{
return op(element1, elements...);
},
inputs.getData()...),
first_of(inputs...).getWidth(),
first_of(inputs...).getHeight(),
first_of(inputs...).getDepth());
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<std::size_t unwrap_level = 1, class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static auto voxelwiseOperation(ExPo execution_policy, auto op, const Image<InputT>& input1)
{
auto output = Cube(
recursive_transform<unwrap_level>(
execution_policy,
[&](auto&& element1)
{
return op(element1);
},
(input1.getData())),
input1.getWidth(),
input1.getHeight(),
input1.getDepth());
return output;
}
// plus template function implementation
template<class InputT>
constexpr static Cube<InputT> plus(const Cube<InputT>& input1)
{
return input1;
}
template<class InputT, class... Args>
constexpr static Cube<InputT> plus(const Cube<InputT>& input1, const Args&... inputs)
{
return voxelwiseOperation(std::plus<>{}, input1, plus(inputs...));
}
template<class InputT, class... Args>
constexpr static auto plus(const std::vector<Cube<InputT>>& input1, const Args&... inputs)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&&... inputs_element)
{
return plus(input1_element, inputs_element...);
}, input1, inputs...);
}
// subtract template function implementation
template<class InputT>
constexpr static Cube<InputT> subtract(const Cube<InputT>& input1, const Cube<InputT>& input2)
{
check_size_same(input1, input2);
return voxelwiseOperation(std::minus<>{}, input1, input2);
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<class InputT>
constexpr static auto subtract(const std::vector<Cube<InputT>>& input1, const std::vector<Cube<InputT>>& input2)
{
assert(input1.size() == input2.size());
return recursive_transform<1>(
[](auto&& input1_element, auto&& input2_element)
{
return subtract(input1_element, input2_element);
}, input1, input2);
}
// multiplies template function implementation
template<class InputT>
constexpr static Cube<InputT> multiplies(const Cube<InputT>& input1, const Cube<InputT>& input2)
{
return voxelwiseOperation(std::multiplies<>{}, input1, input2);
}
template<class InputT, class TimesT>
requires(std::floating_point<TimesT> || std::integral<TimesT>)
constexpr static Cube<InputT> multiplies(const Cube<InputT>& input1, const TimesT times)
{
return multiplies(
input1,
Cube(input1.getWidth(), input1.getHeight(), input1.getDepth(), times)
);
}
template<class InputT, class TimesT>
requires(std::floating_point<TimesT> || std::integral<TimesT>)
constexpr static Cube<InputT> multiplies(const TimesT times, const Cube<InputT>& input1)
{
return multiplies(input1, times);
}
template<class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Cube<InputT> multiplies(ExPo execution_policy, const Cube<InputT>& input1, const Cube<InputT>& input2)
{
return voxelwiseOperation(execution_policy, std::multiplies<>{}, input1, input2);
}
template<class InputT>
constexpr static Cube<InputT> divides(const Cube<InputT>& input1, const Cube<InputT>& input2)
{
return voxelwiseOperation(std::divides<>{}, input1, input2);
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<class InputT>
constexpr static auto divides(const std::vector<Cube<InputT>>& input1, const std::vector<Cube<InputT>>& input2)
{
assert(input1.size() == input2.size());
return recursive_transform<1>(
[](auto&& input1_element, auto&& input2_element)
{
return divides(input1_element, input2_element);
}, input1, input2);
}
template<class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Cube<InputT> divides(ExPo execution_policy, const Cube<InputT>& input1, const Cube<InputT>& input2)
{
return voxelwiseOperation(execution_policy, std::divides<>{}, input1, input2);
}
template<class InputT>
constexpr static Cube<InputT> modulus(const Cube<InputT>& input1, const Cube<InputT>& input2)
{
return voxelwiseOperation(std::modulus<>{}, input1, input2);
}
template<class InputT>
constexpr static Image<InputT> negate(const Image<InputT>& input1)
{
return voxelwiseOperation(std::negate<>{}, input1);
}
}
Full Testing Code
The full testing code:
// Three dimensional data structure in C++
// Developed by Jimmy Hu
#include <algorithm>
#include <cassert> // for assert
#include <chrono> // for std::chrono::system_clock::now
#include <cmath> // for std::exp
#include <concepts>
#include <execution> // for std::is_execution_policy_v
#include <iostream> // for std::cout
#include <vector>
struct RGB
{
std::uint8_t channels[3];
};
using GrayScale = std::uint8_t;
// image.h
namespace TinyDIP
{
template <typename ElementT>
class Image
{
public:
Image() = default;
Image(const std::size_t width, const std::size_t height):
width(width),
height(height),
image_data(width * height) { } | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
Image(const std::size_t width, const std::size_t height, const ElementT initVal):
width(width),
height(height),
image_data(width * height, initVal) {}
Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight):
width(newWidth),
height(newHeight)
{
if (input.size() != newWidth * newHeight)
{
throw std::runtime_error("Image data input and the given size are mismatched!");
}
image_data = input;
}
Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight):
width(newWidth),
height(newHeight)
{
if (input.size() != newWidth * newHeight)
{
throw std::runtime_error("Image data input and the given size are mismatched!");
}
image_data = std::move(input); // Reference: https://stackoverflow.com/a/51706522/6667035
}
Image(const std::vector<std::vector<ElementT>>& input)
{
height = input.size();
width = input[0].size();
for (auto& rows : input)
{
image_data.insert(image_data.end(), std::ranges::begin(input), std::ranges::end(input)); // flatten
}
return;
}
constexpr ElementT& at(const unsigned int x, const unsigned int y)
{
checkBoundary(x, y);
return image_data[y * width + x];
}
constexpr ElementT const& at(const unsigned int x, const unsigned int y) const
{
checkBoundary(x, y);
return image_data[y * width + x];
}
constexpr std::size_t getWidth() const
{
return width;
}
constexpr std::size_t getHeight() const noexcept
{
return height;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
constexpr auto getSize() noexcept
{
return std::make_tuple(width, height);
}
std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data
void print(std::string separator = "\t", std::ostream& os = std::cout) const
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y) << separator;
}
os << "\n";
}
os << "\n";
return;
}
// Enable this function if ElementT = RGB
void print(std::string separator = "\t", std::ostream& os = std::cout) const
requires(std::same_as<ElementT, RGB>)
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
os << "( ";
for (std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y).channels[channel_index] << separator;
}
os << ")" << separator;
}
os << "\n";
}
os << "\n";
return;
}
friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs)
{
const std::string separator = "\t";
rhs.print(separator, os);
return os;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
Image<ElementT>& operator+=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::plus<>{});
return *this;
}
Image<ElementT>& operator-=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::minus<>{});
return *this;
}
Image<ElementT>& operator*=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::multiplies<>{});
return *this;
}
Image<ElementT>& operator/=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::divides<>{});
return *this;
}
friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default;
friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default;
friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 += input2;
}
friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 -= input2;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
friend Image<ElementT> operator*(Image<ElementT> input1, ElementT input2)
{
return multiplies(input1, input2);
}
friend Image<ElementT> operator*(ElementT input1, Image<ElementT> input2)
{
return multiplies(input2, input1);
}
Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign
Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign
Image(const Image<ElementT> &input) = default; // Copy Constructor
Image(Image<ElementT> &&input) = default; // Move Constructor
#ifdef USE_BOOST_SERIALIZATION
void Save(std::string filename)
{
const std::string filename_with_extension = filename + ".dat";
// Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c
std::ofstream ofs(filename_with_extension, std::ios::binary);
boost::archive::binary_oarchive ArchiveOut(ofs);
// write class instance to archive
ArchiveOut << *this;
// archive and stream closed when destructors are called
ofs.close();
}
#endif
private:
std::size_t width;
std::size_t height;
std::vector<ElementT> image_data;
void checkBoundary(const size_t x, const size_t y) const
{
if (x >= width)
throw std::out_of_range("Given x out of range!");
if (y >= height)
throw std::out_of_range("Given y out of range!");
}
};
template<typename T, typename ElementT>
concept is_Image = std::is_same_v<T, Image<ElementT>>;
}
// cube.h
namespace TinyDIP
{
template <typename ElementT>
class Cube
{
public:
Cube() = default; | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
Cube(const std::size_t newWidth, const std::size_t newHeight, const std::size_t newDepth):
width(width),
height(height),
depth(newDepth),
data(width * height * depth) { }
Cube(const int newWidth, const int newHeight, const int newDepth, ElementT initVal):
width(newWidth),
height(newHeight),
depth(newDepth),
data(width * height * depth, initVal) {}
Cube(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight, const std::size_t newDepth):
width(newWidth),
height(newHeight),
depth(newDepth)
{
if (input.size() != newWidth * newHeight * newDepth)
{
throw std::runtime_error("Data input and the given size are mismatched!");
}
data = input;
}
Cube(const std::vector<Image<ElementT>>& input)
{
width = input[0].getWidth();
height = input[0].getHeight();
depth = input.size();
data.resize(width * height * depth);
for (std::size_t z = 0; z < input.size(); ++z)
{
auto image = input[z];
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
data[z * width * height + y * width + x] = image.at(x, y);
}
}
}
return;
}
constexpr ElementT& at(const unsigned int x, const unsigned int y, const unsigned int z)
{
checkBoundary(x, y, z);
return data[z * width * height + y * width + x];
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
constexpr ElementT const& at(const unsigned int x, const unsigned int y, const unsigned int z) const
{
checkBoundary(x, y, z);
return data[z * width * height + y * width + x];
}
constexpr auto getSizeX() const noexcept
{
return width;
}
constexpr auto getSizeY() const noexcept
{
return height;
}
constexpr auto getSizeZ() const noexcept
{
return depth;
}
constexpr auto getWidth() const noexcept
{
return width;
}
constexpr auto getHeight() const noexcept
{
return height;
}
constexpr auto getDepth() const noexcept
{
return depth;
}
std::vector<ElementT> const& getData() const noexcept { return data; } // expose the internal data
void print(std::string separator = "\t", std::ostream& os = std::cout) const
{
for(std::size_t z = 0; z < depth; ++z)
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y, z) << separator;
}
os << "\n";
}
os << "\n";
}
os << "\n";
return;
}
friend std::ostream& operator<<(std::ostream& os, const Cube<ElementT>& rhs)
{
const std::string separator = "\t";
rhs.print(separator, os);
return os;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
Cube<ElementT>& operator+=(const Cube<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(data), std::ranges::cend(data), std::ranges::cbegin(rhs.data),
std::ranges::begin(data), std::plus<>{});
return *this;
}
Cube<ElementT>& operator-=(const Cube<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(data), std::ranges::cend(data), std::ranges::cbegin(rhs.data),
std::ranges::begin(data), std::minus<>{});
return *this;
}
Cube<ElementT>& operator*=(const Cube<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(data), std::ranges::cend(data), std::ranges::cbegin(rhs.data),
std::ranges::begin(data), std::multiplies<>{});
return *this;
}
Cube<ElementT>& operator/=(const Cube<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(data), std::ranges::cend(data), std::ranges::cbegin(rhs.data),
std::ranges::begin(data), std::divides<>{});
return *this;
}
friend bool operator==(Cube<ElementT> const&, Cube<ElementT> const&) = default;
friend bool operator!=(Cube<ElementT> const&, Cube<ElementT> const&) = default;
friend Cube<ElementT> operator+(Cube<ElementT> input1, const Cube<ElementT>& input2)
{
return input1 += input2;
}
friend Cube<ElementT> operator-(Cube<ElementT> input1, const Cube<ElementT>& input2)
{
return input1 -= input2;
}
friend Cube<ElementT> operator*(Cube<ElementT> input1, ElementT input2)
{
return multiplies(input1, input2);
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
Cube<ElementT>& operator=(Cube<ElementT> const& input) = default; // Copy Assign
Cube<ElementT>& operator=(Cube<ElementT>&& other) = default; // Move Assign
Cube(const Cube<ElementT> &input) = default; // Copy Constructor
Cube(Cube<ElementT> &&input) = default; // Move Constructor
private:
std::size_t width;
std::size_t height;
std::size_t depth;
std::vector<ElementT> data;
void checkBoundary(const size_t x, const size_t y, const size_t z) const
{
if (x >= width)
throw std::out_of_range("Given x out of range!");
if (y >= height)
throw std::out_of_range("Given y out of range!");
if (z >= depth)
throw std::out_of_range("Given z out of range!");
}
};
}
// cube_operations.h
namespace TinyDIP
{
template<typename ElementT>
constexpr bool is_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
return x.getSizeX() == y.getSizeX();
}
template<typename ElementT>
constexpr bool is_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
return is_width_same(x, y) && is_width_same(y, z);
}
template<typename ElementT>
constexpr bool is_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
return x.getSizeY() == y.getSizeY();
}
template<typename ElementT>
constexpr bool is_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
return is_height_same(x, y) && is_height_same(y, z);
}
template<typename ElementT>
constexpr bool is_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
return x.getSizeZ() == y.getSizeZ();
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<typename ElementT>
constexpr bool is_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
return is_depth_same(x, y) && is_depth_same(y, z);
}
template<typename ElementT>
constexpr bool is_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
return is_width_same(x, y) && is_height_same(x, y) && is_depth_same(x, y);
}
template<typename ElementT>
constexpr bool is_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
return is_size_same(x, y) && is_size_same(y, z);
}
template<typename ElementT>
constexpr void assert_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
assert(is_width_same(x, y));
}
template<typename ElementT>
constexpr void assert_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
assert(is_width_same(x, y, z));
}
template<typename ElementT>
constexpr void assert_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
assert(is_height_same(x, y));
}
template<typename ElementT>
constexpr void assert_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
assert(is_height_same(x, y, z));
}
template<typename ElementT>
constexpr void assert_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
assert(is_depth_same(x, y));
}
template<typename ElementT>
constexpr void assert_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
assert(is_depth_same(x, y));
assert(is_depth_same(y, z));
}
template<typename ElementT>
constexpr void assert_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
assert_width_same(x, y);
assert_height_same(x, y);
assert_depth_same(x, y);
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<typename ElementT>
constexpr void assert_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y, const Cube<ElementT>& z)
{
assert_size_same(x, y);
assert_size_same(y, z);
}
template<typename ElementT>
constexpr void check_width_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
if (!is_width_same(x, y))
throw std::runtime_error("Width mismatched!");
}
template<typename ElementT>
constexpr void check_height_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
if (!is_height_same(x, y))
throw std::runtime_error("Height mismatched!");
}
template<typename ElementT>
constexpr void check_depth_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
if (!is_depth_same(x, y))
throw std::runtime_error("Depth mismatched!");
}
template<typename ElementT>
constexpr void check_size_same(const Cube<ElementT>& x, const Cube<ElementT>& y)
{
check_width_same(x, y);
check_height_same(x, y);
check_depth_same(x, y);
}
// voxelwiseOperation template function implementation
template<std::size_t unwrap_level = 1, class... Args>
constexpr static auto voxelwiseOperation(auto op, const Args&... inputs)
{
auto output = Cube(
recursive_transform<unwrap_level>(
[&](auto&& element1, auto&&... elements)
{
return op(element1, elements...);
},
inputs.getData()...),
first_of(inputs...).getWidth(),
first_of(inputs...).getHeight(),
first_of(inputs...).getDepth());
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<std::size_t unwrap_level = 1, class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static auto voxelwiseOperation(ExPo execution_policy, auto op, const Image<InputT>& input1)
{
auto output = Cube(
recursive_transform<unwrap_level>(
execution_policy,
[&](auto&& element1)
{
return op(element1);
},
(input1.getData())),
input1.getWidth(),
input1.getHeight(),
input1.getDepth());
return output;
}
// plus template function implementation
template<class InputT>
constexpr static Cube<InputT> plus(const Cube<InputT>& input1)
{
return input1;
}
template<class InputT, class... Args>
constexpr static Cube<InputT> plus(const Cube<InputT>& input1, const Args&... inputs)
{
return voxelwiseOperation(std::plus<>{}, input1, plus(inputs...));
}
template<class InputT, class... Args>
constexpr static auto plus(const std::vector<Cube<InputT>>& input1, const Args&... inputs)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&&... inputs_element)
{
return plus(input1_element, inputs_element...);
}, input1, inputs...);
}
// subtract template function implementation
template<class InputT>
constexpr static Cube<InputT> subtract(const Cube<InputT>& input1, const Cube<InputT>& input2)
{
check_size_same(input1, input2);
return voxelwiseOperation(std::minus<>{}, input1, input2);
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<class InputT>
constexpr static auto subtract(const std::vector<Cube<InputT>>& input1, const std::vector<Cube<InputT>>& input2)
{
assert(input1.size() == input2.size());
return recursive_transform<1>(
[](auto&& input1_element, auto&& input2_element)
{
return subtract(input1_element, input2_element);
}, input1, input2);
}
// multiplies template function implementation
template<class InputT>
constexpr static Cube<InputT> multiplies(const Cube<InputT>& input1, const Cube<InputT>& input2)
{
return voxelwiseOperation(std::multiplies<>{}, input1, input2);
}
template<class InputT, class TimesT>
requires(std::floating_point<TimesT> || std::integral<TimesT>)
constexpr static Cube<InputT> multiplies(const Cube<InputT>& input1, const TimesT times)
{
return multiplies(
input1,
Cube(input1.getWidth(), input1.getHeight(), input1.getDepth(), times)
);
}
template<class InputT, class TimesT>
requires(std::floating_point<TimesT> || std::integral<TimesT>)
constexpr static Cube<InputT> multiplies(const TimesT times, const Cube<InputT>& input1)
{
return multiplies(input1, times);
}
template<class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Cube<InputT> multiplies(ExPo execution_policy, const Cube<InputT>& input1, const Cube<InputT>& input2)
{
return voxelwiseOperation(execution_policy, std::multiplies<>{}, input1, input2);
}
template<class InputT, class... Args>
constexpr static Cube<InputT> multiplies(const Cube<InputT>& input1, const Args&... inputs)
{
return voxelwiseOperation(std::multiplies<>{}, input1, multiplies(inputs...));
}
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
namespace TinyDIP
{
// 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>>() + std::size_t{1};
}
template<std::size_t index = 1, typename Arg, typename... Args>
constexpr static auto& get_from_variadic_template(const Arg& first, const Args&... inputs)
{
if constexpr (index > 1)
return get_from_variadic_template<index - 1>(inputs...);
else
return first;
}
template<typename... Args>
constexpr static auto& first_of(Args&... inputs) {
return get_from_variadic_template<1>(inputs...);
}
template<std::size_t, typename, typename...>
struct get_from_variadic_template_struct { };
template<typename T1, typename... Ts>
struct get_from_variadic_template_struct<1, T1, Ts...>
{
using type = T1;
};
template<std::size_t index, typename T1, typename... Ts>
requires ( requires { typename get_from_variadic_template_struct<index - 1, Ts...>::type; })
struct get_from_variadic_template_struct<index, T1, Ts...>
{
using type = typename get_from_variadic_template_struct<index - 1, Ts...>::type;
};
template<std::size_t index, typename... Ts>
using get_from_variadic_template_t = typename get_from_variadic_template_struct<index, Ts...>::type;
// recursive_invoke_result_t implementation
template<std::size_t, typename, typename>
struct recursive_invoke_result { };
template<typename T, typename F>
struct recursive_invoke_result<0, F, T> { using type = std::invoke_result_t<F, T>; }; | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<std::size_t unwrap_level, std::copy_constructible F, template<typename...> typename Container, typename... Ts>
requires (std::ranges::input_range<Container<Ts...>> &&
requires { typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<unwrap_level, F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
template<std::size_t unwrap_level, std::copy_constructible F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<unwrap_level, F, T>::type;
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<std::copy_constructible 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>...>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<std::size_t unwrap_level, std::copy_constructible 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, std::copy_constructible F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
template<typename OutputIt, std::copy_constructible NAryOperation, typename InputIt, typename... InputIts>
OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) {
while (first != last) {
*d_first++ = op(*first++, (*rest++)...);
}
return d_first;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
// recursive_transform for the multiple parameters cases (the version with unwrap_level)
template<std::size_t unwrap_level = 1, std::copy_constructible F, class Arg1, class... Args>
requires(unwrap_level <= recursive_depth<Arg1>())
constexpr auto recursive_transform(const F& f, const Arg1& arg1, const Args&... args)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, Arg1, Args...> output{};
transform(
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element1, auto&&... elements) { return recursive_transform<unwrap_level - 1>(f, element1, elements...); },
std::ranges::cbegin(arg1),
std::ranges::cend(arg1),
std::ranges::cbegin(args)...
);
return output;
}
else
{
return std::invoke(f, arg1, args...);
}
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
// 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 (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
unwrap_level <= recursive_depth<T>())
constexpr auto recursive_transform(ExPo execution_policy, const F& f, const T& input)
{
if constexpr (unwrap_level > 0)
{
recursive_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, f, element);
});
return output;
}
else
{
return std::invoke(f, input);
}
}
}
namespace TinyDIP
{
template<typename ElementT>
constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
return x.getWidth() == y.getWidth();
}
template<typename ElementT>
constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
return is_width_same(x, y) && is_width_same(y, z) && is_width_same(x, z);
}
template<typename ElementT>
constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
return x.getHeight() == y.getHeight();
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<typename ElementT>
constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
return is_height_same(x, y) && is_height_same(y, z) && is_height_same(x, z);
}
template<typename ElementT>
constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
return is_width_same(x, y) && is_height_same(x, y);
}
template<typename ElementT>
constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
return is_size_same(x, y) && is_size_same(y, z) && is_size_same(x, z);
}
template<typename ElementT>
constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
assert(is_width_same(x, y));
}
template<typename ElementT>
constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
assert(is_width_same(x, y, z));
}
template<typename ElementT>
constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
assert(is_height_same(x, y));
}
template<typename ElementT>
constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
assert(is_height_same(x, y, z));
}
template<typename ElementT>
constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
assert_width_same(x, y);
assert_height_same(x, y);
}
template<typename ElementT>
constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
assert_size_same(x, y);
assert_size_same(y, z);
assert_size_same(x, z);
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<typename ElementT>
constexpr void check_width_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
if (!is_width_same(x, y))
throw std::runtime_error("Width mismatched!");
}
template<typename ElementT>
constexpr void check_height_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
if (!is_height_same(x, y))
throw std::runtime_error("Height mismatched!");
}
template<typename ElementT>
constexpr void check_size_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
check_width_same(x, y);
check_height_same(x, y);
}
template<std::size_t unwrap_level = 1, class... Args>
constexpr static auto pixelwiseOperation(auto op, const Args&... inputs)
{
auto output = Image(
recursive_transform<unwrap_level>(
[&](auto&& element1, auto&&... elements)
{
return op(element1, elements...);
},
inputs.getImageData()...),
first_of(inputs...).getWidth(),
first_of(inputs...).getHeight());
return output;
}
template<std::size_t unwrap_level = 1, class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static auto pixelwiseOperation(ExPo execution_policy, auto op, const Image<InputT>& input1)
{
auto output = Image(
recursive_transform<unwrap_level>(
execution_policy,
[&](auto&& element1)
{
return op(element1);
},
(input1.getImageData())),
input1.getWidth(),
input1.getHeight());
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<typename T>
requires(std::floating_point<T> || std::integral<T>)
T normalDistribution1D(const T x, const T standard_deviation)
{
return std::exp(-x * x / (2 * standard_deviation * standard_deviation));
}
template<typename T>
requires(std::floating_point<T> || std::integral<T>)
T normalDistribution2D(const T xlocation, const T ylocation, const T standard_deviation)
{
return std::exp(-(xlocation * xlocation + ylocation * ylocation) / (2 * standard_deviation * standard_deviation)) / (2 * std::numbers::pi * standard_deviation * standard_deviation);
}
// multiple standard deviations
template<class InputT>
requires(std::floating_point<InputT> || std::integral<InputT>)
constexpr static Image<InputT> gaussianFigure2D(
const size_t xsize, const size_t ysize,
const size_t centerx, const size_t centery,
const InputT standard_deviation_x, const InputT standard_deviation_y)
{
auto output = Image<InputT>(xsize, ysize);
auto row_vector_x = Image<InputT>(xsize, 1);
for (size_t x = 0; x < xsize; ++x)
{
row_vector_x.at(x, 0) = normalDistribution1D(static_cast<InputT>(x) - static_cast<InputT>(centerx), standard_deviation_x);
}
auto row_vector_y = Image<InputT>(ysize, 1);
for (size_t y = 0; y < ysize; ++y)
{
row_vector_y.at(y, 0) = normalDistribution1D(static_cast<InputT>(y) - static_cast<InputT>(centery), standard_deviation_y);
}
for (size_t y = 0; y < ysize; ++y)
{
for (size_t x = 0; x < xsize; ++x)
{
output.at(x, y) = row_vector_x.at(x, 0) * row_vector_y.at(y, 0);
}
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
// single standard deviation
template<class InputT>
requires(std::floating_point<InputT> || std::integral<InputT>)
constexpr static Image<InputT> gaussianFigure2D(
const size_t xsize, const size_t ysize,
const size_t centerx, const size_t centery,
const InputT standard_deviation)
{
return gaussianFigure2D(xsize, ysize, centerx, centery, standard_deviation, standard_deviation);
}
// multiple standard deviations
template<class InputT>
requires(std::floating_point<InputT> || std::integral<InputT>)
constexpr static auto gaussianFigure3D(
const size_t xsize, const size_t ysize, const size_t zsize,
const size_t centerx, const size_t centery, const size_t centerz,
const InputT standard_deviation_x, const InputT standard_deviation_y, const InputT standard_deviation_z)
{
auto output = std::vector<Image<InputT>>();
output.reserve(zsize);
auto gaussian_image2d = gaussianFigure2D(xsize, ysize, centerx, centery, standard_deviation_x, standard_deviation_y);
for (size_t z = 0; z < zsize; ++z)
{
output.emplace_back(
normalDistribution1D(static_cast<InputT>(z) - static_cast<InputT>(centerz), standard_deviation_z) *
gaussian_image2d
);
}
return Cube(output);
}
template<class InputT>
constexpr static Image<InputT> plus(const Image<InputT>& input1)
{
return input1;
}
template<class InputT, class... Args>
constexpr static Image<InputT> plus(const Image<InputT>& input1, const Args&... inputs)
{
return pixelwiseOperation(std::plus<>{}, input1, plus(inputs...));
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<class InputT, class... Args>
constexpr static auto plus(const std::vector<Image<InputT>>& input1, const Args&... inputs)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&&... inputs_element)
{
return plus(input1_element, inputs_element...);
}, input1, inputs...);
}
template<class InputT>
constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2)
{
check_size_same(input1, input2);
return pixelwiseOperation(std::minus<>{}, input1, input2);
}
template<class InputT>
constexpr static auto subtract(const std::vector<Image<InputT>>& input1, const std::vector<Image<InputT>>& input2)
{
assert(input1.size() == input2.size());
return recursive_transform<1>(
[](auto&& input1_element, auto&& input2_element)
{
return subtract(input1_element, input2_element);
}, input1, input2);
}
template<class InputT = RGB>
requires (std::same_as<InputT, RGB>)
constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2)
{
check_size_same(input1, input2);
Image<InputT> output(input1.getWidth(), input1.getHeight());
for (std::size_t y = 0; y < input1.getHeight(); ++y)
{
for (std::size_t x = 0; x < input1.getWidth(); ++x)
{
for(std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
output.at(x, y).channels[channel_index] =
std::clamp(
input1.at(x, y).channels[channel_index] -
input2.at(x, y).channels[channel_index],
0,
255);
}
}
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<class InputT>
constexpr static Image<InputT> multiplies(const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(std::multiplies<>{}, input1, input2);
}
template<class InputT, class TimesT>
requires(std::floating_point<TimesT> || std::integral<TimesT>)
constexpr static Image<InputT> multiplies(const Image<InputT>& input1, const TimesT times)
{
return multiplies(
input1,
Image(input1.getWidth(), input1.getHeight(), times)
);
}
template<class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Image<InputT> multiplies(ExPo execution_policy, const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(execution_policy, std::multiplies<>{}, input1, input2);
}
template<class InputT, class... Args>
constexpr static Image<InputT> multiplies(const Image<InputT>& input1, const Args&... inputs)
{
return pixelwiseOperation(std::multiplies<>{}, input1, multiplies(inputs...));
}
template<class ExPo, class InputT, class... Args>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Image<InputT> multiplies(ExPo execution_policy, const Image<InputT>& input1, const Args&... inputs)
{
return pixelwiseOperation(execution_policy, std::multiplies<>{}, input1, multiplies(inputs...));
}
template<class InputT, class... Args>
constexpr static auto multiplies(const std::vector<Image<InputT>>& input1, const Args&... inputs)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&&... inputs_element)
{
return multiplies(input1_element, inputs_element...);
}, input1, inputs...);
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
template<class InputT>
constexpr static Image<InputT> divides(const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(std::divides<>{}, input1, input2);
}
template<class InputT>
constexpr static auto divides(const std::vector<Image<InputT>>& input1, const std::vector<Image<InputT>>& input2)
{
assert(input1.size() == input2.size());
return recursive_transform<1>(
[](auto&& input1_element, auto&& input2_element)
{
return divides(input1_element, input2_element);
}, input1, input2);
}
template<class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Image<InputT> divides(ExPo execution_policy, const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(execution_policy, std::divides<>{}, input1, input2);
}
template<class InputT>
constexpr static Image<InputT> modulus(const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(std::modulus<>{}, input1, input2);
}
template<class InputT>
constexpr static Image<InputT> negate(const Image<InputT>& input1)
{
return pixelwiseOperation(std::negate<>{}, input1);
}
}
template<typename T>
void gaussianFigure3DTest(const size_t size = 3)
{
auto gaussian_image3d = TinyDIP::gaussianFigure3D(
size,
size,
size,
1, 1, 1,
static_cast<T>(3), static_cast<T>(3), static_cast<T>(3));
gaussian_image3d.print();
return;
} | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
int main()
{
auto start = std::chrono::system_clock::now();
gaussianFigure3DTest<double>();
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:
0.846482 0.894839 0.846482
0.894839 0.945959 0.894839
0.846482 0.894839 0.846482
0.894839 0.945959 0.894839
0.945959 1 0.945959
0.894839 0.945959 0.894839
0.846482 0.894839 0.846482
0.894839 0.945959 0.894839
0.846482 0.894839 0.846482
Computation finished at Tue Dec 26 06:37:57 2023
elapsed time: 6.6216e-05
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
Three dimensional gaussian image generator in C++
What changes has been made in the code since last question?
I am trying to create 3D data structure Cube in this post.
Why a new review is being asked for?
Please review Cube template class implementation and all suggestions are welcome.
Answer: Lots of small issues
Missing checks for overflow of width * height * depth.
Inconsistent types for coordinates: one constructor uses std::size_t for the dimensions, another int, and at() takes unsigned ints.
Sometimes you use size_t instead of std::size_t.
Unnecessary copies, for example in:
auto image = input[z];
Unnecessary return statement in the last constructor.
Why have both getSizeX() and getWidth()?
Why not use std::ranges::transform(), like so:
std::ranges::transform(data, rhs.data, std::ranges::begin(data), std::plus<>{}); | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
c++, image, template, classes, c++20
Remove the copy/move constructors/assignment operators; if they are all default you don't need to specify them at all (also see the rule of zero).
Do you really need all of is_foo_same(), assert_foo_same() and check_foo_same()?
Why do you even need assert_size_same() that takes three parameters? And even if you do, you only need two calls to assert_size_same() in it.
Multiplying a Cube by an ElementT still generates another Cube unnecessarily.
voxelwiseOperation() seems unnecessarily complex
It's weird to see recursive_transform() used here, but I guess if you want to support operations with more than two arguments and you couldn't use C++23's zip() yet, it might make sense. I would still have just written two simpler versions, one for unary operations and one for binary operations. However, even your version can be simplified a tiny bit this way:
template<std::size_t unwrap_level = 1, class First, class... Rest>
constexpr static auto voxelwiseOperation(auto op, const First& first, const Rest&... rest)
{
return Cube(
recursive_transform<unwrap_level>(
[&](auto&&... elements)
{
return op(elements...);
},
first.getData(),
rest.getData()...
),
first.getWidth(),
first.getHeight(),
first.getDepth()
);
}
There is also the issue that recursive_transform() will generate a new std::vector<ElementT>, and since you don't have a constructor that can move from a std::vector<ElementT>, that whole vector will be copied, but that could be avoided.
What about hypercubes?
What if you need even higher-dimensional images? Adding a four-dimensional version would be a lot of work and lines of code. You could instead try to make Image take a template parameter that tells it the number of dimensions it has. | {
"domain": "codereview.stackexchange",
"id": 45327,
"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++, image, template, classes, c++20",
"url": null
} |
python, programming-challenge, string-processing
Title: Advent of Code 2023 - Day 5: If You Give A Seed A Fertilizer (Part 1)
Question: The task involves determining the lowest location number corresponding to a given set of seeds by following numerical mappings for soil, fertilizer, water, light, temperature, humidity, and location.
The almanac (your puzzle input) lists all of the seeds that need to be
planted. It also lists what type of soil to use with each kind of
seed, what type of fertilizer to use with each kind of soil, what type
of water to use with each kind of fertilizer, and so on. Every type of
seed, soil, fertilizer and so on is identified with a number, but
numbers are reused by each category - that is, soil 123 and fertilizer
123 aren't necessarily related to each other.
For example:
seeds: 79 14 55 13
seed-to-soil map:
50 98 2
52 50 48
soil-to-fertilizer map:
0 15 37
37 52 2
39 0 15
fertilizer-to-water map:
49 53 8
0 11 42
42 0 7
57 7 4
water-to-light map:
88 18 7
18 25 70
light-to-temperature map:
45 77 23
81 45 19
68 64 13
temperature-to-humidity map:
0 69 1
1 0 69
humidity-to-location map:
60 56 37
56 93 4
The almanac starts by listing which seeds need to be planted: seeds
79, 14, 55, and 13.
The rest of the almanac contains a list of maps which describe how to
convert numbers from a source category into numbers in a destination
category. That is, the section that starts with seed-to-soil map:
describes how to convert a seed number (the source) to a soil number
(the destination).
The maps describe entire ranges of numbers that can be converted. Each
line within a map contains three numbers: the destination range start,
the source range start, and the range length.
Consider again the example seed-to-soil map:
50 98 2
52 50 48 | {
"domain": "codereview.stackexchange",
"id": 45328,
"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, programming-challenge, string-processing",
"url": null
} |
python, programming-challenge, string-processing
50 98 2
52 50 48
The first line has a destination range start of 50, a source range
start of 98, and a range length of 2. This line means that the source
range starts at 98 and contains two values: 98 and 99. The destination
range is the same length, but it starts at 50, so its two values are
50 and 51. With this information, you know that seed number 98
corresponds to soil number 50 and that seed number 99 corresponds to
soil number 51.
The second line means that the source range starts at 50 and contains
48 values: 50, 51, ..., 96, 97. This corresponds to a destination
range starting at 52 and also containing 48 values: 52, 53, ..., 98,
99. So, seed number 53 corresponds to soil number 55.
Any source numbers that aren't mapped correspond to the same
destination number. So, seed number 10 corresponds to soil number 10.
So, the entire list of seed numbers and their corresponding soil
numbers looks like this:
seed soil
0 0
1 1
... ...
48 48
49 49
50 52
51 53
... ...
96 98
97 99
98 50
99 51
With this map, you can look up the soil number required for each
initial seed number:
Seed number 79 corresponds to soil number 81. Seed number 14
corresponds to soil number 14. Seed number 55 corresponds to soil
number 57. Seed number 13 corresponds to soil number 13.
The goal is to convert each seed number through these categories until determining its corresponding location number, ultimately identifying the closest location that needs a seed.
In this example, the corresponding types are:
Seed 79, soil 81, fertilizer 81, water 81, light 74, temperature 78, humidity 78, location 82.
Seed 14, soil 14, fertilizer 53, water 49, light 42, temperature 42, humidity 43, location 43.
Seed 55, soil 57, fertilizer 57, water 53, light 46, temperature 82, humidity 82, location 86.
Seed 13, soil 13, fertilizer 52, water 41, light 34, temperature 34, humidity 35, location 35. | {
"domain": "codereview.stackexchange",
"id": 45328,
"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, programming-challenge, string-processing",
"url": null
} |
python, programming-challenge, string-processing
So, the lowest location number in this example is 35.
My initial approach - although very inefficient - successfully handled the sample input presented here, but crashed for the larger file provided at the website (EHWPOISON 133 Memory page has hardware error, I was out of resources). But it could still use a review.
#!/usr/bin/env python3
from functools import reduce
from pathlib import Path
from typing import Iterable
import typer
def map_ranges(lines: Iterable[str]) -> dict[int, int]:
range_map = {}
for line in lines:
# We are at the end of the map if there's an empty line.
if not line.strip():
break
dest_range_start, src_range_start, range_len = map(int, line.split())
for i in range(range_len):
range_map[src_range_start + i] = dest_range_start + i
return range_map
def parse_seeds(line: str) -> int:
# seeds: X Y Z ...
return {int(i) for i in line.split() if i[0].isdigit()}
def parse_locations(seeds: set[int], maps: dict[str, dict[int, int]]) -> int:
return {
reduce(lambda curr, map_: maps[map_].get(curr, curr), maps, seed)
for seed in seeds
}
def parse_maps(lines: Iterable[str]) -> dict[str, dict[int, int]]:
return {
line.strip(): map_ranges(lines)
for line in lines
if any(
line.startswith(x)
for x in [
"seed",
"soil",
"fertilizer",
"water",
"light",
"temperature",
"humidity",
]
)
}
def lowest_location(lines: Iterable[str]) -> int:
return min(parse_locations(parse_seeds(lines.readline()), parse_maps(lines)))
def main(almanac_file: Path) -> None:
with open(almanac_file) as f:
print(lowest_location(f))
if __name__ == "__main__":
typer.run(main) | {
"domain": "codereview.stackexchange",
"id": 45328,
"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, programming-challenge, string-processing",
"url": null
} |
python, programming-challenge, string-processing
if __name__ == "__main__":
typer.run(main)
After opting for another algorithm, this new approach didn't hog system resources and works well for both small and large datasets.
#!/usr/bin/env python3
from pathlib import Path
from typing import Iterable
import typer
def map_seeds(seeds: list[int], lines: Iterable[str]) -> list[int]:
new = seeds.copy()
for line in lines:
# We are at the end of the map if there's an empty line.
if not line.strip():
break
dest, src, range_ = map(int, line.split())
for idx, seed in enumerate(seeds):
if seed >= src and seed <= (src + range_ - 1):
new[idx] += dest - src
return new
def parse_maps(seeds: list[int], lines: Iterable[str]) -> list[int]:
for line in lines:
if any(
line.startswith(x)
for x in [
"seed",
"soil",
"fertilizer",
"water",
"light",
"temperature",
"humidity",
]
):
seeds = map_seeds(seeds, lines)
return seeds
def parse_seeds(line: str) -> list[int]:
# seeds: X Y Z ...
return [int(i) for i in line.split() if i[0].isdigit()]
def lowest_location(lines: Iterable[str]) -> int:
return min(parse_maps(parse_seeds(lines.readline()), lines))
def main(almanac_file: Path) -> None:
with open(almanac_file) as f:
print(lowest_location(f))
if __name__ == "__main__":
typer.run(main)
Review Request:
What'd be a better algorithm?
How can parse_maps() be simplified? What are some other simplications?
General coding comments, style, etc. | {
"domain": "codereview.stackexchange",
"id": 45328,
"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, programming-challenge, string-processing",
"url": null
} |
python, programming-challenge, string-processing
Answer: Algorithmically your code looks fine and there is nothing that has to be changed. There are a few changes I would suggest that could slightly improve performance or be more Pythonic. There are additional suggestions that might not result in faster execution but might make the code marginally clearer (and this is just my opinion; others may differ).
You have a loop in function map_seeds that computes two values that are loop invariant and should ideally be calculated once before entering the loop. map_seeds is called repeatedly.
Only on the first invocation is my_seeds being passed list of seed values; on subsequent calls it is being a passed a list of locations. So calling this function map_seeds, which is passed an argument named seeds, is not really accurate. In general, this function is being passed a list of values that are to be mapped to new values. So a better name for this function is map_values, which is passed an argument named input_values.
I have also changed the name of variables to match more closely the problem description names for these quantities.
Finally, I have modified your check to see whether a value falls within a range of values to be more Pythonic:
...
def map_values(input_values: list[int], lines: Iterable[str]) -> list[int]:
new_values = input_values.copy()
for line in lines:
# We are at the end of the map if there's an empty line.
if not line.strip():
break
# Modified variable names to match problem description names:
destination_range_start, source_range_start, range_length = map(int, line.split())
# Calculate these values once:
source_range_end = source_range_start + range_length - 1
adjustment = destination_range_start - source_range_start | {
"domain": "codereview.stackexchange",
"id": 45328,
"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, programming-challenge, string-processing",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.