text stringlengths 1 2.12k | source dict |
|---|---|
c, event-handling, networking, unix, posix
Closing new connections that have a filedescriptor above FD_SETSIZE seems like the best option. You might consider printing a warning when that happens though, or even sending a message over that filedescriptor, in a non-blocking way, right before closing it, to inform the peer that tried to join that this server cannot handle any more connections at this moment.
Does any part of my code require a comment?
Ideally, your code is structured in a logical way, and has clear variable and function names such that the meaning of the code is obvious to a reader. In those cases where clear code is not enough to tell a reader what is going on, you should add comments.
I see you added some comments above functions, describing what they do and what the return values mean. That's great, but consider doing this in the Doxygen format. This allows the Doxygen tools to generate a reference manual for your code, and if you enable warnings those tools can even check that you didn't forget to document all functions, parameters and return values.
How do I avoid mixed messages? For instance:
Jack (typing): hel...
John (typing): nig...
Jack's screen: hellnight
By keeping a per-socket buffer, and only forwarding a message when it has been received completely. This will increase the complexity of your program of course, but there is no way around that.
Would it suffice to call fsync() before closing the file descriptor once, instead of calling it after every write()? | {
"domain": "codereview.stackexchange",
"id": 44528,
"lm_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, event-handling, networking, unix, posix",
"url": null
} |
c, event-handling, networking, unix, posix
It depends on what you want to happen if the program is terminated abnormally. Do you need the log to be as complete as possible at all times, or is it OK if you miss part of it in the rare case that your program crashes or your computer loses power? You are already handling errors very gracefully now, and not calling exit() in the middle of the program. That means that if there are no bugs in your program that would cause it to crash, it will always exit from main() in an orderly fashion, in which case any open file descriptors will be flushed and closed automatically. So I would consider removing the calls to fsync() entirely. | {
"domain": "codereview.stackexchange",
"id": 44528,
"lm_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, event-handling, networking, unix, posix",
"url": null
} |
javascript
Title: Improving player button control code
Question: Would somebody be kind enough to show me the best way to loop through this so it much more efficient that just repeating everything?
const playButton = document.querySelector("#btnPlay");
const playButton1 = document.querySelector("#btnPlay1");
const playButton2 = document.querySelector("#btnPlay2");
const playButton3 = document.querySelector("#btnPlay3");
const playButton4 = document.querySelector("#btnPlay4");
const playButton5 = document.querySelector("#btnPlay5");
const playButton6 = document.querySelector("#btnPlay6");
const playButton7 = document.querySelector("#btnPlay7");
const playButton8 = document.querySelector("#btnPlay8");
const playButton9 = document.querySelector("#btnPlay9");
const playButton10 = document.querySelector("#btnPlay10");
const pauseButton = document.querySelector("#btnPause");
const pauseButton1 = document.querySelector("#btnPause1");
const pauseButton2 = document.querySelector("#btnPause2");
const pauseButton3 = document.querySelector("#btnPause3");
const pauseButton4 = document.querySelector("#btnPause4");
const pauseButton5 = document.querySelector("#btnPause5");
const pauseButton6 = document.querySelector("#btnPause6");
const pauseButton7 = document.querySelector("#btnPause7");
const pauseButton8 = document.querySelector("#btnPause8");
const pauseButton9 = document.querySelector("#btnPause9");
const pauseButton10 = document.querySelector("#btnPause10"); | {
"domain": "codereview.stackexchange",
"id": 44529,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
const iframe = document.querySelector("#player");
const iframe1 = document.querySelector("#player1");
const iframe2 = document.querySelector("#player2");
const iframe3 = document.querySelector("#player3");
const iframe4 = document.querySelector("#player4");
const iframe5 = document.querySelector("#player5");
const iframe6 = document.querySelector("#player6");
const iframe7 = document.querySelector("#player7");
const iframe8 = document.querySelector("#player8");
const iframe9 = document.querySelector("#player9");
const iframe10 = document.querySelector("#player10");
const player = new Vimeo.Player(iframe);
const player1 = new Vimeo.Player(iframe1);
const player2 = new Vimeo.Player(iframe2);
const player3 = new Vimeo.Player(iframe3);
const player4 = new Vimeo.Player(iframe4);
const player5 = new Vimeo.Player(iframe5);
const player6 = new Vimeo.Player(iframe6);
const player7 = new Vimeo.Player(iframe7);
const player8 = new Vimeo.Player(iframe8);
const player9 = new Vimeo.Player(iframe9);
const player10 = new Vimeo.Player(iframe10);
playButton.addEventListener("click", playVideo);
playButton1.addEventListener("click", playVideo1);
playButton2.addEventListener("click", playVideo2);
playButton3.addEventListener("click", playVideo3);
playButton4.addEventListener("click", playVideo4);
playButton5.addEventListener("click", playVideo5);
playButton6.addEventListener("click", playVideo6);
playButton7.addEventListener("click", playVideo7);
playButton8.addEventListener("click", playVideo8);
playButton9.addEventListener("click", playVideo9);
playButton10.addEventListener("click", playVideo10); | {
"domain": "codereview.stackexchange",
"id": 44529,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
pauseButton.addEventListener("click", pauseVideo);
pauseButton1.addEventListener("click", pauseVideo1);
pauseButton2.addEventListener("click", pauseVideo2);
pauseButton3.addEventListener("click", pauseVideo3);
pauseButton4.addEventListener("click", pauseVideo4);
pauseButton5.addEventListener("click", pauseVideo5);
pauseButton6.addEventListener("click", pauseVideo6);
pauseButton7.addEventListener("click", pauseVideo7);
pauseButton8.addEventListener("click", pauseVideo8);
pauseButton9.addEventListener("click", pauseVideo9);
pauseButton10.addEventListener("click", pauseVideo10);
function playVideo() {
player.play();
}
function playVideo1() {
player1.play();
}
function playVideo2() {
player2.play();
}
function playVideo3() {
player3.play();
}
function playVideo4() {
player4.play();
}
function playVideo5() {
player5.play();
}
function playVideo6() {
player6.play();
}
function playVideo7() {
player7.play();
}
function playVideo8() {
player8.play();
}
function playVideo9() {
player9.play();
}
function playVideo10() {
player10.play();
}
function pauseVideo() {
player.pause();
player.setCurrentTime(0);
}
function pauseVideo1() {
player1.pause();
player1.setCurrentTime(0);
}
function pauseVideo2() {
player2.pause();
player2.setCurrentTime(0);
}
function pauseVideo3() {
player3.pause();
player3.setCurrentTime(0);
}
function pauseVideo4() {
player4.pause();
player4.setCurrentTime(0);
}
function pauseVideo5() {
player5.pause();
player5.setCurrentTime(0);
}
function pauseVideo6() {
player6.pause();
player6.setCurrentTime(0);
}
function pauseVideo7() {
player7.pause();
player7.setCurrentTime(0);
}
function pauseVideo8() {
player8.pause();
player8.setCurrentTime(0);
}
function pauseVideo9() {
player9.pause();
player9.setCurrentTime(0);
}
function pauseVideo10() {
player10.pause();
player10.setCurrentTime(0);
} | {
"domain": "codereview.stackexchange",
"id": 44529,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
Answer: Instead of creating a variable for each of these, you can use arrays for the buttons, iframes, and players, and you can use anonymous functions for the click event listeners.
const playerCount = 11;
const playButtons = new Array(playerCount)
.fill(0)
.map((_, i) => document.querySelector(`#btnPlay${i || ""}`));
const pauseButtons = new Array(playerCount)
.fill(0)
.map((_, i) => document.querySelector(`#btnPause${i || ""}`));
const iframes = new Array(playerCount)
.fill(0)
.map((_, i) => document.querySelector(`#player${i || ""}`));
const players = iframes.map((iframe) => new Vimeo.Player(iframe));
players.forEach((player, index) => {
playButtons[index].addEventListener("click", player.play);
pauseButtons[index].addEventListener("click", () => {
player.pause();
player.setCurrentTime(0);
});
});
.fill(0) is needed because new Array(size) has "empty" elements, which are skipped over by .map.
${i || ""} is part of a template literal, this makes it so that if the value is 0 it's an empty string.
Another approach is a traditional for-loop. If you don't need to store a reference to each of buttons, etc., that you can access later, this option can be considered "cleaner" since it doesn't have extra variables leak out into the surrounding scope.
const playerCount = 11;
// if you need this
// const players = [];
// you can also repeat this for other variables you want outside of this loop
for (let i = 0; i < playerCount; i++) {
const playButton = document.querySelector(`#btnPlay${i || ""}`);
const pauseButton = document.querySelector(`#btnPause${i || ""}`);
const iframe = document.querySelector(`#player${i || ""}`);
const player = new Vimeo.Player(iframe);
playButton.addEventListener("click", player.play);
pauseButton.addEventListener("click", () => {
player.pause();
player.setCurrentTime(0);
});
// if you need this
// players.push(player);
} | {
"domain": "codereview.stackexchange",
"id": 44529,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
// if you need this
// players.push(player);
}
Speed isn't an issue for something this small (only 11 players). The choice is mostly just stylistic and whatever you find to be the most readable. | {
"domain": "codereview.stackexchange",
"id": 44529,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
c, heap, binary-tree, heap-sort
Title: Max-heap implementation in C
Question: I have tried to implement my Heap in C. The following are the 13 operations defined:
build_maxheap
insert
exctract_max (delete heap max root)
max_delete (delete an element or key)
max_heapify
clear
heapSort
get_max
print
increase_key (helper function for insert and delete key functions)
height
is_empty
is_maxheap (checks if the array is a heap)
This is the code in C:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
typedef struct MaxHeap {
int size;
int* heap;
} MaxHeap;
const MaxHeap maxheap_init = { .size = 0, .heap = NULL };
int INF = 1000, N_INF = -1000;
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int parent(int i) {
return (i-1)/2;
}
int left(int i) {
return (2*i + 1);
}
int right(int i) {
return (2*i + 2);
}
int get_max(MaxHeap* max_heap) { //O(1)
return max_heap->heap[0];
}
int is_empty(MaxHeap* max_heap) {
return max_heap->heap[0] == N_INF;
}
int height(MaxHeap* max_heap) {
return floor(log2(max_heap->size));
}
MaxHeap* create_maxheap(int size) {
MaxHeap* heap = calloc(size, sizeof * heap);
if (!heap) return heap;
heap->size = size;
return heap;
}
void max_heapify(int* data, int* key_index, int i, int size) { // O(logn)
int largest = i, leftie = left(i), rightie = right(i);
if (leftie < size && data[leftie] > data[largest])
largest = leftie;
if (rightie < size && data[rightie] > data[largest])
largest = rightie;//transitvity
if (largest != i) {
swap(&data[i], &data[largest]);
//
key_index[data[i]] = i;
key_index[data[largest]] = largest;
//
max_heapify(data, key_index, largest, size);
}
} | {
"domain": "codereview.stackexchange",
"id": 44530,
"lm_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, heap, binary-tree, heap-sort",
"url": null
} |
c, heap, binary-tree, heap-sort
void increase_key(MaxHeap* max_heap, int* key_index, int j, int key) {
if (key < max_heap->heap[j])
printf("Error: key must be larger \n");
else {
max_heap->heap[j] = key;
key_index[key] = j;
for (int i = j; i > 0; i = parent(i)) {
if (max_heap->heap[i] > max_heap->heap[parent(i)]) {
swap(&max_heap->heap[i], &max_heap->heap[parent(i)]);
key_index[max_heap->heap[i]] = i;
key_index[max_heap->heap[parent(i)]] = parent(i);
}
else break;
}
}
}
int* build_max_heap(int* data, int* key_index, int size) { //O(n)
for (int i = size / 2 - 1; i >= 0; i--) {
max_heapify(data, key_index, i, size);
}
return data;
}
void insert(MaxHeap* max_heap, int* key_index, int key) { // O(logn)
int* temp = realloc (max_heap->heap, (max_heap->size + 1) * sizeof (*(max_heap->heap)));
if (temp) {
max_heap->heap = temp;
max_heap->heap[max_heap->size] = N_INF;
increase_key(max_heap, key_index, max_heap->size, key);
max_heap->size += 1;
temp = 0;
}
}
void extract_max(MaxHeap* max_heap, int* key_index) { // O(logn)
swap(&max_heap->heap[0], &max_heap->heap[max_heap->size - 1]);
max_heap->size -= 1;
max_heapify(max_heap->heap, key_index, 0, max_heap->size);
}
void delete_key(MaxHeap* max_heap, int* key_index, int key) { //O(logn)
int index = key_index[key];
increase_key(max_heap, key_index, index, INF);
extract_max(max_heap, key_index);
}
void clear(MaxHeap* max_heap) {
for (int i = 0; i < max_heap->size; i++)
max_heap->heap[i] = N_INF; //assuming it is never in the heap
max_heap->size = 0;
} | {
"domain": "codereview.stackexchange",
"id": 44530,
"lm_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, heap, binary-tree, heap-sort",
"url": null
} |
c, heap, binary-tree, heap-sort
void print_heap(MaxHeap* max_heap) { // O(n)
int size = max_heap->size;
if (size % 2 != 0)
size = size + 1;
for (int i = 0; i < size/2 - 1; i++) {
printf("Parent: %d -> Left: %d | Right: %d \n", max_heap->heap[i], max_heap->heap[2*i+1], max_heap->heap[2*i+2]);
}
int j = max_heap->size/2 - 1;
if (max_heap->size % 2 == 0)
printf("Parent: %d -> Left: %d \n", max_heap->heap[j], max_heap->heap[2*j+1]);
}
int is_maxheap(MaxHeap* max_heap) { // O(n)
for (int i = max_heap->size-1; i > 0 ; i--) {
if (max_heap->heap[i] > max_heap->heap[parent(i)]) {
return 0;
}
}
return 1;
}
void heap_sort(MaxHeap* max_heap, int* key_index) { // assumes already a max heap as argument
// if the input is not a heap, call build_max_heap()
for (int i = max_heap->size - 1; i >= 0; i--) {
swap(&max_heap->heap[0], &max_heap->heap[i]);
max_heapify(max_heap->heap, key_index, 0, i);
}
}
void print_arr(MaxHeap* max_heap) {
for (int i = 0; i < max_heap->size; i++)
printf("%d ", max_heap->heap[i]);
printf("\n");
} | {
"domain": "codereview.stackexchange",
"id": 44530,
"lm_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, heap, binary-tree, heap-sort",
"url": null
} |
c, heap, binary-tree, heap-sort
int main() {
int size = 6, MAX_Key = INF, elements[6] = {10, 20, 15, 12, 40, 25};
int* data = calloc(size, sizeof * data);
if (!data) return 0;
for (int i = 0; i < size; i++)
data[i] = elements[i];
int* key_index = calloc(MAX_Key, sizeof * key_index); // we assume key > 0, if key < 0, then we add an additional array
if (!key_index) return 0;
for (int i = 0; i < size; i++)
key_index[elements[i]] = i;
MaxHeap max_heap = maxheap_init;
max_heap.size = size;
max_heap.heap = build_max_heap(data, key_index, size);
print_heap(&max_heap);
printf("is_max_heap: %d \n", is_maxheap(&max_heap));
extract_max(&max_heap, key_index);
printf("is_max_heap: %d \n", is_maxheap(&max_heap));
print_heap(&max_heap);
insert(&max_heap, key_index, 14);
printf("is_max_heap: %d \n", is_maxheap(&max_heap));
print_heap(&max_heap);
delete_key(&max_heap, key_index, 14);
printf("is_max_heap: %d \n", is_maxheap(&max_heap));
print_heap(&max_heap);
printf("height: %d \n", height(&max_heap));
printf("max: %d \n", get_max(&max_heap));
heap_sort(&max_heap, key_index);
print_arr(&max_heap);
clear(&max_heap);
printf("is empty: %d \n", is_empty(&max_heap));
free(data);
free(key_index);
return 0;
}
If you have any improvement ideas, I would be very grateful to read through them. I should note that this implementation is for learning purposes, not for a client or something. There might be some place when I missed some secondary check for an empty array or something, but I am interested in seeing if the code holds or not. I tested it and it works just fine. | {
"domain": "codereview.stackexchange",
"id": 44530,
"lm_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, heap, binary-tree, heap-sort",
"url": null
} |
c, heap, binary-tree, heap-sort
Answer: This is a max-heap datastructure,
and there is very consistent nomenclature here which reflects that.
I'm sure it is clear and commendable.
But I wouldn't have minded seeing it written in a comment, once,
and then we just call it a heap in the code.
(Or perhaps there's some design document, not in the submission,
that talks about future plans for a min-heap.)
Consider adopting a code style (maybe GNU? or Google?)
and enforcing it with a linter or pretty printer.
There are well-known issues that stem from
neglecting to adorn single-line if / for statements
with curly braces.
Type a couple of "extra" { } characters -- it will
be worth it in the end!
I guess this looks mostly plausible:
int height(MaxHeap* max_heap) {
return floor(log2(max_heap->size));
}
It's not obvious to me that most callers would
expect a floor result instead of a ceil result.
But there's no comment documentation specifying its behavior,
and we can only report a bug w.r.t. some written spec,
so this code's behavior must be correct.
We're not restricted to power-of-two sizes,
and it's nice that that is pretty clear.
There is no warning that caller is responsible
for verifying non-empty prior to calling this,
for example we see that maxheap_init is valid but empty.
I can't say that I feel good about returning negative
HUGE_VAL in the empty
case, since 0 seems the most natural response for that.
This submission includes a demo but no unit tests.
In particular, we see no self-evaluating tests that would
offer concrete example return values for
particular heaps. Adding such test(s) would
bring documentation value. | {
"domain": "codereview.stackexchange",
"id": 44530,
"lm_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, heap, binary-tree, heap-sort",
"url": null
} |
c, heap, binary-tree, heap-sort
max_heapify's recursive call to itself is Fine.
If this was implemented in scheme, it's a sure thing
the tail recursion would be optimized, with no extra
stack usage.
This submission does not include a Makefile or build script
that shows which compiler is used with which compilation flags.
For some compiler target of interest, it would be useful
for a comment to mention whether recursion costs us stack
space here or not. A caller might know that it is tight
on stack space and would want to know if it is safe to heapify.
A https://godbolt.org link could suffice.
Alternatively, you might prefer to code a while loop here.
insert should probably report fatal error
if caller violates this constraint:
N_INF < key < INF
Given the void signature,
I can't say I get warm fuzzies about how a practical
application would behave once insert exhausts memory.
At a minimum we need some comments describing caller's
responsibility for checking errno.
temp = 0;
What's that all about?
Leftover debug?
This isn't java, it's not like nulling out the pointer
will enable some garbage collection.
Making extract_max void seems odd.
Yes, caller could grab the value prior to the call.
But it seems natural to return the extracted value, no?
Or maybe this should have been a private helper
for delete_key ?
In clear, "assume" seems like the wrong verb.
max_heap->heap[i] = N_INF; //assuming it is never in the heap
As touched on above, restricted range of heap values
is a fundamental invariant of this datastructure.
We "enforce" what range those values are in.
Prefer a verb like "shall never be in the heap".
print_heap does this:
... max_heap->heap[i], max_heap->heap[2*i+1], max_heap->heap[2*i+2]);
Rather than those expressions, prefer the left / right helpers.
Also, is there an opportunity to use the parent helper, here? | {
"domain": "codereview.stackexchange",
"id": 44530,
"lm_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, heap, binary-tree, heap-sort",
"url": null
} |
c, heap, binary-tree, heap-sort
The is_maxheap identifier is suggestive of Boolean,
very nice, thank you.
But couldn't we offer a return type in the signature
that is narrower than signed integer?
print_arr does this:
printf("%d ", max_heap->heap[i]);
Given the limited range of heap values,
it might be convenient to impose a fixed
number of display columns for each decimal value.
Then they'd have a better chance of lining
up when wrapped at the terminal's line length.
main tidies up after itself:
free(data);
free(key_index);
I am looking at the allocation in create_maxheap.
But we never called that, preferring build_max_heap instead.
Maybe delete some vestigial code?
main correctly verifies allocations,
and silently drops out upon failure.
Not the friendliest behavior -- it is likely
to increase the cost of supporting this code
in the field when problem reports hit the helpdesk.
Consider linking against allocation routines that are
a bit more on the chatty side when things go south.
Overall?
This looks fairly solid.
I would be willing to delegate or accept maintenance tasks
for this code base.
Ship it! | {
"domain": "codereview.stackexchange",
"id": 44530,
"lm_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, heap, binary-tree, heap-sort",
"url": null
} |
c#, game, winforms, chess
Title: 2-Player Chess in WinForms
Question: Introduction
I decided to program a two player Chess game in C# windows forms to help me to improve my programming skills and OOP skills.
I have come to a working finished program (as far as I can tell) where two players on the same computer can play chess together.
Here is the Github link to my repo for easy access:
https://github.com/Shinglington/prjChessForms.git
I have also copied the code into here so that the original code at the time of writing can be preserved.
Code
Chess Form
The Form that the game takes place in. Sets up controls for the layout and alternates letting each player make a move.
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
namespace prjChessForms
{
public partial class Chess : Form
{
private Board _board;
private TableLayoutPanel _layoutPanel;
private Label[] _timerLabels;
private System.Timers.Timer _timer;
private SemaphoreSlim _semaphoreClick = new SemaphoreSlim(0, 1);
private CancellationTokenSource cts = new CancellationTokenSource();
private Coords _clickedCoords;
private Coords _fromCoords = new Coords();
private Coords _toCoords = new Coords();
private GameResult _result;
private Player[] _players;
private Player _currentPlayer;
public Chess()
{
InitializeComponent();
CreatePlayers();
SetupControls();
StartGame();
}
public async Task StartGame()
{
await Play(cts.Token);
OnGameOver();
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
public async Task Play(CancellationToken cToken)
{
_currentPlayer = _players[0];
_result = GameResult.Unfinished;
while (_result == GameResult.Unfinished)
{
try
{
_timer.Elapsed += OnPlayerTimerTick;
_timer.Start();
ChessMove move = await GetPlayerMove(cToken);
_timer.Stop();
_timer.Elapsed -= OnPlayerTimerTick;
Rulebook.MakeMove(_board, _currentPlayer, move);
if (_currentPlayer == _players[1])
{
_currentPlayer = _players[0];
}
else
{
_currentPlayer = _players[1];
}
_result = Rulebook.GetGameResult(_board, _currentPlayer);
}
catch when (cToken.IsCancellationRequested)
{
_result = GameResult.Time;
}
}
}
private async Task<ChessMove> GetPlayerMove(CancellationToken cToken)
{ | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
private async Task<ChessMove> GetPlayerMove(CancellationToken cToken)
{
_fromCoords = new Coords();
_toCoords = new Coords();
ChessMove move = new ChessMove();
bool validMove = false;
while (!validMove)
{
await _semaphoreClick.WaitAsync(cToken);
if (_board.GetPieceAt(_clickedCoords) != null && _board.GetPieceAt(_clickedCoords).Owner == _currentPlayer)
{
_fromCoords = _clickedCoords;
_toCoords = new Coords();
_board.ClearHighlights();
_board.HighlightAt(_fromCoords, System.Drawing.Color.AliceBlue);
foreach (ChessMove m in Rulebook.GetPossibleMoves(_board, _board.GetPieceAt(_fromCoords)))
{
_board.HighlightAt(m.EndCoords, System.Drawing.Color.Green);
}
}
else if (!_fromCoords.Equals(new Coords()))
{
_toCoords = _clickedCoords;
}
// Check if move is valid now
if (!_toCoords.Equals(new Coords()) && !_fromCoords.Equals(new Coords()))
{
move = new ChessMove(_fromCoords, _toCoords);
validMove = Rulebook.CheckLegalMove(_board, _currentPlayer, move);
}
}
_board.ClearHighlights();
return move;
}
private void CreatePlayers()
{
_players = new Player[2];
_players[0] = new HumanPlayer(PieceColour.White, new TimeSpan(0, 3, 0));
_players[1] = new HumanPlayer(PieceColour.Black, new TimeSpan(0, 3, 0));
}
private void SetupControls()
{
// Timer
_timer = new System.Timers.Timer(1000);
_timerLabels = new Label[2]; | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
// Layout
_layoutPanel = new TableLayoutPanel()
{
Parent = this,
Dock = DockStyle.Fill,
};
_layoutPanel.ColumnStyles.Clear();
_layoutPanel.RowStyles.Clear();
_layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 90));
_layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 10));
_layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 5));
_layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 90));
_layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 5));
// Board
_board = new Board(_players)
{
Parent = _layoutPanel
};
_layoutPanel.SetCellPosition(_board, new TableLayoutPanelCellPosition(0, 1));
foreach (Square square in _board.GetSquares())
{
square.Click += OnSquareClicked;
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
// White player label
TableLayoutPanel whiteTable = new TableLayoutPanel()
{
Parent = _layoutPanel,
Dock = DockStyle.Fill,
ColumnStyles = { new ColumnStyle(SizeType.Percent, 50), new ColumnStyle(SizeType.Percent, 50) },
RowStyles = { new RowStyle(SizeType.Percent, 100) },
};
_layoutPanel.SetCellPosition(whiteTable, new TableLayoutPanelCellPosition(0, 2));
Label whiteLabel = new Label()
{
Parent = whiteTable,
Dock = DockStyle.Fill,
Text = _players[0].Colour.ToString(),
};
whiteTable.SetCellPosition(whiteLabel, new TableLayoutPanelCellPosition(0, 0));
_timerLabels[0] = new Label()
{
Parent = whiteTable,
Dock = DockStyle.Fill,
Text = _players[0].RemainingTime.ToString(),
};
whiteTable.SetCellPosition(_timerLabels[0], new TableLayoutPanelCellPosition(1, 0));
// Black player label
TableLayoutPanel blackTable = new TableLayoutPanel()
{
Parent = _layoutPanel,
Dock = DockStyle.Fill,
ColumnStyles = { new ColumnStyle(SizeType.Percent, 50), new ColumnStyle(SizeType.Percent, 50) },
RowStyles = { new RowStyle(SizeType.Percent, 100) },
};
_layoutPanel.SetCellPosition(blackTable, new TableLayoutPanelCellPosition(0, 0));
Label blackLabel = new Label()
{
Parent = blackTable,
Dock = DockStyle.Fill,
Text = _players[1].Colour.ToString(),
};
blackTable.SetCellPosition(blackLabel, new TableLayoutPanelCellPosition(0, 0)); | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
_timerLabels[1] = new Label()
{
Parent = blackTable,
Dock = DockStyle.Fill,
Text = _players[1].RemainingTime.ToString(),
};
whiteTable.SetCellPosition(_timerLabels[1], new TableLayoutPanelCellPosition(1, 0));
}
private void OnSquareClicked(object sender, EventArgs e)
{
if (sender is Square square)
{
_clickedCoords = square.Coords;
Console.WriteLine(_clickedCoords);
_semaphoreClick.Release();
}
}
private void OnPlayerTimerTick(object sender, ElapsedEventArgs e)
{
_currentPlayer.TickTime(new TimeSpan(0, 0, 1));
Label timeLabel = _currentPlayer == _players[0] ? _timerLabels[0] : _timerLabels[1];
timeLabel.Invoke((MethodInvoker)delegate
{
timeLabel.Text = _currentPlayer.RemainingTime.ToString();
});
if (TimeSpan.Compare(_currentPlayer.RemainingTime, new TimeSpan(0, 0, 0)) < 1)
{
_timer.Elapsed -= OnPlayerTimerTick;
cts.Cancel();
}
}
private void OnGameOver()
{
cts.Cancel();
foreach (Square s in _board.GetSquares())
{
s.Click -= OnSquareClicked;
}
Player winner = null;
if (_result == GameResult.Checkmate || _result == GameResult.Time)
{
winner = _currentPlayer == _players[0] ? _players[1] : _players[0];
}
MessageBox.Show(_result.ToString() + " ," + (winner != null ? winner.Colour.ToString() : "Nobody") + " Wins");
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
Board and Square classes
Board inherits TableLayoutPanel which displays the Board as a control. Each cell has a Square in it.
Square inherits from Button and can have a piece in it.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace prjChessForms
{
public struct Coords
{
public Coords(int x, int y)
{
X = x;
Y = y;
}
public int X { get; }
public int Y { get; }
public override string ToString()
{
return Convert.ToString(Convert.ToChar(Convert.ToInt32('a') + X)) + Convert.ToString(Y + 1);
}
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != typeof(Coords))
{
return false;
}
else
{
Coords other = (Coords)obj;
return other.X == X && other.Y == Y;
}
}
public override int GetHashCode()
{
int hashCode = 367829482;
hashCode = hashCode * -1521134295 + X.GetHashCode();
hashCode = hashCode * -1521134295 + Y.GetHashCode();
return hashCode;
}
}
class Board : TableLayoutPanel
{
private const int ROW_COUNT = 8;
private const int COL_COUNT = 8;
private Player[] _players;
private Square[,] _squares;
public Board(Player[] players)
{
_players = players;
SetupBoard();
Display();
}
public void Display()
{
foreach (Square s in _squares)
{
s.Parent = this;
SetCellPosition(s, new TableLayoutPanelCellPosition(s.Coords.X, RowCount - 1 - s.Coords.Y));
}
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
public void MakeMove(ChessMove Move)
{
Coords StartCoords = Move.StartCoords;
Coords EndCoords = Move.EndCoords;
Piece p = GetPieceAt(StartCoords);
if (p != null)
{
GetSquareAt(EndCoords).Piece = p;
GetSquareAt(StartCoords).Piece = null;
p.HasMoved = true;
}
}
public King GetKing(PieceColour colour)
{
King king = null;
foreach (Piece p in GetPieces(colour))
{
if (p.GetType() == typeof(King))
{
king = (King)p;
break;
}
}
return king;
}
public List<Piece> GetPieces(PieceColour colour)
{
List<Piece> pieces = new List<Piece>();
Piece p;
for (int y = 0; y < ROW_COUNT; y++)
{
for (int x = 0; x < COL_COUNT; x++)
{
p = GetPieceAt(new Coords(x, y));
if (p != null && p.Colour == colour)
{
pieces.Add(p);
}
}
}
return pieces;
}
public Piece GetPieceAt(Coords coords)
{
return (GetSquareAt(coords).Piece);
}
public Coords GetCoordsOfPiece(Piece piece)
{
if (piece == null)
{
throw new ArgumentNullException();
}
foreach (Square s in GetSquares())
{
if (s.Piece == piece)
{
return s.Coords;
}
}
throw new Exception("Piece could not be located");
}
public Square[,] GetSquares()
{
return _squares;
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
public Square[,] GetSquares()
{
return _squares;
}
public Square GetSquareAt(Coords coords)
{
return _squares[coords.X, coords.Y];
}
public void ClearHighlights()
{
foreach (Square s in GetSquares())
{
s.ResetPanelColour();
}
}
public void HighlightAt(Coords coords, Color highlightColour)
{
GetSquareAt(coords).BackColor = highlightColour;
}
public void RemoveGhostPawns()
{
foreach (Square s in GetSquares())
{
if (s.GetGhostPawn() != null)
{
s.Piece = null;
}
}
}
public bool CheckMoveInCheck(Player player, ChessMove move)
{
Coords start = move.StartCoords;
Coords end = move.EndCoords;
bool startPieceHasMoved = GetPieceAt(start).HasMoved;
Piece originalEndPiece = GetPieceAt(end);
MakeMove(move);
bool SelfCheck = Rulebook.IsInCheck(this, player);
MakeMove(new ChessMove(end, start));
GetSquareAt(start).Piece.HasMoved = startPieceHasMoved;
GetSquareAt(end).Piece = originalEndPiece;
return SelfCheck;
}
private void SetupBoard()
{
// Format
Dock = DockStyle.Fill;
Padding = new Padding(0);
Margin = new Padding(0);
ColumnCount = COL_COUNT;
ColumnStyles.Clear();
RowCount = ROW_COUNT;
ColumnStyles.Clear();
for (int c = 0; c < COL_COUNT; c++)
{
ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100 / COL_COUNT));
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
for (int r = 0; r < ROW_COUNT; r++)
{
RowStyles.Add(new RowStyle(SizeType.Percent, 100 / ROW_COUNT));
}
// Add squares
_squares = new Square[ColumnCount, RowCount];
for (int y = 0; y < ROW_COUNT; y++)
{
for (int x = 0; x < COL_COUNT; x++)
{
_squares[x, y] = new Square(this, x, y);
}
}
// Add pieces
AddDefaultPieces();
}
private void AddDefaultPieces()
{
char[,] defaultPieces =
{
{ 'P','P','P','P','P','P','P','P'},
{ 'R','N','B','Q','K','B','N','R'}
};
// Pieces
Player player;
Square square;
for (int i = 0; i < 2; i++)
{
player = _players[i];
for (int y = 0; y < 2; y++)
{
for (int x = 0; x < COL_COUNT; x++)
{
if (player.Colour == PieceColour.White)
{
square = GetSquareAt(new Coords(x, 1 - y));
}
else
{
square = GetSquareAt(new Coords(x, ROW_COUNT - 2 + y));
}
AddPiece(defaultPieces[y, x], player, square);
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
private void AddPiece(char pieceType, Player player, Square square)
{
Piece p = null;
switch (pieceType)
{
case 'P':
p = new Pawn(player);
break;
case 'N':
p = new Knight(player);
break;
case 'B':
p = new Bishop(player);
break;
case 'R':
p = new Rook(player);
break;
case 'Q':
p = new Queen(player);
break;
case 'K':
p = new King(player);
break;
default:
throw new ArgumentException("Unrecognised pieceType");
}
square.Piece = p;
}
}
class Square : Button
{
private Color _defaultPanelColour;
private Piece _piece;
public Square(Board board, int x, int y)
{
Parent = board;
Coords = new Coords(x, y);
_defaultPanelColour = (x + y) % 2 == 0 ? Color.SandyBrown : Color.LightGray;
Piece = null;
SetupSquare();
}
public Piece Piece
{
get
{
if (_piece != null && _piece.GetType() == typeof(GhostPawn))
{
return null;
}
return _piece;
}
set
{
_piece = value;
UpdateSquare();
}
}
public Coords Coords { get; }
public void ResetPanelColour()
{
BackColor = _defaultPanelColour;
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
public GhostPawn GetGhostPawn()
{
return (_piece != null && _piece.GetType() == typeof(GhostPawn)) ? (GhostPawn)_piece : null;
}
private void SetupSquare()
{
BackColor = _defaultPanelColour;
Dock = DockStyle.Fill;
UpdateSquare();
}
private void UpdateSquare()
{
Image = Piece != null ? Piece.Image : null;
}
}
}
Piece Class
Abstract Piece class is template for the other pieces
Has a CanMove method which returns whether the piece can move from given start and end coordinates while ignoring complications of putting yourself in check etc.
using System;
using System.Drawing;
namespace prjChessForms
{
public enum PieceColour
{
White,
Black
}
abstract class Piece
{
public Piece(Player player)
{
Owner = player;
string imageName = Colour.ToString() + "_" + this.GetType().Name;
try
{
Image = (Image)Properties.Resources.ResourceManager.GetObject(imageName);
}
catch
{
Image = null;
}
}
public bool HasMoved { get; set; }
public Player Owner { get; }
public Image Image { get; }
public PieceColour Colour { get { return Owner.Colour; } }
public abstract bool CanMove(Board board, Coords startCoords, Coords endCoords);
}
class Pawn : Piece
{
public Pawn(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y; | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
int direction = yChange > 0 ? 1 : -1;
if (direction != (Owner.Colour == PieceColour.White ? 1 : -1))
{
return false;
}
if (xChange == 0 && board.GetPieceAt(endCoords) == null)
{
if (Math.Abs(yChange) == 1)
{
allowed = true;
}
else if (Math.Abs(yChange) == 2 && !HasMoved
&& board.GetPieceAt(new Coords(startCoords.X, startCoords.Y + direction)) == null)
{
allowed = true;
}
}
if (Math.Abs(xChange) == 1 && Math.Abs(yChange) == 1)
{
if (board.GetPieceAt(endCoords) != null)
{
allowed = true;
}
}
return allowed;
}
}
class GhostPawn : Piece
{
public GhostPawn(Player player, Pawn referencedPawn) : base(player)
{
LinkedPawn = referencedPawn;
}
public Pawn LinkedPawn { get; }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
return false;
}
}
class Knight : Piece
{
public Knight(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = Math.Abs(endCoords.X - startCoords.X);
int yChange = Math.Abs(endCoords.Y - startCoords.Y);
if ((xChange == 2 && yChange == 1) || (xChange == 1 && yChange == 2))
{
allowed = true;
}
return allowed;
}
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
class Bishop : Piece
{
public Bishop(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (Math.Abs(xChange) == Math.Abs(yChange))
{
allowed = true;
int xDirection = xChange > 0 ? 1 : -1;
int yDirection = yChange > 0 ? 1 : -1;
for (int delta = 1; delta < Math.Abs(xChange); delta += 1)
{
Coords checkCoords = new Coords(startCoords.X + delta * xDirection, startCoords.Y + delta * yDirection);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
return allowed;
}
}
class Rook : Piece
{
public Rook(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (xChange == 0 && yChange != 0)
{
allowed = true;
int direction = yChange > 0 ? 1 : -1;
for (int deltaY = 1; deltaY < Math.Abs(yChange); deltaY += 1)
{
Coords checkCoords = new Coords(startCoords.X, startCoords.Y + deltaY * direction);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
}
else if (yChange == 0 && xChange != 0)
{
allowed = true;
int direction = xChange > 0 ? 1 : -1;
for (int deltaX = 1; deltaX < Math.Abs(xChange); deltaX += 1)
{
Coords checkCoords = new Coords(startCoords.X + deltaX * direction, startCoords.Y);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
return allowed;
}
}
class Queen : Piece
{
public Queen(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
return BishopMove(board, startCoords, endCoords) || RookMove(board, startCoords, endCoords);
}
private bool BishopMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (Math.Abs(xChange) == Math.Abs(yChange))
{
allowed = true;
int xDirection = xChange > 0 ? 1 : -1;
int yDirection = yChange > 0 ? 1 : -1;
for (int delta = 1; delta < Math.Abs(xChange); delta += 1)
{
Coords checkCoords = new Coords(startCoords.X + delta * xDirection, startCoords.Y + delta * yDirection);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
return allowed;
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
private bool RookMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (xChange == 0 && yChange != 0)
{
allowed = true;
int direction = yChange > 0 ? 1 : -1;
for (int deltaY = 1; deltaY < Math.Abs(yChange); deltaY += 1)
{
Coords checkCoords = new Coords(startCoords.X, startCoords.Y + deltaY * direction);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
else if (yChange == 0 && xChange != 0)
{
allowed = true;
int direction = xChange > 0 ? 1 : -1;
for (int deltaX = 1; deltaX < Math.Abs(xChange); deltaX += 1)
{
Coords checkCoords = new Coords(startCoords.X + deltaX * direction, startCoords.Y);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
return allowed;
}
}
class King : Piece
{
public King(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (Math.Abs(xChange) <= 1 && Math.Abs(yChange) <= 1)
{
allowed = true;
}
return allowed;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
Rulebook
Static class which has methods which help with determining whether a move is allowed or not.
Also can get the coordinates for where a piece is allowed to move to.
using System;
using System.Collections.Generic;
namespace prjChessForms
{
public enum GameResult
{
Unfinished,
Checkmate,
Stalemate,
Time
}
public struct ChessMove
{
public ChessMove(Coords startCoords, Coords endCoords)
{
StartCoords = startCoords;
EndCoords = endCoords;
}
public Coords StartCoords { get; }
public Coords EndCoords { get; }
public override string ToString()
{
return StartCoords.ToString() + " -> " + EndCoords.ToString();
}
}
class Rulebook
{
public static void MakeMove(Board board, Player player, ChessMove move)
{
if (!CheckLegalMove(board, player, move))
{
throw new ArgumentException(string.Format("Move {0} is not a valid move", move));
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
if (IsEnPassant(board, move))
{
GhostPawn ghostPawn = board.GetSquareAt(move.EndCoords).GetGhostPawn();
Coords linkedPawnCoords = board.GetCoordsOfPiece(ghostPawn.LinkedPawn);
board.GetSquareAt(linkedPawnCoords).Piece = null;
}
// Remove ghost pawns
board.RemoveGhostPawns();
if (IsDoublePawnMove(board, move))
{
Coords ghostPawnCoords = new Coords(move.StartCoords.X, move.StartCoords.Y + (move.EndCoords.Y - move.StartCoords.Y) / 2);
board.GetSquareAt(ghostPawnCoords).Piece = new GhostPawn(player, (Pawn)board.GetPieceAt(move.StartCoords));
}
else if (IsCastle(board, move))
{
int direction = move.EndCoords.X - move.StartCoords.X > 0 ? 1 : -1;
Coords rookCoords = direction > 0 ? new Coords(board.ColumnCount - 1, move.StartCoords.Y) : new Coords(0, move.StartCoords.Y);
board.MakeMove(new ChessMove(rookCoords, new Coords(move.EndCoords.X + direction * -1, move.EndCoords.Y)));
}
board.MakeMove(move);
Promotions(board, move.EndCoords);
}
public static bool CheckLegalMove(Board board, Player player, ChessMove move)
{
Coords start = move.StartCoords;
Coords end = move.EndCoords; | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
bool legal = false;
Piece movedPiece = board.GetPieceAt(start);
Piece capturedPiece = board.GetPieceAt(end);
if (movedPiece != null && movedPiece.Colour == player.Colour && !start.Equals(end))
{
if (IsEnPassant(board, move) || IsCastle(board, move))
{
legal = true;
}
else if (movedPiece.CanMove(board, start, end))
{
if (capturedPiece == null || (capturedPiece.Colour != player.Colour))
{
if (!board.CheckMoveInCheck(player, move))
{
legal = true;
}
}
}
}
return legal;
}
public static List<ChessMove> GetPossibleMoves(Board board, Piece p)
{
List<ChessMove> possibleMoves = new List<ChessMove>();
Coords pieceCoords = board.GetCoordsOfPiece(p);
if (board.GetPieceAt(pieceCoords) != null)
{
Piece piece = board.GetPieceAt(pieceCoords);
ChessMove move;
for (int y = 0; y < board.RowCount; y++)
{
for (int x = 0; x < board.ColumnCount; x++)
{
move = new ChessMove(pieceCoords, new Coords(x, y));
if (CheckLegalMove(board, piece.Owner, move))
{
possibleMoves.Add(move);
}
}
}
}
return possibleMoves;
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
public static GameResult GetGameResult(Board board, Player currentPlayer)
{
if (IsInStalemate(board, currentPlayer))
{
return GameResult.Stalemate;
}
else if (IsInCheckmate(board, currentPlayer))
{
return GameResult.Checkmate;
}
else
{
return GameResult.Unfinished;
}
}
public static bool IsInCheck(Board board, Player currentPlayer)
{
bool check = false;
King king = board.GetKing(currentPlayer.Colour);
if (king == null)
{
return true;
}
Coords kingCoords = board.GetCoordsOfPiece(king);
foreach (Square square in board.GetSquares())
{
if (square.Piece != null && square.Piece.Owner != currentPlayer)
{
if (CheckLegalMove(board, square.Piece.Owner, new ChessMove(square.Coords, kingCoords)))
{
check = true;
break;
}
}
}
return check;
}
private static bool IsInCheckmate(Board board, Player currentPlayer)
{
if (!IsInCheck(board, currentPlayer))
{
return false;
}
return !CheckIfThereAreRemainingLegalMoves(board, currentPlayer);
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
private static bool IsInStalemate(Board board, Player currentPlayer)
{
if (IsInCheck(board, currentPlayer))
{
return false;
}
return !CheckIfThereAreRemainingLegalMoves(board, currentPlayer);
}
private static bool CheckIfThereAreRemainingLegalMoves(Board board, Player currentPlayer)
{
bool anyLegalMoves = false;
foreach (Piece p in board.GetPieces(currentPlayer.Colour))
{
List<ChessMove> moves = GetPossibleMoves(board, p);
if (moves.Count > 0)
{
anyLegalMoves = true;
break;
}
}
return anyLegalMoves;
}
private static bool IsDoublePawnMove(Board board, ChessMove move)
{
if (board.GetPieceAt(move.StartCoords).GetType() == typeof(Pawn))
{
if (Math.Abs(move.EndCoords.Y - move.StartCoords.Y) == 2)
{
return true;
}
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
return false;
}
private static bool IsCastle(Board board, ChessMove move)
{
bool isCastleMove = false;
if (board.GetPieceAt(move.StartCoords).GetType() == typeof(King) && !board.GetPieceAt(move.StartCoords).HasMoved)
{
if (Math.Abs(move.EndCoords.Y - move.StartCoords.Y) == 0 && Math.Abs(move.EndCoords.X - move.StartCoords.X) == 2)
{
int direction = move.EndCoords.X - move.StartCoords.X > 0 ? 1 : -1;
Coords rookCoords = direction > 0 ? new Coords(board.ColumnCount - 1, move.StartCoords.Y) : new Coords(0, move.StartCoords.Y);
Piece p = board.GetPieceAt(rookCoords);
if (p != null && p.GetType() == typeof(Rook) && !p.HasMoved)
{
isCastleMove = true;
Coords currCoords = new Coords(move.StartCoords.X + direction, move.StartCoords.Y);
while (!currCoords.Equals(rookCoords))
{
if (board.GetPieceAt(currCoords) != null || board.CheckMoveInCheck(p.Owner, new ChessMove(move.StartCoords, currCoords)))
{
isCastleMove = false;
break;
}
currCoords = new Coords(currCoords.X + direction, currCoords.Y);
}
}
}
}
return isCastleMove;
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
private static bool IsEnPassant(Board board, ChessMove move)
{
if (board.GetPieceAt(move.StartCoords).GetType() == typeof(Pawn))
{
Pawn piece = (Pawn)board.GetPieceAt(move.StartCoords);
int legalDirection = (piece.Colour == PieceColour.White ? 1 : -1);
if (Math.Abs(move.EndCoords.X - move.StartCoords.X) == 1 && move.EndCoords.Y - move.StartCoords.Y == legalDirection)
{
GhostPawn ghostPawn = board.GetSquareAt(move.EndCoords).GetGhostPawn();
if (ghostPawn != null && ghostPawn.Colour != piece.Colour)
{
return true;
}
}
}
return false;
}
private static void Promotions(Board board, Coords endCoords)
{
Piece p = board.GetPieceAt(endCoords);
if (p.GetType() == typeof(Pawn))
{
if (endCoords.Y == 0 || endCoords.Y == board.RowCount - 1)
{
board.GetSquareAt(endCoords).Piece = new Queen(p.Owner);
}
}
}
}
}
Player
Stores information about a player.
using System;
using System.Timers;
using System.Windows.Forms;
namespace prjChessForms
{
abstract class Player
{
public Player(PieceColour colour, TimeSpan initialTime)
{
Colour = colour;
RemainingTime = initialTime;
}
public TimeSpan RemainingTime { get; private set; }
public PieceColour Colour { get; }
public void TickTime(TimeSpan time)
{
RemainingTime = RemainingTime.Subtract(time);
}
}
class HumanPlayer : Player
{
public HumanPlayer(PieceColour colour, TimeSpan initialTime) : base(colour, initialTime) { }
} | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
class ComputerPlayer : Player
// Did not use this, but just put it in incase I wanted to add it later
{
public ComputerPlayer(PieceColour colour, TimeSpan initialTime) : base(colour, initialTime) { }
}
}
Program
I don't know if you need this, it is just the default file really, but I've added it just in case.
using System;
using System.Windows.Forms;
namespace prjChessForms
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Chess());
}
}
}
Please take as much time as you need to criticize any aspects of my code to help me to improve my way of programming.
I will try my best to answer any comments / questions if needed as soon as possible.
Answer: Welcome to CodeReview! There is quite a lot to digest here. I have seen just a few things I would like to comment on. For such a fairly big post, you may not get one full answer but hopefully lots of little answers.
Overall, I like it. Both your post and your code is above average for a first time poster. Naming and style is decent. But there are still plenty of opportunities for improvement, or just areas with alternatives may be considered.
Coords Structure
This feels very wordy to me with so many explicit Convert calls:
public override string ToString()
{
return Convert.ToString(Convert.ToChar(Convert.ToInt32('a') + X)) + Convert.ToString(Y + 1);
}
You should shorten it up with a string interpolation:
public override ToString() => $"{(char)('a' + X)}{Y + 1}"; | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
c#, game, winforms, chess
That is shorter to read which makes it easier to follow IMO. My eyeballs can quickly scan the main thing without being distracted by 4 Convert calls.
Abstract Piece Class
I think its nice where you override ToString. Oddly, enough you do not do so with class abstract Piece. To me, and maybe its just me, but this class is just begging for these additions:
public string Name => GetType().Name;
public string Fullname => $"{Colour} {Name}";
public override ToString() => Name;
Now you can easily output "Pawn" or "White Pawn".
Chess Form
The private void OnPlayerTimerTick method has a line that could be better. Specifically, this conditional:
if (TimeSpan.Compare(_currentPlayer.RemainingTime, new TimeSpan(0, 0, 0)) < 1)
I think this is much easier to read and to understand the logic with:
if (_currentPlayer.RemainingTime > TimeSpan.Zero)
For your consideration
There is Principle of Separation of Concerns. To a good extent, you do this. Think of the 2 main chunks of your code. One is all related to the rules and objects for the game of Chess. That is the board, squares, pieces, and all the rules. Let's call this the Chess Logic Library.
The other main chunk is the Winform. Let's call this the Presentation UI.
Imagine if you were going to switch this to a Unity front-end UI. Or maybe a web frond-end. You would want to have the same Chess Logic Library used by the different Presentation UI's since the rules of chess would not change from Winform to web or Unity.
I offer this section purely as something for you to consider. | {
"domain": "codereview.stackexchange",
"id": 44531,
"lm_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, winforms, chess",
"url": null
} |
python, performance, mathematics, numerical-methods
Title: Finite difference estimation of partial derivatives for arbitrary grids in python
Question: I am currently working on testing some codes on python to solve differential equations by finite differences, but some problems and equations i am dealing with are:
Too big to keep manually writing it without heavy risk of mistakes
Often contain nonuniform grids which makes the usual evenly spaced grids finite differences to not apply.
Therefore, to prevent mistakes and to avoid exhaustive handpicking of equations, I decided to make a function that estimates partial derivatives for both arbitrary grids.
What the code does:
Obtains the dependent variable(the one which is to be differentiated)
Obtains the independent variable(basically the discretized grid points)
Checks the dimension of the variable to be differentiated
Checks in what dimension should the derivative be performed, for instance, for a 3D variable with entries [i,j,k] the partial derivative could be relative to i,j,or k.
Then it returns the partial derivative for each entry of the variable, using the Forward Finite Difference method for inner points and one-sided difference for boundary.
import matplotlib.pyplot as plt
import numpy as np
import sympy as sp
from scipy.optimize import fsolve
from scipy import optimize
import pandas as pd
from numba import njit | {
"domain": "codereview.stackexchange",
"id": 44532,
"lm_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, mathematics, numerical-methods",
"url": null
} |
python, performance, mathematics, numerical-methods
@njit
def partial(var,var2,dim):
y = var
x = var2
vardim = var.ndim
invalid_input = 0
#Forward
if vardim == 1 and dim == 1:
dydx = np.zeros(len(y))
for i in range(len(dydx)):
if i == len(dydx) - 1:
dydx[i] =( (-1/(x[i-2]-x[i]) - 1/(x[i-1]-x[i])) * y[i]
-(x[i-2]-x[i])/((x[i-1]-x[i-2])*(x[i-1]-x[i])) * y[i-1]
+(x[i-1]-x[i])/((x[i-1]-x[i-2])*(x[i-2]-x[i])) * y[i-2] )
else:
dydx[i] = (y[i+1] - y[i])/(x[i+1] - x[i])
elif vardim == 2 and dim == 1:
dydx = np.zeros((len(y[:,0]), len(y[0,:])))
for i in range(len(dydx[:,0])):
for j in range(len(dydx[0,:])):
if i == len(dydx[:,0]) - 1:
dydx[i,j] =( (-1/(x[i-2]-x[i]) - 1/(x[i-1]-x[i])) * y[i,j]
-(x[i-2]-x[i])/((x[i-1]-x[i-2])*(x[i-1]-x[i])) * y[i-1,j]
+(x[i-1]-x[i])/((x[i-1]-x[i-2])*(x[i-2]-x[i])) * y[i-2,j] )
else:
dydx[i,j] = (y[i+1,j] - y[i,j])/(x[i+1] - x[i])
elif vardim == 2 and dim == 2:
dydx = np.zeros((len(y[:,0]), len(y[0,:])))
for i in range(len(dydx[:,0])):
for j in range(len(dydx[0,:])):
if j == len(dydx[0,:]) - 1:
dydx[i,j] =( (-1/(x[j-2]-x[j]) - 1/(x[j-1]-x[j])) * y[i,j]
-(x[j-2]-x[j])/((x[j-1]-x[j-2])*(x[j-1]-x[j])) * y[i,j-1]
+(x[j-1]-x[j])/((x[j-1]-x[j-2])*(x[j-2]-x[j])) * y[i,j-2] )
else:
dydx[i,j] = (y[i,j+1] - y[i,j])/(x[j+1] - x[j])
elif vardim == 3 and dim == 1:
dydx = np.zeros((len(y[:,0,0]), len(y[0,:,0]), len(y[0,0,:])))
for i in range(len(dydx[:,0,0])): | {
"domain": "codereview.stackexchange",
"id": 44532,
"lm_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, mathematics, numerical-methods",
"url": null
} |
python, performance, mathematics, numerical-methods
for i in range(len(dydx[:,0,0])):
for j in range(len(dydx[0,:,0])):
for k in range(len(dydx[0,0,:])):
if i == len(dydx[:,0,0]) - 1:
dydx[i,j,k] =( (-1/(x[i-2]-x[i]) - 1/(x[i-1]-x[i])) * y[i,j,k]
-(x[i-2]-x[i])/((x[i-1]-x[i-2])*(x[i-1]-x[i])) * y[i-1,j,k]
+(x[i-1]-x[i])/((x[i-1]-x[i-2])*(x[i-2]-x[i])) * y[i-2,j,k] )
else:
dydx[i,j,k] = (y[i+1,j,k] - y[i,j,k])/(x[i+1] - x[i])
elif vardim == 3 and dim == 2:
dydx = np.zeros((len(y[:,0,0]), len(y[0,:,0]), len(y[0,0,:])))
for i in range(len(dydx[:,0,0])):
for j in range(len(dydx[0,:,0])):
for k in range(len(dydx[0,0,:])):
if j == len(dydx[0,:,0])-1:
dydx[i,j,k] =( (-1/(x[j-2]-x[j]) - 1/(x[j-1]-x[j])) * y[i,j,k]
-(x[j-2]-x[j])/((x[j-1]-x[j-2])*(x[j-1]-x[j])) * y[i,j-1,k]
+(x[j-1]-x[j])/((x[j-1]-x[j-2])*(x[j-2]-x[j])) * y[i,j-2,k] )
else:
dydx[i,j,k] = (y[i,j+1,k] - y[i,j,k])/(x[j+1] - x[j])
elif vardim == 3 and dim == 3:
dydx = np.zeros((len(y[:,0,0]), len(y[0,:,0]), len(y[0,0,:])))
for i in range(len(dydx[:,0,0])):
for j in range(len(dydx[0,:,0])):
for k in range(len(dydx[0,0,:])):
if k == len(dydx[0,0,:]) - 1:
dydx[i,j,k] =( (-1/(x[k-2]-x[k]) - 1/(x[k-1]-x[k])) * y[i,j,k]
-(x[k-2]-x[k])/((x[k-1]-x[k-2])*(x[k-1]-x[k])) * y[i,j,k-1]
+(x[k-1]-x[k])/((x[k-1]-x[k-2])*(x[k-2]-x[k])) * y[i,j,k-2] )
else: | {
"domain": "codereview.stackexchange",
"id": 44532,
"lm_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, mathematics, numerical-methods",
"url": null
} |
python, performance, mathematics, numerical-methods
else:
dydx[i,j,k] = (y[i,j,k+1] - y[i,j,k])/(x[k+1] - x[k])
else:
invalid_input = 1
if invalid_input == 1:
raise ValueError('Invalid Input')
else:
return dydx | {
"domain": "codereview.stackexchange",
"id": 44532,
"lm_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, mathematics, numerical-methods",
"url": null
} |
python, performance, mathematics, numerical-methods
I am already using njit to speed up the function, and it indeed is much faster than without it, but even so, this code is still much slower than writing out the equations manually and adds a bottleneck on the problem solving. Since i am dealing with systems that will contain thousands of variables, the difference in time gets significant.
Is there any way to improve the efficiency of the code above?
Thanks.
EDIT: Time test example
compile_function = partial(np.linspace(0,5,6),np.linspace(0,5,6),1)
Test_variable = np.linspace(0,10000000,10000001)
Test_grid = np.linspace(0,10000000,10000001)
t0 = time.time()
partial(Test_variable,Test_grid,1)
elapsed = time.time() - t0
print(elapsed)
0.04687905311584473
Answer: As @J_H said. This is not properly answerable in its current state, but as a review of the code and standards.
Split your code into simple functions
Instead of having your methods all in a block in the same partial function, divide your code into sub-functions:
def calc_diff_1d_dx(x, y)
dydx = np.zeros(len(y))
for i in range(len(dydx)):
if i == len(dydx) - 1:
dydx[i] =( (-1/(x[i-2]-x[i]) - 1/(x[i-1]-x[i])) * y[i]
-(x[i-2]-x[i])/((x[i-1]-x[i-2])*(x[i-1]-x[i])) * y[i-1]
+(x[i-1]-x[i])/((x[i-1]-x[i-2])*(x[i-2]-x[i])) * y[i-2] )
else:
dydx[i] = (y[i+1] - y[i])/(x[i+1] - x[i])
Then, your big select statement becomes:
if vardim == 1 and dim == 1:
calc_diff_1d_dx(x, y)
elif vardim == 2 and dim == 1:
calc_diff_2d_dx(x, y)
elif vardim == 2 and dim == 2:
calc_diff_2d_dy(x, y)
... | {
"domain": "codereview.stackexchange",
"id": 44532,
"lm_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, mathematics, numerical-methods",
"url": null
} |
python, performance, mathematics, numerical-methods
This means we can then focus down on optimising/timing each of these independently.
Testing
Before you ever start optimising, however, you need good testing, particularly regression testing, just to make sure that whatever you change doesn't affect your answer in a questionable way. A lot of optimisations can (and will) change your answer, but you have to be aware of what is an acceptable change in your circumstances. Does an absolute difference of 1e-10 affect your result? How about 1%? etc.
Without tests and a fully working code, there's no hope of optimising sensibly.
Tests also give us the benefit of a stable state to compare times with.
Obvious efficiency gain
One obvious thing right away is that you're looping with ifs in the loops to check whether you're on the final iteration. Stop your loop one early and evaluate the part in the if as a final step.
for i in range(len(dydx)):
if i == len(dydx) - 1:
dydx[i] =( (-1/(x[i-2]-x[i]) - 1/(x[i-1]-x[i])) * y[i]
-(x[i-2]-x[i])/((x[i-1]-x[i-2])*(x[i-1]-x[i])) * y[i-1]
+(x[i-1]-x[i])/((x[i-1]-x[i-2])*(x[i-2]-x[i])) * y[i-2] )
else:
dydx[i] = (y[i+1] - y[i])/(x[i+1] - x[i])
Becomes
for i in range(len(dydx)-1):
dydx[i] = (y[i+1] - y[i])/(x[i+1] - x[i])
i = len(dydx) - 1
dydx[i] =( (-1/(x[i-2]-x[i]) - 1/(x[i-1]-x[i])) * y[i]
-(x[i-2]-x[i])/((x[i-1]-x[i-2])*(x[i-1]-x[i])) * y[i-1]
+(x[i-1]-x[i])/((x[i-1]-x[i-2])*(x[i-2]-x[i])) * y[i-2] )
This makes things much clearer
You aren't performing a comparison every step of the loop and potentially branching. I'm not 100% sure on how Numba's JIT would optimise this, but this could kill many compiled languages' performance if they aren't smart enough to spot it. | {
"domain": "codereview.stackexchange",
"id": 44532,
"lm_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, mathematics, numerical-methods",
"url": null
} |
python, performance, mathematics, numerical-methods
Further optimisation
In terms of general good techniques for optimisation, my first recommendation is to find a library which does what you want. Generally, you don't want to have to implement high-performance mathematical algorithms yourself except as a learning experience (unless they really definitely don't exist/are no longer supported).
In your code, you are using numpy, but doing looping through them in Python (something which should be avoided in optimising anyway), which is wasting the potential of numpy which has optimised, vectorised routines in C to do the heavy lifting. If you want it to be fast, you should be exploiting these as much as you can, rather than relying on JIT to get performance. | {
"domain": "codereview.stackexchange",
"id": 44532,
"lm_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, mathematics, numerical-methods",
"url": null
} |
c++, a-star
Title: A* algorithm on a 2D vector of enum
Question: here is the A* implementation:
#include <queue>
#include <stdexcept>
#include <unordered_map>
enum class TileType {
DebugWall,
Empty,
Floor,
Wall,
Obstacle,
Player,
HealthPotion,
ArmourPotion,
HealthBoostPotion,
ArmourBoostPotion,
SpeedBoostPotion,
FireRateBoostPotion
};
template<class T>
inline void hash_combine(size_t &seed, const T &v) {
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
struct Point {
int x, y;
inline bool operator==(const Point pnt) const {
return x == pnt.x && y == pnt.y;
}
inline bool operator!=(const Point pnt) const {
return x != pnt.x || y != pnt.y;
}
Point() = default;
Point(int x_val, int y_val) {
x = x_val;
y = y_val;
}
std::pair<int, int> sum(Point &other) const {
return std::make_pair(x + other.x, y + other.y);
}
std::pair<int, int> abs_diff(Point &other) const {
return std::make_pair(abs(x - other.x), abs(y - other.y));
}
};
template<>
struct std::hash<Point> {
size_t operator()(const Point &pnt) const {
size_t res = 0;
hash_combine(res, pnt.x);
hash_combine(res, pnt.y);
return res;
}
};
const std::vector<Point> INTERCARDINAL_OFFSETS = {
{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1},
};
struct Neighbour {
int cost;
Point pair;
inline bool operator<(const Neighbour nghbr) const {
return cost >= nghbr.cost;
}
};
std::vector<Point> grid_bfs(Point &target, int height, int width) {
std::vector<Point> result;
for (Point offset : INTERCARDINAL_OFFSETS) {
int x = target.x + offset.x;
int y = target.y + offset.y;
if ((x >= 0 && x < width) && (y >= 0 && y < height)) {
result.emplace_back(x, y);
}
}
return result;
} | {
"domain": "codereview.stackexchange",
"id": 44533,
"lm_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++, a-star",
"url": null
} |
c++, a-star
return result;
}
std::vector<Point>
calculate_astar_path(std::vector<std::vector<TileType>> &grid, Point &start,
Point &end) {
std::vector<Point> result;
std::priority_queue<Neighbour> queue;
std::unordered_map<Point, Point> came_from = {{start, start}};
std::unordered_map<Point, int> distances = {{start, 0}};
int height = (int) grid.capacity();
int width = (int) grid[0].capacity();
queue.push({0, start});
while (!queue.empty()) {
Point current = queue.top().pair;
queue.pop();
if (current == end) {
while (!(came_from[current] == current)) {
result.emplace_back(current.x, current.y);
current = came_from[current];
}
result.emplace_back(start.x, start.y);
break;
}
for (Point neighbour : grid_bfs(current, height, width)) {
if (grid[neighbour.y][neighbour.x] == TileType::Obstacle) {
continue;
}
int distance = distances[current] + 1;
if ((!came_from.contains(neighbour)) || distance < distances.at(neighbour)) {
came_from[neighbour] = current;
distances[neighbour] = distance;
queue.push({distance + std::max(abs(end.x - neighbour.x), abs(end.y - neighbour.y)), neighbour});
}
}
}
return result;
}
The main problem I have right now is the order in which INTERCARDINAL_OFFSETS is iterated through. Since the bottom-right direction is last so it will always prefer going in the bottom-right direction since that node is added to the heap last. Is there a way I can improve this implementation?
Answer: Make better use of class Point
I see you created a class Point that represents a 2D coordinate, but you are not making very good use of it. Instead of the weird sum() member function that returns a std::pair<int, int> and which you don't even use, consider adding an operator+() member function that returns another Point:
Point operator+(const Point& other) const {
return {x + other.x, y + other.y};
} | {
"domain": "codereview.stackexchange",
"id": 44533,
"lm_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++, a-star",
"url": null
} |
c++, a-star
Then you can change grid_bfs() like so:
std::vector<Point> grid_bfs(Point target, …) {
std::vector<Point> result;
for (Point offset: INTERCARDINAL_OFFSETS) {
Point grid_point = target + offset;
if (…) {
result.emplace_back(grid_point);
}
}
return result;
}
Note that width and height together also form a 2D coordinate. Instead of passing those individually, pass them as a Point, and maybe name it grid_size or top_right (assuming the origin is bottom left). Then you could write:
bool is_in_range(Point point, Point max) {
return point.x >= 0 && point.x < max.x && point.y >= 0 && point.y < max.y;
}
std::vector<Point> grid_bfs(Point target, Point grid_size) {
…
if (is_in_range(grid_point, grid_size) {
result.emplace_back(grid_point);
}
…
}
Try to get rid of all occurences where you manually pass x and y or width and height separately, and replace them with calls to functions or operators that work on Points as a whole.
Pass by const reference where appropriate
If you pass something by reference or pointer, but you are not modifying the data that is passed in, make sure you make it a const reference or pointer. This will allow the compiler to generate more optimal code, and it will catch potential mistakes if you do accidentally write to it.
Alternatively, you can pass small things by value. For something like a Point, which only contains two ints, it might even be more efficient than passing by reference, although with optimizations enabled, the compiler will probably generate the exact same code.
Avoid unnecessary temporary variables
In this line of code:
for (Point neighbour : grid_bfs(current, height, width)) {
The call to grid_bfs() will return a temporary std::vector<Point>. That might seem innocent, but std::vector will do memory allocations behind the scenes. But you don't need need that. There are various ways around this: | {
"domain": "codereview.stackexchange",
"id": 44533,
"lm_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++, a-star",
"url": null
} |
c++, a-star
Just manually inline grid_bfs() here:
for (Point offset : INTERCARDINAL_OFFSETS) {
Point neighbour = current + offset;
if (!is_in_range(neighbour, grid_size)) {
continue;
}
Make grid_bfs a class that has begin() and end() member functions that return iterators that yield valid neighbour points.
Turn grid_bfs() into a coroutine that returns a std::generator<Point>. Made easy in C++23, but also possible in C++20 (see also Lewis Baker's CppCoro library).
Don't use at() unnecessarily
Using at() on a container will check if the element exists, and if not will throw an exception. This wastes CPU cycles if you already know the element is in the container. In this line:
if ((!came_from.contains(neighbour)) || distance < distances.at(neighbour)) {
The right hand side of || will only be evaluated if came_from.container(neighbour) is true, and since you always add items both to came_from and distances at the same time, you then know that distances will also contain neighbour.
Merge came_from and distances
You have two std::unordered_maps, but they always contain the same Points as keys. That just wastes memory and requires two lookups instead of one in most cases. You already have a struct Neighbour that holds a Point and an int, so I would replace the two maps with one std::unordered_map<Point, Neighbour> neighbours. | {
"domain": "codereview.stackexchange",
"id": 44533,
"lm_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++, a-star",
"url": null
} |
javascript, node.js, configuration
Title: Node.js configuration object based on environment variables
Question: In the code below, I am building a NODE_ENV-sensitive config object from environment variables.
let username
let password
let cluster
let hosts
let databaseName
let replicaSet
if (process.env.NODE_ENV === 'production') {
username = process.env.ATLAS_HUB_USERNAME
password = process.env.ATLAS_HUB_PASSWORD
cluster = process.env.ATLAS_CLUSTER
hosts = process.env.ATLAS_HOSTS
databaseName = process.env.ATLAS_DATABASE
replicaSet = process.env.ATLAS_REPLICA_SET
} else {
username = process.env.MONGO_HUB_USERNAME
password = process.env.MONGO_HUB_PASSWORD
cluster = process.env.MONGO_CLUSTER
hosts = process.env.MONGO_HOSTS
databaseName = process.env.MONGO_DATABASE
replicaSet = process.env.MONGO_REPLICA_SET
}
const config = { username, password, cluster, hosts, databaseName, replicaSet }
In this new age of fancy spread and rest operators, I hate polluting my files with code like this which repeat the same variable name multiple times and uses let instead of const for the wrong reasons, all for something simple and frequent. I could use the ternary operator to get something way better:
const config = {
username: process.env.NODE_ENV === 'production' ? process.env.ATLAS_HUB_USERNAME : process.env.MONGO_HUB_USERNAME,
password: process.env.NODE_ENV === 'production' ? process.env.ATLAS_HUB_PASSWORD : process.env.MONGO_HUB_PASSWORD,
cluster: process.env.NODE_ENV === 'production' ? process.env.ATLAS_CLUSTER : process.env.MONGO_CLUSTER,
hosts: process.env.NODE_ENV === 'production' ? process.env.ATLAS_HOSTS : process.env.MONGO_HOSTS,
databaseName: process.env.NODE_ENV === 'production' ? process.env.ATLAS_DATABASE : process.env.MONGO_DATABASE,
replicaSet: process.env.NODE_ENV === 'production' ? process.env.ATLAS_REPLICA_SET : process.env.MONGO_REPLICA_SET
} | {
"domain": "codereview.stackexchange",
"id": 44534,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js, configuration",
"url": null
} |
javascript, node.js, configuration
But even this seems one step short of what modern js should be able to do. I'd now like to get rid of the repeated process.env.NODE_ENV, I just can't figure out how (apart from creating a new const with a shorter name). If I had a magic wand, I'd write something along the following lines:
const config = ({
username: [process.env.MONGO_HUB_USERNAME, process.env.ATLAS_HUB_USERNAME],
password: [process.env.MONGO_HUB_PASSWORD, process.env.ATLAS_HUB_PASSWORD],
cluster: [process.env.MONGO_CLUSTER, process.env.ATLAS_CLUSTER],
hosts: [process.env.MONGO_HOSTS, process.env.ATLAS_HOSTS],
databaseName: [process.env.MONGO_DATABASE, process.env.ATLAS_DATABASE],
replicaSet: [process.env.MONGO_REPLICA_SET, process.env.ATLAS_REPLICA_SET]
}).*[new Number(process.env.NODE_ENV === 'production')]
But I don't, and it's not even all that great, sooo, any suggestions?
I thought of using a function, like below, but this just introduces another dependency you need to internalize for a simple batch conditional assignment operation... And if the function is in-line, there is duplication across files and it's frankly just confusing.
function fromEach (obj, key) {
const final = {}
Object.keys(obj).forEach((k) => {
final[k] = obj[k][key]
})
return final
}
const config = fromEach({
username: [process.env.MONGO_HUB_USERNAME, process.env.ATLAS_HUB_USERNAME],
password: [process.env.MONGO_HUB_PASSWORD, process.env.ATLAS_HUB_PASSWORD],
cluster: [process.env.MONGO_CLUSTER, process.env.ATLAS_CLUSTER],
hosts: [process.env.MONGO_HOSTS, process.env.ATLAS_HOSTS],
databaseName: [process.env.MONGO_DATABASE, process.env.ATLAS_DATABASE],
replicaSet: [process.env.MONGO_REPLICA_SET, process.env.ATLAS_REPLICA_SET]
}, new Number(process.env.NODE_ENV === 'production'))
Note: I use new Number(process.env.NODE_ENV === 'production') in these examples, but I don't like it, feel free to propose something better! | {
"domain": "codereview.stackexchange",
"id": 44534,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js, configuration",
"url": null
} |
javascript, node.js, configuration
Answer: Years later, I'm using a different approach of expecting environment-appropriate values in the environment variables and delegating the decision to the execution context.
First, we define the values for the variables in various environments:
.env.development
HUB_USERNAME=usernameForDevelopment
HUB_PASSWORD=passwordForDevelopment
CLUSTER=clusterForDevelopment
HOSTS=hostsForDevelopment
DATABASE=databaseForDevelopment
REPLICA_SET=replicaSetForDevelopment
.env.production
HUB_USERNAME=usernameForProduction
HUB_PASSWORD=passwordForProduction
CLUSTER=clusterForProduction
HOSTS=hostsForProduction
DATABASE=databaseForProduction
REPLICA_SET=replicaSetForProduction
Next, we expect the correct file to have been used and the variables to have environment-appropriate values, removing the need for the process.env.NODE_ENV === 'production' conditional altogether:
index.js
const env = process.env
const config = {
username: env.HUB_USERNAME,
password: env.HUB_PASSWORD,
cluster: env.CLUSTER,
hosts: env.HOSTS,
databaseName: env.DATABASE,
replicaSet: env.REPLICA_SET
}
The execution context can decide which set of variables to use.
For example, in Next.js, it looks like this:
next dev // Environment variables fetched from `.env.development`
next start // Environment variables fetched from `.env.production`
Or, using Node.js directly (with the help of the dotenv package, don't forget to npm i -D dotenv):
node -r dotenv/config index.js dotenv_config_path=.env.development // DEV
node -r dotenv/config index.js dotenv_config_path=.env.production // PROD | {
"domain": "codereview.stackexchange",
"id": 44534,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js, configuration",
"url": null
} |
c++, multithreading, thread-safety, queue
Title: ThreadSafe std::queue
Question: I have written a threadsafe queue and I would like you to suggest what can be improved and how to write good unit tests for this implementation.
#include <mutex>
#include <queue>
#include <atomic>
#include <condition_variable>
#include <concepts>
#include <optional>
template<typename LockT>
concept Lockable = requires(LockT lock) {
{ lock.try_lock() } -> std::convertible_to<bool>;
{ lock.lock() } -> std::convertible_to<void>;
{ lock.unlock() }-> std::convertible_to<void>;
};
template<typename T, Lockable LockT = std::mutex>
struct ThreadSafeQueue
{
ThreadSafeQueue() = default;
void push(std::convertible_to<T> auto&& func)
{
{
std::scoped_lock lock(lockT);
queue.push(std::forward<decltype(func)>(func));
}
cv.notify_one();
}
[[nodiscard]] T pop()
{
T item = std::move(pop_opt().value());
return item;
}
[[nodiscard]] std::optional<T> try_pop()
{
auto item = pop_opt();
return item;
}
[[nodiscard]] inline std::size_t size()
{
std::scoped_lock lock(lockT);
return queue.size();
}
[[nodiscard]] inline bool empty()
{
std::scoped_lock lock(lockT);
return queue.empty();
}
inline void request_quit()
{
quit = true;
cv.notify_all();
}
[[nodiscard]] inline bool quit_requested() const
{
return quit;
}
private:
[[nodiscard]] std::optional<T> pop_opt()
{
std::unique_lock lock(lockT);
while (queue.empty() && !quit) {
cv.wait(lock);
}
if (queue.empty()) {
return std::nullopt;
}
auto item = std::move(queue.front());
queue.pop();
lock.unlock();
return item;
}
std::queue<T> queue;
LockT lockT;
std::condition_variable_any cv;
std::atomic_bool quit = false;
}; | {
"domain": "codereview.stackexchange",
"id": 44535,
"lm_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, thread-safety, queue",
"url": null
} |
c++, multithreading, thread-safety, queue
#include <gtest/gtest.h>
#include <vector>
#include "ThreadSafeQueue.h"
TEST(ThreadSafeQueueTest, MultipleThreads)
{
ThreadSafeQueue<int> queue;
constexpr static std::size_t kNumThreads = 10;
constexpr static int kNumIterations = 1000;
std::vector<std::thread> threads;
threads.reserve(kNumThreads);
for (int i = 0; i < kNumThreads; ++i) {
threads.emplace_back([&queue]() {
for (int j = 0; j < kNumIterations; ++j) {
queue.push(j);
}
});
}
for (int i = 0; i < kNumThreads; ++i) {
threads.emplace_back([&queue]() {
for (int j = 0; j < kNumIterations; ++j) {
int value = queue.pop();
EXPECT_GE(value, 0);
EXPECT_LT(value, kNumIterations);
}
});
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_TRUE(queue.empty());
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | {
"domain": "codereview.stackexchange",
"id": 44535,
"lm_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, thread-safety, queue",
"url": null
} |
c++, multithreading, thread-safety, queue
Answer: Why is there a template parameter LockT?
I don't understand why there is a template parameter for the type of lockT, but not for the type of queue. I think I'd rather have the type of queue be a template parameter, so that you could create one with a non-default allocator. Changing the type of lock is potentially dangerous; can your ThreadSafeQueue really guarantee thread-safety if it doesn't know that kind of lock is used?
I also don't see any use case for any of the mutex types from the standard library, other than the standard one. You are only using std::scoped_lock, so you will never benefit from std::shared_mutex or any of the timed mutexes. A std::recursive_mutex also doesn't make sense, since your class never recurses itself, and mutexT is private so nothing else could take that lock.
Remove size() and empty()
I see these member functions often added to thread safe queue implementations. It might seem natural since it's like a container, and the standard containers also provide these functions. However, by the time size() and empty() return, the value they return might no longer be valid. So the caller should not trust the results, and is in fact better off not calling them at all.
Missing std::move() in try_pop()
In try_pop() you don't use std::move(), resulting in a potentially suboptimal copy being made.
I recommend that you don't use temporary variables at all if they are unnecessary; this avoids needing to use std::move() to begin with:
[[nodiscard]] T pop()
{
return pop_opt().value();
}
[[nodiscard]] std::optional<T> try_pop()
{
return pop_opt();
} | {
"domain": "codereview.stackexchange",
"id": 44535,
"lm_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, thread-safety, queue",
"url": null
} |
python, numpy, mathematics, finance, scipy
Title: Fixing math library functions in Black-Scholes options pricing model
Question: I've amended a code for the Black-Scholes formula for European pricing options found here at the bottom of the page and fixed the math functions accordingly. Unlike the code on the website, mine has run successfully giving me the correct mathematical solution.
Would this be the method in solving this issue?
Could the coding be improved?
import scipy.stats as sp
import numpy as np
class BsmModel:
def __init__(self, option_type, price, strike, interest_rate, expiry, volatility, dividend_yield=0):
self.s = price # Underlying asset price
self.k = strike # Option strike K
self.r = interest_rate # Continuous risk fee rate
self.q = dividend_yield # Dividend continuous rate
self.T = expiry # time to expiry (year)
self.sigma = volatility # Underlying volatility
self.type = option_type # option type "p" put option "c" call option
def n(self, d):
# cumulative probability distribution function of standard normal distribution
return sp.norm.cdf(d)
def dn(self, d):
# the first order derivative of n(d)
return sp.norm.pdf(d)
def d1(self):
return (math.log(self.s / self.k) + (self.r - self.q + self.sigma ** 2 * 0.5) * self.T) / (self.sigma * math.sqrt(self.T))
def d2(self):
return (math.log(self.s / self.k) + (self.r - self.q - self.sigma ** 2 * 0.5) * self.T) / (self.sigma * math.sqrt(self.T)) | {
"domain": "codereview.stackexchange",
"id": 44536,
"lm_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, numpy, mathematics, finance, scipy",
"url": null
} |
python, numpy, mathematics, finance, scipy
def bsm_price(self):
d1 = self.d1()
d2 = d1 - self.sigma * math.sqrt(self.T)
if self.type == 'c':
return math.exp(-self.r*self.T) * (self.s * math.exp((self.r - self.q)*self.T) * self.n(d1) - self.k * self.n(d2))
if self.type == 'p':
return math.exp(-self.r*self.T) * (self.k * self.n(-d2) - (self.s * math.exp((self.r - self.q)*self.T) * self.n(-d1)))
print ("option type can only be c or p")
a = BsmModel('c', 42, 35, 0.1, 90.0/365, 0.2)
a.bsm_price()
## 7.8778518797804225
The error I received using the code from the website was:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-25-0e7b66f29cf6> in <module>
35
36 a = BsmModel('c', 42, 35, 0.1, 90.0/365, 0.2)
---> 37 a.bsm_price()
<ipython-input-25-0e7b66f29cf6> in bsm_price(self)
26
27 def bsm_price(self):
---> 28 d1 = self.d1()
29 d2 = d1 - self.sigma * sqrt(self.T)
30 if self.type == 'c':
<ipython-input-25-0e7b66f29cf6> in d1(self)
20
21 def d1(self):
---> 22 return (log(self.s / self.k) + (self.r - self.q + self.sigma ** 2 * 0.5) * self.T) / (self.sigma * sqrt(self.T))
23
24 def d2(self):
NameError: name 'log' is not defined
Answer:
Would this be the method in solving this issue?
No.
You seem to reporting that some narrative discourse in a HTML
web page omitted an obvious from math import log statement.
Which is rather different from code published on github / pypi
lacking the import.
The appropriate remedy is
in the immediate timeframe, create local file which imports log plus author's code so you can use it now
report the issue to the author so in coming weeks we will see an upstream fix | {
"domain": "codereview.stackexchange",
"id": 44536,
"lm_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, numpy, mathematics, finance, scipy",
"url": null
} |
python, numpy, mathematics, finance, scipy
If the author had published this code on e.g. GitHub,
the appropriate response would be to politely submit a
PR
that adds a suggested import. | {
"domain": "codereview.stackexchange",
"id": 44536,
"lm_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, numpy, mathematics, finance, scipy",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Title: A recursive_transform_view Template Function Implementation
Question: This is a follow-up question for A recursive_transform Template Function with Unwrap Level for std::array Implementation in C++. Considering the suggestion mentioned in Davislor's answer, I am trying to implement recursive_transform_view template function and comparing it with recursive_transform template function. The proposed experimental implementation is tested with int (non-nested input test), non-nested std::array, std::vector container. Please noticed that without specifying unwrap_level, generic lambda (auto&& or auto) cannot be used.
The experimental implementation
The experimental implementations of recursive_transform_view template function is as follows.
recursive_transform_view function implementation:
/* Base case of recursive_transform_view template function
https://codereview.stackexchange.com/a/283581/231235
*/
template< typename T,
std::invocable<T> F >
requires (std::copy_constructible<F>)
constexpr auto recursive_transform_view( const T& input, const F& f )
{
return std::invoke( f, input );
}
/* The recursive case of recursive_transform_view template function
https://codereview.stackexchange.com/a/283581/231235
*/
template< template<typename...> typename Container,
std::copy_constructible F,
typename... Ts >
requires (std::ranges::input_range<Container<Ts...>>&&
std::ranges::view<Container<Ts...>>)
constexpr auto recursive_transform_view(const Container<Ts...>& input, const F& f)
{
const auto view = std::ranges::transform_view(
std::ranges::subrange( std::begin(input), std::end(input) ),
[f](const auto& x) constexpr { return recursive_transform_view( x, f ); } );
recursive_invoke_result_t<F, Container<Ts...>> output( view.begin(), view.end() ); | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// One last sanity check.
if constexpr( is_sized<Container<Ts...>> && is_sized<recursive_invoke_result_t<F, Container<Ts...>>> )
{
assert( output.size() == input.size() );
}
return output;
}
/* The recursive case of recursive_transform_view template function for std::array
https://codereview.stackexchange.com/a/283581/231235
*/
template< template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
std::copy_constructible F>
requires std::ranges::input_range<Container<T, N>>
constexpr auto recursive_transform_view(const Container<T, N>& input, const F& f)
{
Container<recursive_invoke_result_t<F, T>, N> output;
std::ranges::transform( // Use std::ranges::transform() for std::arrays
input,
std::begin(output),
[&f](auto&& element){ return recursive_transform_view(element, f); }
);
// One last sanity check.
if constexpr( is_sized<Container<T, N>> && is_sized<recursive_invoke_result_t<F, Container<T, N>>> )
{
assert( output.size() == input.size() );
}
return output;
}
Full Testing Code
The full testing code:
// A recursive_transform_view Template Function Implementation
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <queue>
#include <ranges>
#include <stack>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
// is_reservable concept
template<class T>
concept is_reservable = requires(T input)
{
input.reserve(1);
}; | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// is_sized concept, https://codereview.stackexchange.com/a/283581/231235
template<class T>
concept is_sized = requires(T x)
{
std::size(x);
};
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return 0;
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + 1;
}
// recursive_invoke_result_t implementation
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>>&& // F cannot be invoked to Container<Ts...> directly
std::ranges::input_range<Container<Ts...>>&&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<
typename recursive_invoke_result<
F,
std::ranges::range_value_t<Container<Ts...>>
>::type
>;
};
template<template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
std::invocable<Container<T, N>> F>
struct recursive_invoke_result<F, Container<T, N>>
{
using type = std::invoke_result_t<F, Container<T, N>>;
}; | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
typename F>
requires (
!std::invocable<F, Container<T, N>>&& // F cannot be invoked to Container<Ts...> directly
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<T, N>>>::type; })
struct recursive_invoke_result<F, Container<T, N>>
{
using type = Container<
typename recursive_invoke_result<
F,
std::ranges::range_value_t<Container<T, N>>
>::type
, N>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;
// clone_empty_container template function implementation
template<class T, class F>
constexpr auto clone_empty_container(const T& input, const F& f)
{
recursive_invoke_result_t<F, T> output;
return output;
}
// recursive_transform template function implementation (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class T, class F>
requires (unwrap_level <= recursive_depth<T>()) // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
auto output = clone_empty_container(input, f);
if constexpr (is_reservable<decltype(output)>) // reserve space
{
output.reserve(input.size());
}
std::ranges::transform(
input, // passing a range to std::ranges::transform()
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return std::invoke(f, input); // use std::invoke()
}
} | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
/* This overload of recursive_transform is to support std::array
*/
template< std::size_t unwrap_level = 1,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
typename F >
requires std::ranges::input_range<Container<T, N>>
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
Container<recursive_invoke_result_t<F, T>, N> output;
std::ranges::transform( // Use std::ranges::transform() for std::arrays as well
input,
std::begin(output),
[&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
/* Base case of recursive_transform_view template function
https://codereview.stackexchange.com/a/283581/231235
*/
template< typename T,
std::invocable<T> F >
requires (std::copy_constructible<F>)
constexpr auto recursive_transform_view( const T& input, const F& f )
{
return std::invoke( f, input );
}
/* The recursive case of recursive_transform_view template function
https://codereview.stackexchange.com/a/283581/231235
*/
template< template<typename...> typename Container,
std::copy_constructible F,
typename... Ts >
requires (std::ranges::input_range<Container<Ts...>>&&
std::ranges::view<Container<Ts...>>)
constexpr auto recursive_transform_view(const Container<Ts...>& input, const F& f)
{
const auto view = std::ranges::transform_view(
std::ranges::subrange( std::begin(input), std::end(input) ),
[f](const auto& x) constexpr { return recursive_transform_view( x, f ); } );
recursive_invoke_result_t<F, Container<Ts...>> output( view.begin(), view.end() );
// One last sanity check.
if constexpr( is_sized<Container<Ts...>> && is_sized<recursive_invoke_result_t<F, Container<Ts...>>> )
{
assert( output.size() == input.size() );
} | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
return output;
}
/* The recursive case of recursive_transform_view template function for std::array
https://codereview.stackexchange.com/a/283581/231235
*/
template< template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
std::copy_constructible F>
requires std::ranges::input_range<Container<T, N>>
constexpr auto recursive_transform_view(const Container<T, N>& input, const F& f)
{
Container<recursive_invoke_result_t<F, T>, N> output;
std::ranges::transform( // Use std::ranges::transform() for std::arrays
input,
std::begin(output),
[&f](auto&& element){ return recursive_transform_view(element, f); }
);
// One last sanity check.
if constexpr( is_sized<Container<T, N>> && is_sized<recursive_invoke_result_t<F, Container<T, N>>> )
{
assert( output.size() == input.size() );
}
return output;
}
void tests()
{
// non-nested input test, lambda function applied on input directly
std::cout << "non-nested input test, lambda function applied on input directly:\n";
int test_number = 3;
auto recursive_transform_output1 = recursive_transform<0>(test_number, [](auto&& element) { return element + 1; });
std::cout << "recursive_transform function output: \n"
<< recursive_transform_output1 << '\n';
auto recursive_transform_view_output1 = recursive_transform_view(test_number, [](auto&& element) { return element + 1; });
std::cout << "recursive_transform_view function output: \n"
<< recursive_transform_view_output1 << "\n\n";
assert(recursive_transform_output1 == recursive_transform_view_output1); | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
assert(recursive_transform_output1 == recursive_transform_view_output1);
// test with non-nested std::array container
std::cout << "test with non-nested std::array container:\n";
static constexpr std::size_t D = 3;
auto test_array = std::array< double, D >{1, 2, 3};
auto recursive_transform_output2 = recursive_transform<1>(test_array, [](auto&& element) { return element + 1; });
std::cout << "recursive_transform function output: \n";
for(int i = 0; i < recursive_transform_output2.size(); ++i)
{
std::cout << recursive_transform_output2[i] << " ";
}
std::cout << '\n';
// Without specifying unwrap_level, generic lambda (auto&& or auto) cannot be used.
// error: invalid operands to binary expression ('std::array<double, 3>' and 'int')
//auto recursive_transform_view_output2 = recursive_transform_view(test_array, [](auto&& element) { return element + 1; });
auto recursive_transform_view_output2 = recursive_transform_view(test_array, [](int&& element) { return element + 1; });
std::cout << "recursive_transform_view function output: \n";
for(int i = 0; i < recursive_transform_view_output2.size(); ++i)
{
std::cout << recursive_transform_view_output2[i] << " ";
}
std::cout << "\n\n";
// test with nested std::arrays
auto test_nested_array = std::array< decltype(test_array), D >{test_array, test_array, test_array};
//std::cout << "test with nested std::arrays: \n"
// << recursive_transform<2>(test_nested_array, [](auto&& element) { return element + 1; })[0][0] << '\n'; | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "std::vector input test, lambda function applied on input directly:\n";
std::vector<int> test_vector1 = {
1, 2, 3
};
auto recursive_transform_output3 = recursive_transform<0>(test_vector1, [](auto element)
{
element.push_back(4);
element.push_back(5);
return element;
});
std::cout << "recursive_transform function output: \n";
for(int i = 0; i < recursive_transform_output3.size(); ++i)
{
std::cout << recursive_transform_output3[i] << " ";
}
std::cout << '\n';
std::vector<int> test_vector2 = {
1, 2, 3
};
// Error from Clang:
// error: no matching function for call to '__begin'
/*
auto recursive_transform_view_output3 = recursive_transform_view(test_vector2, [](int element)
{
return element;
});
std::cout << "recursive_transform_view function output: \n";
for(int i = 0; i < recursive_transform_view_output3.size(); ++i)
{
std::cout << recursive_transform_view_output3[i] << " ";
}
*/
std::cout << "\n\n";
std::vector<int> test_vector = {
1, 2, 3
};
auto test_priority_queue =
std::priority_queue<int>(std::ranges::begin(test_vector), std::ranges::end(test_vector));
std::cout << "test with std::priority_queue container: \n"
<< recursive_transform<0>(test_priority_queue, [](auto element)
{
element.push(4);
element.push(5);
element.push(6);
return element;
}).top() << '\n'; | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// Convert each int element in std::vector to std::string
// std::vector<int> -> std::vector<std::string>
auto recursive_transform_result = recursive_transform<1>(
test_vector,
[](int x)->std::string { return std::to_string(x); }
); // For testing
std::cout << "std::vector<int> -> std::vector<std::string>: " +
recursive_transform_result.at(0) << '\n'; // recursive_transform_result.at(0) is a std::string
// std::vector<string> -> std::vector<int>
std::cout << "std::vector<string> -> std::vector<int>: "
<< recursive_transform<1>(
recursive_transform_result,
[](std::string x) { return std::atoi(x.c_str()); }).at(0) + 1 << '\n'; // std::string element to int
// std::vector<std::vector<int>> -> std::vector<std::vector<std::string>>
std::vector<decltype(test_vector)> test_nested_vector = {
test_vector, test_vector, test_vector
};
auto recursive_transform_result2 = recursive_transform<2>(
test_nested_vector,
[](int x)->std::string { return std::to_string(x); }
); // For testing
std::cout << "string: " + recursive_transform_result2.at(0).at(0) << '\n'; // recursive_transform_result.at(0).at(0) is also a std::string
// std::deque<int> -> std::deque<std::string>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto recursive_transform_result3 = recursive_transform<1>(
test_deque,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result3.at(0) << '\n'; | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "string: " + recursive_transform_result3.at(0) << '\n';
// std::deque<std::deque<int>> -> std::deque<std::deque<std::string>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto recursive_transform_result4 = recursive_transform<2>(
test_deque2,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result4.at(0).at(0) << '\n';
// std::list<int> -> std::list<std::string>
std::list<int> test_list = { 1, 2, 3, 4 };
auto recursive_transform_result5 = recursive_transform<1>(
test_list,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result5.front() << '\n';
// std::list<std::list<int>> -> std::list<std::list<std::string>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto recursive_transform_result6 = recursive_transform<2>(
test_list2,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result6.front().front() << '\n';
}
int main()
{
tests();
return 0;
}
The output of the test code above:
non-nested input test, lambda function applied on input directly:
recursive_transform function output:
4
recursive_transform_view function output:
4
test with non-nested std::array container:
recursive_transform function output:
2 3 4
recursive_transform_view function output:
2 3 4
std::vector input test, lambda function applied on input directly:
recursive_transform function output:
1 2 3 4 5 | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
test with std::priority_queue container:
6
std::vector<int> -> std::vector<std::string>: 1
std::vector<string> -> std::vector<int>: 2
string: 1
string: 1
string: 1
string: 1
string: 1
Godbolt link
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_transform Template Function with Unwrap Level for std::array Implementation in C++
What changes has been made in the code since last question?
I am trying to implement recursive_transform_view template function and comparing it with recursive_transform template function.
Why a new review is being asked for?
Please review the experimental implementation of recursive_transform_view template function. If there is any misunderstanding, please let me know.
Answer: The name is wrong
Calling this recursive_transform_view() gives the impression that this return a std::ranges::view. However, semantically your function does the same as recursive_transform() from your earlier questions, and this is just an improved version based on Davislor's suggestions. So it should still be named recursive_transform().
If you want to be able to compare a new version of recursive_transform() to an old one in the same program, then consider wrapping them each in their own namespace.
Of course, it might be interesting in itself to create a recursive_transform_view() that does return a view...
Match the requirements of std::ranges::transform_view()
If your code is going to call std::ranges::transform_view(), make sure you add the same requires clauses to your own function. See the code at the end of my answer for an example.
However, you must take into account the recursion. Before Davislor pointed out my mistake, I had included this in the requires clause as well:
&& std::regular_invocable<F&, std::ranges::range_reference_t<Container>> | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
However, that is wrong, since the function F only needs to work at the bottom level of the recursion. You could make the requires clause recurse:
&& std::regular_invocable<F&, std::ranges::range_reference_t<
recursive_invoke_result_t<F, Container>
>>
Although I don't think that will make the error message you would get from passing an incorrect F any better.
You don't need Ts... in the generic recursive case
In the generic recursive case, your have a template template parameter template<typename...> typename Container and a parameter pack typename... Ts. However, you don't need to know anything about the structure of Container in this case, you only need to pass it on to recursive_invoke_result_t<>. So you can just take Container as a regular template parameter:
template< std::ranges::input_range Container,
std::copy_constructible F >
requires (std::ranges::view<Container> &&
std::is_object_v<F>)
constexpr auto recursive_transform_view(const Container& input, const F& f)
{
…
recursive_invoke_result_t<F, Container> output( view.begin(), view.end() );
…
} | {
"domain": "codereview.stackexchange",
"id": 44537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, unit-testing, queue
Title: Blocking Queue Class Unit Test
Question: I would like any feedback on making the unit test for a BlockingQueue class more robust or better? improvements to the coding style, use of the gtest framework, better test cases etc. C++ style suggestions (up to c++ 14). Feel free to add suggestion to improve the BlockingQueue class if you feel inclined to.
BlockingQueue.h
#pragma once
#include <condition_variable>
#include <mutex>
#include <thread>
#include <queue>
#include <string>
#include <iostream>
#include <sstream>
template <typename T>
class BlockingQueue
{
public:
BlockingQueue() = default;
BlockingQueue(BlockingQueue<T>&& blockingQ);
BlockingQueue<T>& operator=(BlockingQueue<T>&& blockingQ);
BlockingQueue(const BlockingQueue<T>&) = delete;
BlockingQueue<T>& operator=(const BlockingQueue<T>&) = delete;
T deQ();
void enQ(const T& t);
T& front();
void clear();
size_t size();
private:
std::queue<T> queue_;
std::mutex mtx_;
std::condition_variable conditionVar_;
};
// Move constructor
template<typename T>
BlockingQueue<T>::BlockingQueue(BlockingQueue<T>&& blockingQ)
{
std::lock_guard<std::mutex> lock(mtx_);
// Here we are moving blockingQ.queue into queue_
queue_ = blockingQ.queue_;
while (blockingQ.queue_.size() > 0)
{
blockingQ.queue_.pop();
}
// can't copy or move mutex or condition variable, so use default members
}
//Move assignment
template<typename T>
BlockingQueue<T>& BlockingQueue<T>::operator=(BlockingQueue<T>&& blockingQ)
{
if (this == &blockingQ)
{
return *this;
}
std::lock_guard<std::mutex> lock(mtx_);
queue_ = blockingQ.queue_;
while (blockingQ.queue_.size() > 0) // clear blockingQ
{
blockingQ.queue_.pop();
}
// can't move assign mutex or condition variable so use target's
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 44538,
"lm_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++, unit-testing, queue",
"url": null
} |
c++, unit-testing, queue
// can't move assign mutex or condition variable so use target's
return *this;
}
// Remove element from front of queue
template<typename T>
T BlockingQueue<T>::deQ()
{
std::unique_lock<std::mutex> lock(mtx_);
// This lock type is required for use with condition variables.
// The operating system needs to lock and unlock the mutex:
// * When wait is called, below, the OS suspends waiting thread and releases lock.
// * When notify is called in enQ() the OS relocks the mutex,
// resumes the waiting thread and sets the condition variable to signaled state.
// std::lock_guard does not have publick lock and unlock functions
if (queue_.size() > 0)
{
T temp = queue_.front();
queue_.pop();
return temp;
}
// may have spurious returns so loop on !condition
conditionVar_.wait(lock, [this]() {return queue_.size() > 0; });
T temp = queue_.front();
queue_.pop();
return temp;
}
// push element onto back of queue
template<typename T>
void BlockingQueue<T>::enQ(const T& t)
{
{
std::unique_lock<std::mutex> lock(mtx_);
queue_.push(t);
}
conditionVar_.notify_one();
}
// Peek at next item to be popped
template <typename T>
T& BlockingQueue<T>::front()
{
std::lock_guard<std::mutex> lock(mtx_);
if (queue_.size() > 0)
{
return queue_.front();
}
throw std::exception("attemp to deQue empty queue");
}
template <typename T>
void BlockingQueue<T>::clear()
{
std::lock_guard<std::mutex> l(mtx_);
while (queue_.size() > 0)
queue_.pop();
}
// return number of elements in queue
template<typename T>
size_t BlockingQueue<T>::size()
{
std::lock_guard<std::mutex> l(mtx_);
return queue_.size();
}
test.cpp
#include "pch.h"
#include "../BlockingQueue/BlockingQueue.h" | {
"domain": "codereview.stackexchange",
"id": 44538,
"lm_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++, unit-testing, queue",
"url": null
} |
c++, unit-testing, queue
test.cpp
#include "pch.h"
#include "../BlockingQueue/BlockingQueue.h"
// This test creates multiple threads that push and pop items from a BlockingQueue
// simultaneously. It tests if the BlockingQueue is thread-safe and can handle race
// conditions correctly.
TEST(BlockingQueueTest, MultipleThreads)
{
BlockingQueue<int> queue;
std::vector<std::thread> threads;
// Create 10 threads that push 100 items to the queue
for (int i = 0; i < 10; ++i)
{
threads.emplace_back([&queue]() {
for (int j = 0; j < 100; ++j)
{
queue.enQ(j);
}
});
}
// Create 10 threads that pop 100 items from the queue
for (int i = 0; i < 10; ++i)
{
threads.emplace_back([&queue]() {
for (int j = 0; j < 100; ++j)
{
queue.deQ();
}
});
}
// Wait for all threads to finish
for (auto& thread : threads)
{
thread.join();
}
// Test if the queue is empty
EXPECT_EQ(queue.size(), 0);
}
// This test creates two threads that push and pop items from a BlockingQueue.
// One thread pops items faster than the other, causing a race condition.
// This test checks if the BlockingQueue can handle this race condition correctly.
TEST(BlockingQueueTest, RaceCondition)
{
BlockingQueue<int> queue;
std::thread popThread([&queue]() {
for (int i = 0; i < 1000; ++i)
{
queue.deQ();
// Add a sleep to simulate a slower consumer
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
});
// Push 1000 items to the queue
for (int i = 0; i < 1000; ++i)
{
queue.enQ(i);
}
// Wait for the pop thread to finish
popThread.join();
// Test if the queue is empty
EXPECT_EQ(queue.size(), 0);
} | {
"domain": "codereview.stackexchange",
"id": 44538,
"lm_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++, unit-testing, queue",
"url": null
} |
c++, unit-testing, queue
// Test if the queue is empty
EXPECT_EQ(queue.size(), 0);
}
Answer: Use std::swap() to move construct/assign
I see you repeated the code to clear a queue in many places. However, the destructor of BlockingQueue should already take care of properly clearing itself. So in the move constructor and move assignment operator, I recommend you just use std::swap() to swap the queue member variables:
template<typename T>
BlockingQueue<T>::BlockingQueue(BlockingQueue<T>&& other)
{
std::swap(queue_, other.queue_);
}
template<typename T>
BlockingQueue<T>& BlockingQueue<T>::operator=(BlockingQueue<T>&& other)
{
std::lock_guard<std::mutex> lock(mtx_);
std::swap(queue_, other.queue_);
return *this;
}
std::swap() will handle the case where this == &other correctly. Your class has an implicitly generated destructor that will in turn destroy all items in queue_ correctly.
No need to take the lock in a constructor
You don't need to lock mtx_ in the constructor itself. Nothing can possibly use the object before the constructor returns after all.
Avoid repeating code unnecessarily
In deQ() you wrote code to pop an item twice, once before the call to wait() and once after. However, you don't need to do it twice. If you use wait() with a predicate, it will check the predicate before doing a wait, so you don't have to do that yourself. So you can just write:
template<typename T>
T BlockingQueue<T>::deQ()
{
std::unique_lock<std::mutex> lock(mtx_);
conditionVar_.wait(lock, [this]() { return !queue_.empty(); });
T temp = std::move(queue_.front());
queue_.pop();
return temp;
} | {
"domain": "codereview.stackexchange",
"id": 44538,
"lm_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++, unit-testing, queue",
"url": null
} |
c++, unit-testing, queue
std::move() items out of the queue
As shown above, you should use std::move() when taking an item out of the queue, as this might result in more optimal code being generated. Also think about T being possibly non-copyable.
Allow items to be moved or emplaced in the queue
Your enQ() takes an item by const reference. That works, but requires a copy to be made when adding it to queue_. Consider adding overloads that takes an r-value reference, so the item can be moved into the queue_. It might also make sense to add a version that works like emplace(). Again, this allows more optimal code to be generated, and allows non-copyable types to be used.
It's not thread-safe
Your front() returns a reference to an element in queue_. However, by the time front() returns, another thread might have called deQ() and caused that reference to not be valid anymore.
Calling size() in itself will not cause any issues, but by the time it returns, the size of the queue might already be different. So any code relying on the return value of size() is asking for trouble. It's best to remove this function.
You could state that your code only allows two threads at a time, one producer thread that only ever adds items to the queue, and another one that only ever looks at items or removes them. In that case, front() and size() might make sense. However, I recommend that you avoid this and make it safe for an arbitrary number of producer/consumer threads. This will result in less surprises. Also, the test cases suggest that it should handle many simultaneous producers and consumers.
Try to use the same naming convention as the standard library
For a programmer who is already used to the standard library, it would be much nicer if your class uses the same exact terminology, so they don't have to learn that your class uses enQ() instead of push() or emplace(). Even better, if you have the same interface as the standard library, some STL algorithms may also work on your queue. | {
"domain": "codereview.stackexchange",
"id": 44538,
"lm_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++, unit-testing, queue",
"url": null
} |
c++, unit-testing, queue
Testing for race conditions
It's is really hard to test for race conditions. By their very nature, they only trigger in rare conditions. There is no guarantee that your tests will hit a race condition, so the fact that they pass cannot be used to say that your code is race-free. Even if a race condition is triggered, it might not result in an exception or a crash.
There's this comment:
// One thread pops items faster than the other, causing a race condition. | {
"domain": "codereview.stackexchange",
"id": 44538,
"lm_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++, unit-testing, queue",
"url": null
} |
c++, unit-testing, queue
It's actually the thread that pushes that runs faster. But even if the thread popping would run faster, then your code should still run fine and never hit a race condition; after all, pop() will block until a new element is available.
Writing proper tests
Your test cases don't really test much. The only EXPECT I see is that the queue is empty after all threads finish. But what about the values that deQ() returns? It could always return zeroes for all you know, and the test just passes.
Make sure you test all the properties that a queue has: what goes in comes out. Maybe there is also some ordering guarantee you want to preserve: if you enqueue values in ascending order, a single thread calling deQ() multiple times will also only ever see ascending results.
Make sure you test all member functions, constructors, assignment operators and so on. Also test queues of various types: does it handle std::strings? Does it handle non-copyable types? | {
"domain": "codereview.stackexchange",
"id": 44538,
"lm_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++, unit-testing, queue",
"url": null
} |
python, python-3.x, algorithm
Title: Find the shortest distance between two letters
Question: I've been tasked with finding the distance between two letters in the alphabet. Below is my solution. My main concerns are if there is any shorter way to do this, and if there are any edge cases I'm not. Thanks!
import string
LETTERS = string.ascii_lowercase
def shortest_distance_between_letters(a: str, b: str) -> int:
"""
Returns the shortest distance between letters. This include wrapping
around the letters. See below examples for clarification.
>>> call('a', 'c')
2 # 'a' -> 'b' -> 'c'
>>> call('b', 'x')
4 # 'b' -> 'a' -> 'z' -> 'y' -> 'x'
"""
if a == b:
return 0
first = a if ord(a) < ord(b) else b
second = b if ord(b) > ord(a) else a
return min(
LETTERS.index(second) - LETTERS.index(first),
(len(LETTERS) - LETTERS.index(second)) + LETTERS.index(first)
)
Answer: You don't need list.index(). Just compute the difference between the two
ord() values.
You don't need to worry about first or second. Just find
the absolute difference and then do some arithmetic to handle the
wrap-around.
Next steps: handle invalid inputs. Depending on your use case
you might want to raise a ValueError if the inputs are not in
LETTERS. If you do this, don't rely on assert, for
reasons detailed here.
import string
LETTERS = string.ascii_lowercase
N_LETTERS = len(LETTERS)
def shortest_distance_between_letters(a, b):
diff = abs(ord(a) - ord(b))
return min(diff, N_LETTERS - diff) | {
"domain": "codereview.stackexchange",
"id": 44539,
"lm_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, algorithm",
"url": null
} |
java, algorithm, traveling-salesman
Title: Greedy approximate algorithm for metric TSP in Java
Question: I have a repository that provides three metric TSP solvers:
Brute-force solver,
Genetic solver,
Greedy approximate solver;
solver 3 is the subject matter of this post.
The typical output is:
GA duration : 1318 ms.
Brute-force duration: 4212 ms.
Greedy duration: 1 ms.
---
GA cost : 1430.365851513996
Approximate cost: 1359.474067059351
Brute-force cost: 1216.4965904321161
Cost ratio GA/BF: 1.1758075302175
Cost ratio Approx./BF: 1.1175321638809093
And the tours look like this:
package com.github.coderodde.tsp.impl;
import com.github.coderodde.tsp.AllPairsShortestPathData;
import com.github.coderodde.tsp.Node;
import com.github.coderodde.tsp.TSPSolver;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* This class implements a greedy approximate algorithm for solving TSP. First,
* it selects a shortest edge in the graph and adds it to the tentative tour.
* Then, it repeatedly selects the closest node to some of the tour's end
* points, and continues so until the tour becomes complete.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Mar 8, 2023)
* @see 1.6 (Mar 8, 2023)
*/
public final class ApproximateTSPSolver implements TSPSolver { | {
"domain": "codereview.stackexchange",
"id": 44540,
"lm_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, algorithm, traveling-salesman",
"url": null
} |
java, algorithm, traveling-salesman
private static final class Pair<F, S> {
F first;
S second;
Pair(F first, S second) {
this.first = first;
this.second = second;
}
}
private static final int MINIMUM_GRAPH_SIZE = 3;
@Override
public Solution findTSPSolution(Node seedNode) {
Objects.requireNonNull(seedNode, "The seed node is null.");
List<Node> reachableNodes =
GraphExpander.computeReachableNodesFrom(seedNode);
checkGraphSize(reachableNodes.size());
AllPairsShortestPathData allPairsData =
AllPairsShortestPathSolver.solve(reachableNodes);
Deque<Node> tentativeTour = new ArrayDeque<>();
Pair<Node, Node> initialEdge = getInitialEdge(reachableNodes,
allPairsData);
tentativeTour.addLast(initialEdge.first);
tentativeTour.addLast(initialEdge.second);
Set<Node> visitedSet = new HashSet<>();
visitedSet.add(initialEdge.first);
visitedSet.add(initialEdge.second);
while (tentativeTour.size() < reachableNodes.size()) {
Node head = tentativeTour.getFirst();
Node tail = tentativeTour.getLast();
Node nearestToHead = getNearestNeighborOf(head,
visitedSet,
reachableNodes,
allPairsData);
Node nearestToTail = getNearestNeighborOf(tail,
visitedSet,
reachableNodes,
allPairsData);
if (allPairsData.getShortestPathCost(head, nearestToHead) < | {
"domain": "codereview.stackexchange",
"id": 44540,
"lm_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, algorithm, traveling-salesman",
"url": null
} |
java, algorithm, traveling-salesman
if (allPairsData.getShortestPathCost(head, nearestToHead) <
allPairsData.getShortestPathCost(tail, nearestToTail)) {
tentativeTour.addFirst(nearestToHead);
visitedSet.add(nearestToHead);
} else {
tentativeTour.addLast(nearestToTail);
visitedSet.add(nearestToTail);
}
}
return new Solution(
tentativeTourToResultTour(tentativeTour),
allPairsData);
}
private static Node
getNearestNeighborOf(
Node node,
Set<Node> visitedSet,
List<Node> graphNodes,
AllPairsShortestPathData allPairsData) {
double tentativeCost = Double.POSITIVE_INFINITY;
Node nearestNeighbor = null;
for (Node neighbor : graphNodes) {
if (visitedSet.contains(neighbor)) {
continue;
}
double cost =
allPairsData.getShortestPathCost(
node,
neighbor); | {
"domain": "codereview.stackexchange",
"id": 44540,
"lm_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, algorithm, traveling-salesman",
"url": null
} |
java, algorithm, traveling-salesman
if (tentativeCost > cost) {
tentativeCost = cost;
nearestNeighbor = neighbor;
}
}
return nearestNeighbor;
}
private static Pair<Node, Node>
getInitialEdge(List<Node> reachableNodes,
AllPairsShortestPathData allPairsData) {
double tentativeCost = Double.POSITIVE_INFINITY;
Node tentativeNode1 = null;
Node tentativeNode2 = null;
for (Node node : reachableNodes) {
for (Node neighbor : node.getNeighbors()) {
if (neighbor.equals(node)) {
continue;
}
double cost =
allPairsData.getShortestPathCost(
node,
neighbor);
if (tentativeCost > cost) {
tentativeCost = cost;
tentativeNode1 = node;
tentativeNode2 = neighbor;
}
}
}
return new Pair<>(tentativeNode1, tentativeNode2);
}
private static List<Node> tentativeTourToResultTour(Deque<Node> nodeDeque) {
return new ArrayList<>(nodeDeque);
}
private static void checkGraphSize(int numberOfNodes) {
if (numberOfNodes < MINIMUM_GRAPH_SIZE) {
throw new IllegalArgumentException(
"Too little graph nodes: "
+ numberOfNodes
+ ". Must be at least "
+ MINIMUM_GRAPH_SIZE
+ ".");
}
}
}
Critique request
So how am I doing here? Any ideas are much welcomed.
Answer: private static final int MINIMUM_GRAPH_SIZE = 3; | {
"domain": "codereview.stackexchange",
"id": 44540,
"lm_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, algorithm, traveling-salesman",
"url": null
} |
java, algorithm, traveling-salesman
Answer: private static final int MINIMUM_GRAPH_SIZE = 3;
Maybe this, and some checking code,
should be evicted to a common class used by all three TSP variants?
Also the check could produce a more diagnostic message,
for the case where caller offers three nodes with zero edges.
private static final class Pair<F, S> {
Same argument.
Or if you're willing to depend on e.g. javafx or apache commons,
there's lots of definitions for this trivial struct.
This declaration is clear
Pair<Node, Node> initialEdge
but I'm sad that it isn't Edge initialEdge.
I am accustomed to TSP being formulated on an undirected graph.
I eventually noticed that this code tackles the harder problem
of finding a tour on a digraph.
Some input digraphs will happen to have symmetric edges,
which this class will eventually discover.
I wonder if that costs us cycles?
Also, checkGraphSize will accept the graph A -> B -> C,
neglecting to report that it lacks a C -> A edge.
I feel stricter error checking is warranted.
If caller passes in N nodes, we should find exactly N nodes reachable.
And we shouldn't permit any node to have out-degree of zero. | {
"domain": "codereview.stackexchange",
"id": 44540,
"lm_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, algorithm, traveling-salesman",
"url": null
} |
java, algorithm, traveling-salesman
Wow, AllPairsShortestPathSolver.solve() looks expensive.
And I don't mean the extra factor of 2 due to directed edges.
There's a bunch of hashmap lookups, and each of them is "fast",
I suppose, happening in O(1) time.
But they're not cache friendly,
something that is especially relevant for solve(),
given the quadratic size.
In python land everything tends to involve chasing an object pointer, also,
which explains the popularity of the numpy library.
You can put a bunch of float objects in a container,
but they will be more rapidly scanned if we put them
in a contiguously allocated vector of floats.
Why? Because we're not stalled on a random read
for pointer dereference, and because the hardware
notices sequential scans and has already populated
the cache line with the adjacent floats you're
going to need a moment from now.
If you do choose to implement solve()
with an array, use the smallest bits-per-entry
you can get away with, so a cache line will
accommodate more entries.
I wish getInitialEdge explained that it finds
the minimum edge weight and returns one of those edges.
Its contract
seems to suggest it's free to choose any arbitrary edge.
So the quadratic cost surprised me.
getNearestNeighborOf is a nice name, but maybe rename it to
getNearestUnvisitedNeighborOf ?
Or explain that in a comment.
Could we maybe reduce its cost from O(N) to O(log N)
by sorting the all-pairs data? | {
"domain": "codereview.stackexchange",
"id": 44540,
"lm_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, algorithm, traveling-salesman",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Title: A recursive_transform_view Template Function which returns a view in C++
Question: This is a follow-up question for A recursive_transform_view Template Function Implementation. Following the suggestions mentioned in G. Sliepen's answer:
Of course, it might be interesting in itself to create a recursive_transform_view() that does return a view...
I am trying to update recursive_transform_view template function implementation which the return object is a view in this post. On the other hand, there are several updates:
To compare the different implementations in a better way, the version with unwrap_level template parameter is implemented in UL namespace and the other one without unwrap_level template parameter is implemented in NonUL namespace
Considering the constraint of using std::invoke, std::regular_invocable concept is used and recursive_invoke_result struct is also revised.
The experimental implementation
recursive_transform_view template function implementation:
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>&&
std::regular_invocable<F&, std::ranges::range_reference_t<
recursive_invoke_result_t<F, Container>
>>)
constexpr auto recursive_transform_view(const Container& input, const F& f)
{
return std::ranges::transform_view(
std::ranges::subrange( std::span{input} ),
[&f](const auto&& element) constexpr { return recursive_transform(element, f ); } );
} | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
The revised version of clone_empty_container template function implementation:
// clone_empty_container template function implementation
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>&&
std::regular_invocable<F&, std::ranges::range_reference_t<
recursive_invoke_result_t<F, Container>
>>)
constexpr auto clone_empty_container(const Container& input, const F& f)
{
const auto view = recursive_transform_view(input, f);
recursive_invoke_result_t<F, Container> output(std::ranges::begin(view), std::ranges::end(view));
return output;
}
Full Testing Code
The full testing code:
// A recursive_transform_view Template Function which returns a view in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <cstdlib>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <queue>
#include <ranges>
#include <span>
#include <stack>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
// is_reservable concept
template<class T>
concept is_reservable = requires(T input)
{
input.reserve(1);
};
// is_sized concept, https://codereview.stackexchange.com/a/283581/231235
template<class T>
concept is_sized = requires(T x)
{
std::size(x);
};
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return 0;
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + 1;
} | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_invoke_result_t implementation
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::regular_invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::regular_invocable<F, Container<Ts...>>&& // F cannot be invoked to Container<Ts...> directly
std::ranges::input_range<Container<Ts...>>&&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<
typename recursive_invoke_result<
F,
std::ranges::range_value_t<Container<Ts...>>
>::type
>;
};
template<template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
std::regular_invocable<Container<T, N>> F>
struct recursive_invoke_result<F, Container<T, N>>
{
using type = std::invoke_result_t<F, Container<T, N>>;
};
template<template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
typename F>
requires (
!std::regular_invocable<F, Container<T, N>>&& // F cannot be invoked to Container<Ts...> directly
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<T, N>>>::type; })
struct recursive_invoke_result<F, Container<T, N>>
{
using type = Container<
typename recursive_invoke_result<
F,
std::ranges::range_value_t<Container<T, N>>
>::type
, N>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type; | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// https://codereview.stackexchange.com/a/253039/231235
template<template<class...> class Container = std::vector, std::size_t dim, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times));
}
}
namespace UL // unwrap_level
{
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>&&
std::regular_invocable<F&, std::ranges::range_reference_t<
recursive_invoke_result_t<F, Container>
>>)
constexpr auto recursive_transform_view(const Container& input, const F& f)
{
return std::ranges::transform_view(
std::ranges::subrange( std::span{input} ),
[&f](const auto&& element) constexpr { return recursive_transform(element, f ); } );
} | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// clone_empty_container template function implementation
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>&&
std::regular_invocable<F&, std::ranges::range_reference_t<
recursive_invoke_result_t<F, Container>
>>)
constexpr auto clone_empty_container(const Container& input, const F& f)
{
const auto view = recursive_transform_view(input, f);
recursive_invoke_result_t<F, Container> output(std::ranges::begin(view), std::ranges::end(view));
return output;
}
// recursive_transform template function implementation (the version with unwrap_level template parameter)
template<std::size_t unwrap_level = 1, class T, class F>
requires (unwrap_level <= recursive_depth<T>()) // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
auto output = clone_empty_container(input, f);
if constexpr (is_reservable<decltype(output)>&&
is_sized<decltype(input)>)
{
output.reserve(input.size());
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
}
else
{
std::ranges::transform(
input,
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
);
}
return output;
}
else if constexpr(std::regular_invocable<F, T>)
{
return std::invoke(f, input);
}
else
{
static_assert(!std::regular_invocable<F, T>, "Uninvocable?");
}
} | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
/* This overload of recursive_transform is to support std::array
*/
template< std::size_t unwrap_level = 1,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
typename F >
requires (std::ranges::input_range<Container<T, N>>)
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
Container<recursive_invoke_result_t<F, T>, N> output;
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
}
namespace NonUL
{
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>&&
std::regular_invocable<F&, std::ranges::range_reference_t<
recursive_invoke_result_t<F, Container>
>>)
constexpr auto recursive_transform_view(const Container& input, const F& f)
{
return std::ranges::transform_view(
std::ranges::subrange( std::span{input} ),
[&f](const auto&& element) constexpr { return recursive_transform(element, f ); } );
}
/* Base case of NonUL::recursive_transform template function
https://codereview.stackexchange.com/a/283581/231235
*/
template< typename T,
std::regular_invocable<T> F>
requires (std::copy_constructible<F>)
constexpr auto recursive_transform( const T& input, const F& f )
{
return std::invoke( f, input );
} | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
/* The recursive case of NonUL::recursive_transform template function
https://codereview.stackexchange.com/a/283581/231235
*/
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>&&
std::regular_invocable<F&, std::ranges::range_reference_t<
recursive_invoke_result_t<F, Container>
>>)
constexpr auto recursive_transform(const Container& input, const F& f)
{
const auto view = recursive_transform_view(input, f);
recursive_invoke_result_t<F, Container> output( std::ranges::begin(view), std::ranges::end(view) );
// One last sanity check.
if constexpr( is_sized<Container> && is_sized<recursive_invoke_result_t<F, Container>> )
{
assert( output.size() == input.size() );
}
return output;
}
/* The recursive case of NonUL::recursive_transform template function for std::array
https://codereview.stackexchange.com/a/283581/231235
*/
template< template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
std::copy_constructible F>
requires std::ranges::input_range<Container<T, N>>
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
Container<recursive_invoke_result_t<F, T>, N> output;
std::ranges::transform( // Use std::ranges::transform() for std::arrays
input,
std::ranges::begin(output),
[&f](auto&& element){ return recursive_transform(element, f); }
);
// One last sanity check.
if constexpr( is_sized<Container<T, N>> && is_sized<recursive_invoke_result_t<F, Container<T, N>>> )
{
assert( output.size() == input.size() );
} | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
return output;
}
}
void tests()
{
// non-nested input test, lambda function applied on input directly
std::cout << "non-nested input test, lambda function applied on input directly:\n";
int test_number = 3;
auto ul_recursive_transform_output1 = UL::recursive_transform<0>(test_number, [](auto&& element) { return element + 1; });
std::cout << "UL::recursive_transform function output: \n"
<< ul_recursive_transform_output1 << '\n';
auto nonul_recursive_transform_output1 = NonUL::recursive_transform(test_number, [](auto&& element) { return element + 1; });
std::cout << "NonUL::recursive_transform function output: \n"
<< nonul_recursive_transform_output1 << "\n\n";
assert(ul_recursive_transform_output1 == nonul_recursive_transform_output1);
// test with non-nested std::array container
std::cout << "test with non-nested std::array container:\n";
static constexpr std::size_t D = 3;
auto test_array = std::array< double, D >{1, 2, 3};
auto ul_recursive_transform_output2 = UL::recursive_transform<1>(test_array, [](auto&& element) { return element + 1; });
std::cout << "UL::recursive_transform function output: \n";
for(int i = 0; i < ul_recursive_transform_output2.size(); ++i)
{
std::cout << ul_recursive_transform_output2[i] << " ";
}
std::cout << '\n'; | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// Without specifying unwrap_level, generic lambda (auto&& or auto) cannot be used.
// error: invalid operands to binary expression ('std::array<double, 3>' and 'int')
//auto nonul_recursive_transform_output2 = NonUL::recursive_transform(test_array, [](auto&& element) { return element + 1; });
auto nonul_recursive_transform_output2 = NonUL::recursive_transform(test_array, [](int&& element) { return element + 1; });
std::cout << "NonUL::recursive_transform function output: \n";
for(int i = 0; i < nonul_recursive_transform_output2.size(); ++i)
{
std::cout << nonul_recursive_transform_output2[i] << " ";
}
std::cout << "\n\n";
// TODO: test with nested std::arrays
auto test_nested_array = std::array< decltype(test_array), D >{test_array, test_array, test_array};
//std::cout << "test with nested std::arrays: \n"
// << UL::recursive_transform<2>(test_nested_array, [](auto&& element) { return element + 1; })[0][0] << '\n';
std::cout << "std::vector input test, lambda function applied on input directly:\n";
std::vector<int> test_vector1 = {
1, 2, 3
};
auto ul_recursive_transform_output3 = UL::recursive_transform<0>(test_vector1, [](auto element)
{
element.push_back(4);
element.push_back(5);
return element;
});
std::cout << "UL::recursive_transform function output: \n";
for(int i = 0; i < ul_recursive_transform_output3.size(); ++i)
{
std::cout << ul_recursive_transform_output3[i] << " ";
}
std::cout << '\n'; | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::vector<int> test_vector2 = {
1, 2, 3
};
// [A Issue to Be Addressed] Error from Clang:
// error: no matching function for call to '__begin'
/*
auto nonul_recursive_transform_output3 = NonUL::recursive_transform(test_vector2, [](int element)
{
return element;
});
std::cout << "NonUL::recursive_transform function output: \n";
for(int i = 0; i < nonul_recursive_transform_output3.size(); ++i)
{
std::cout << nonul_recursive_transform_output3[i] << " ";
}
*/
std::cout << "\n\n";
std::vector<int> test_vector = {
1, 2, 3
};
auto test_priority_queue =
std::priority_queue<int>(std::ranges::begin(test_vector), std::ranges::end(test_vector));
std::cout << "test with std::priority_queue container: \n"
<< UL::recursive_transform<0>(test_priority_queue, [](auto element)
{
element.push(4);
element.push(5);
element.push(6);
return element;
}).top() << '\n';
}
int main()
{
tests();
return 0;
}
The output of the test code above:
non-nested input test, lambda function applied on input directly:
UL::recursive_transform function output:
4
NonUL::recursive_transform function output:
4
test with non-nested std::array container:
UL::recursive_transform function output:
2 3 4
NonUL::recursive_transform function output:
2 3 4
std::vector input test, lambda function applied on input directly:
UL::recursive_transform function output:
1 2 3 4 5
test with std::priority_queue container:
6
Godbolt link
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_transform_view Template Function Implementation | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Which question it is a follow-up to?
A recursive_transform_view Template Function Implementation
What changes has been made in the code since last question?
I am trying to update recursive_transform_view template function implementation which the return object is a view in this post.
Why a new review is being asked for?
Please review the revised experimental implementation of recursive_transform_view template function with using std::span and std::ranges::subrange. | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Answer: Do I Contradict Myself?
Very well, then I contradict myself. Since you asked specifically about the use of std::ranges::subrange versus std::span, and you based that on some code I had previously written, I’ll bring up something you made me realize and edit into my answer here, I will repeat one thing I said there.
You don’t actually need either one. You are already constraining the container type to be a std::ranges::input_range, a great idea that I hadn’t thought of, and which is much better than reinventing the wheel like I originally did. It also means you can pass the input argument directly as the first argument to std::ranges::transform_view, since it meets the requirements. There is no need to convert it to any other type. (You still need to compile with Clang Trunk on Godbolt. Versions up to Clang 15.0.0, GCC 12.2 or ICX 2022 do not work.)
However
Returning a non-owning view of a temporary object will result in a dangling reference!
So what you really want to do is create the transformed container, and construct a view of that.
To Prevent this Happening by Accident
If you have a function that constructs a view object of a container, best practice is to add an overload for an expiring input reference, and have that overload return std::ranges::dangling. This will help a programmer catch this logic error.
/* Normally, this would construct some kind of view object from the
* input range. What type is not important here.
*/
template <std::ranges::input_range T>
constexpr auto make_view(const T&) noexcept;
/* Override make_view to catch dangling references. A borrowed range is
* safe from dangling..
*/
template <std::ranges::input_range T>
requires (!std::ranges::borrowed_range<T>)
constexpr std::ranges::dangling make_view(T&&) noexcept
{
return std::ranges::dangling();
} | {
"domain": "codereview.stackexchange",
"id": 44541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
python
Title: Reduce a list by filtering out repeated elements
Question: I want to reduce a list to its sequence. Or I could say I want to remove duplicate neighbors in a list.
This Python code does what I want.
#!/usr/bin/env python3
data = [True, False, False, False, False, True, True]
expected = [True, False, True]
result = []
for d in data:
try:
if result[-1] != d:
result.append(d)
except IndexError:
# Happens in first iteration
result.append(d)
print(result)
Here is a second approach with less lines:
#!/usr/bin/env python3
data = [True, False, False, False, False, True, True]
expected = [True, False, True]
result = [data[0]]
for d in data[1:]:
if result[-1] != d:
result.append(d)
print(result)
But I assume there is a better and more pythonic way.
EDIT: Of course this code should go into a function. But this is not the core of the question here.
Answer: The two programs are pretty similar, just that the first skips data[0] by catching an exception, whilst the second does it by slicing it off the input.
In both cases, we have inlined the logic directly into the program; I think it would be better to create a function and give it a good name - perhaps uniq, based on the standard command that does a similar thing with lines of input. Writing a function also gives us somewhere to document its behaviour and (using doctest) to provide some simple unit tests.
When I want to transform a sequence, I turn first to itertools. In this case, I find it has a convenient groupby function that's pretty much what we want (it even mentions that it's similar to uniq). So all we have to do is to take the key element from each tuple returned by itertools.groupby(data):
import itertools | {
"domain": "codereview.stackexchange",
"id": 44542,
"lm_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",
"url": null
} |
python
def uniq(sequence):
'''
Replace any repeated elements in "sequence" with a single element.
Examples:
>>> uniq([])
[]
>>> uniq([True, False, False, False, False, True, True])
[True, False, True]
'''
return [k for k,g in itertools.groupby(sequence)]
This can be tested in the usual way:
if __name__ == '__main__':
import doctest
doctest.testmod() | {
"domain": "codereview.stackexchange",
"id": 44542,
"lm_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",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.