text
stringlengths
1
2.12k
source
dict
c, array, memory-management | | (9) following ‘true’ branch (when ‘i < rows’)... | | (11) following ‘false’ branch (when ‘i >= rows’)... | 22 | array->data[i] = (double *) malloc(cols * sizeof(double)); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (7) ...to here | | (8) region created on heap here | | (10) ...to here |...... | 25 | return array; | | ~~~~~ | | | | | (12) ...to here | <------+ | ‘main’: events 13-14 | | 55 | struct Array *M = NewArray(2, 4); | | ^~~~~~~~~~~~~~ | | | | | (13) returning to ‘main’ from ‘NewArray’ | 56 | PrintArray(M); | | ~~~~~~~~~~~~~ | | | | | (14) calling ‘PrintArray’ from ‘main’ | +--> ‘PrintArray’: events 15-20 | | 42 | void PrintArray(const struct Array *array) { | | ^~~~~~~~~~ | | | | | (15) entry to ‘PrintArray’ | 43 | for (int i=0; i<array->rows; ++i) { | | ~~~~~~~~~~~~~ | | | | | (16) following ‘true’ branch... | 44 | for (int j=0; j<array->cols; ++j) { | | ~ ~~~~~~~~~~~~~ | | | | | | | (18) following ‘true’ branch... | | (17) ...to here
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management | | (17) ...to here | 45 | printf("%.2lf ", array->data[i][j]); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | | | (19) ...to here | | (20) use of uninitialized value ‘*_5 + _7’ here | 281916.c:45:13: warning: use of uninitialized value ‘*_5 + _7’ [CWE-457] [-Wanalyzer-use-of-uninitialized-value] 45 | printf("%.2lf ", array->data[i][j]); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ‘main’: events 1-2 | | 52 | int main(){ | | ^~~~ | | | | | (1) entry to ‘main’ |...... | 55 | struct Array *M = NewArray(2, 4); | | ~~~~~~~~~~~~~~ | | | | | (2) calling ‘NewArray’ from ‘main’ | +--> ‘NewArray’: events 3-12 | | 11 | struct Array *NewArray(const size_t rows, const size_t cols){ | | ^~~~~~~~ | | | | | (3) entry to ‘NewArray’ | 12 | if (rows <= 0 || cols <= 0){ | | ~ | | | | | (4) following ‘false’ branch... |...... | 15 | struct Array *array = (struct Array *)malloc(sizeof(struct Array *)); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (5) ...to here |...... | 21 | for (size_t i = 0; i < rows; ++i) { | | ~~~~~~~~ | | |
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management | | ~~~~~~~~ | | | | | (6) following ‘true’ branch (when ‘i < rows’)... | | (9) following ‘true’ branch (when ‘i < rows’)... | | (11) following ‘false’ branch (when ‘i >= rows’)... | 22 | array->data[i] = (double *) malloc(cols * sizeof(double)); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (7) ...to here | | (8) region created on heap here | | (10) ...to here |...... | 25 | return array; | | ~~~~~ | | | | | (12) ...to here | <------+ | ‘main’: events 13-14 | | 55 | struct Array *M = NewArray(2, 4); | | ^~~~~~~~~~~~~~ | | | | | (13) returning to ‘main’ from ‘NewArray’ | 56 | PrintArray(M); | | ~~~~~~~~~~~~~ | | | | | (14) calling ‘PrintArray’ from ‘main’ | +--> ‘PrintArray’: events 15-22 | | 42 | void PrintArray(const struct Array *array) { | | ^~~~~~~~~~ | | | | | (15) entry to ‘PrintArray’ | 43 | for (int i=0; i<array->rows; ++i) { | | ~~~~~~~~~~~~~ | | | | | (16) following ‘true’ branch... | 44 | for (int j=0; j<array->cols; ++j) {
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management | 44 | for (int j=0; j<array->cols; ++j) { | | ~ ~~~~~~~~~~~~~ | | | | | | | (18) following ‘true’ branch... | | | (20) following ‘true’ branch... | | (17) ...to here | 45 | printf("%.2lf ", array->data[i][j]); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | | | (19) ...to here | | | (21) ...to here | | (22) use of uninitialized value ‘*_5 + _7’ here | make[2]: Leaving directory '/home/tms/stackexchange/review' valgrind --leak-check=full ./281916 ==4108801== Memcheck, a memory error detector ==4108801== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al. ==4108801== Using Valgrind-3.19.0 and LibVEX; rerun with -h for copyright info ==4108801== Command: ./281916 ==4108801== ==4108801== Invalid write of size 8 ==4108801== at 0x1091B8: NewArray (281916.c:17) ==4108801== by 0x10939B: main (281916.c:55) ==4108801== Address 0x4a5a048 is 0 bytes after a block of size 8 alloc'd ==4108801== at 0x48407B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==4108801== by 0x1091AB: NewArray (281916.c:15) ==4108801== by 0x10939B: main (281916.c:55) ==4108801== ==4108801== Invalid write of size 8 ==4108801== at 0x1091C4: NewArray (281916.c:18) ==4108801== by 0x10939B: main (281916.c:55) ==4108801== Address 0x4a5a050 is 8 bytes after a block of size 8 alloc'd ==4108801== at 0x48407B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==4108801== by 0x1091AB: NewArray (281916.c:15) ==4108801== by 0x10939B: main (281916.c:55) ==4108801== ==4108801== Invalid read of size 8
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management ==4108801== by 0x10939B: main (281916.c:55) ==4108801== ==4108801== Invalid read of size 8 ==4108801== at 0x109365: PrintArray (281916.c:43) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== Address 0x4a5a048 is 0 bytes after a block of size 8 alloc'd ==4108801== at 0x48407B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==4108801== by 0x1091AB: NewArray (281916.c:15) ==4108801== by 0x10939B: main (281916.c:55) ==4108801== ==4108801== Invalid read of size 8 ==4108801== at 0x109344: PrintArray (281916.c:44) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== Address 0x4a5a050 is 8 bytes after a block of size 8 alloc'd ==4108801== at 0x48407B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==4108801== by 0x1091AB: NewArray (281916.c:15) ==4108801== by 0x10939B: main (281916.c:55) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C8FC8: __printf_fp_l (printf_fp.c:396) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C8FE2: __printf_fp_l (printf_fp.c:396) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C4112: __mpn_extract_double (dbl2mpn.c:56) ==4108801== by 0x48C958E: __printf_fp_l (printf_fp.c:396)
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management ==4108801== by 0x48C958E: __printf_fp_l (printf_fp.c:396) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C4117: __mpn_extract_double (dbl2mpn.c:60) ==4108801== by 0x48C958E: __printf_fp_l (printf_fp.c:396) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C9897: __printf_fp_l (printf_fp.c:978) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C98D5: __printf_fp_l (printf_fp.c:981) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48CAA78: __printf_fp_l (printf_fp.c:991) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354)
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C9926: round_away (rounding-mode.h:52) ==4108801== by 0x48C9926: __printf_fp_l (printf_fp.c:998) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C9B94: __printf_fp_l (printf_fp.c:1166) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C9F7E: __printf_fp_l (printf_fp.c:1228) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48C9F63: __printf_fp_l (printf_fp.c:1230) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061)
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48F81D9: _IO_file_overflow@@GLIBC_2.2.5 (fileops.c:782) ==4108801== by 0x48CA047: __printf_fp_l (printf_fp.c:1254) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48D39E4: __vfprintf_internal (vfprintf-internal.c:1062) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48D39F4: done_add_func (vfprintf-internal.c:127) ==4108801== by 0x48D39F4: __vfprintf_internal (vfprintf-internal.c:1067) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48D39FC: __vfprintf_internal (vfprintf-internal.c:1067) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48D2897: done_add_func (vfprintf-internal.c:127) ==4108801== by 0x48D2897: outstring_func (vfprintf-internal.c:241)
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management ==4108801== by 0x48D2897: outstring_func (vfprintf-internal.c:241) ==4108801== by 0x48D2897: __vfprintf_internal (vfprintf-internal.c:1096) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48D28B0: done_add_func (vfprintf-internal.c:127) ==4108801== by 0x48D28B0: outstring_func (vfprintf-internal.c:241) ==4108801== by 0x48D28B0: __vfprintf_internal (vfprintf-internal.c:1096) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Conditional jump or move depends on uninitialised value(s) ==4108801== at 0x48D28B8: __vfprintf_internal (vfprintf-internal.c:1096) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== ==4108801== Syscall param write(buf) points to uninitialised byte(s) ==4108801== at 0x496E190: write (write.c:26) ==4108801== by 0x48F6E64: _IO_file_write@@GLIBC_2.2.5 (fileops.c:1180) ==4108801== by 0x48F621F: new_do_write (fileops.c:448) ==4108801== by 0x48F7E78: _IO_do_write@@GLIBC_2.2.5 (fileops.c:425) ==4108801== by 0x48F8282: _IO_file_overflow@@GLIBC_2.2.5 (fileops.c:783) ==4108801== by 0x48EF1B0: putchar (putchar.c:28) ==4108801== by 0x109356: PrintArray (281916.c:47) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== Address 0x4a5a1a2 is 2 bytes inside a block of size 1,024 alloc'd ==4108801== at 0x48407B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==4108801== by 0x48EB76B: _IO_file_doallocate (filedoalloc.c:101) ==4108801== by 0x48F8F4F: _IO_doallocbuf (genops.c:347) ==4108801== by 0x48F8F4F: _IO_doallocbuf (genops.c:342)
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management ==4108801== by 0x48F8F4F: _IO_doallocbuf (genops.c:342) ==4108801== by 0x48F8317: _IO_file_overflow@@GLIBC_2.2.5 (fileops.c:744) ==4108801== by 0x48CA047: __printf_fp_l (printf_fp.c:1254) ==4108801== by 0x48D3EEC: __printf_fp_spec (vfprintf-internal.c:354) ==4108801== by 0x48D3EEC: __vfprintf_internal (vfprintf-internal.c:1061) ==4108801== by 0x48C84FA: printf (printf.c:33) ==4108801== by 0x109335: PrintArray (281916.c:45) ==4108801== by 0x1093AB: main (281916.c:56) ==4108801== 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 ==4108801== ==4108801== HEAP SUMMARY: ==4108801== in use at exit: 88 bytes in 4 blocks ==4108801== total heap usage: 5 allocs, 1 frees, 1,112 bytes allocated ==4108801== ==4108801== 88 (8 direct, 80 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 3 ==4108801== at 0x48407B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==4108801== by 0x1091AB: NewArray (281916.c:15) ==4108801== by 0x10939B: main (281916.c:55) ==4108801== ==4108801== LEAK SUMMARY: ==4108801== definitely lost: 8 bytes in 1 blocks ==4108801== indirectly lost: 80 bytes in 3 blocks ==4108801== possibly lost: 0 bytes in 0 blocks ==4108801== still reachable: 0 bytes in 0 blocks ==4108801== suppressed: 0 bytes in 0 blocks ==4108801== ==4108801== Use --track-origins=yes to see where uninitialised values come from ==4108801== For lists of detected and suppressed errors, rerun with: -s ==4108801== ERROR SUMMARY: 194 errors from 24 contexts (suppressed: 0 from 0)
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management You're missing the most basic of checks, using pointers returned from malloc() when they may be null. You need to fix that immediately. malloc() returns a void*, which is freely convertible to any kind of object pointer without a cast. Adding a cast serves no purpose, except to clutter the code and sometimes to mask a failure to include <stdlib.h>. It's easier for reviewers if we can see that the size allocated matches the type of pointer without having to go back to the pointer's definition. Consider these: struct Array *array = malloc(sizeof *array); array->data = malloc(rows * sizeof *array->data); array->data[i] = malloc(cols * sizeof *array->data[i]); See how they are much more obviously correct, without needing access to the rest of the code? (That's probably why you didn't spot the error in array = (struct Array *)malloc(sizeof(struct Array *))). FreeArray() looks totally broken: if (array != NULL) { return -1; } assert (array->data); The assert() is reached only if array is null, when dereferencing it in array->data is Undefined Behaviour. The right thing to do is to accept and ignore a null pointer argument, just like free() does. A popular naming convention is to prefix all the operations with the type name. That means they are predictable, and they fall together alphabetically when listing all symbols Fixing the above problems gives: #include <assert.h> #include <stdio.h> #include <stdlib.h> struct Array { double **data; size_t rows; size_t cols; }; struct Array *array_calloc(const size_t rows, const size_t cols) { struct Array *array = malloc(sizeof *array); if (!array) { return array; } array->rows = rows; array->cols = cols; array->data = malloc(rows * sizeof *array->data); if (!array->data) { free(array); return NULL; }
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management for (size_t i = 0; i < rows; ++i) { array->data[i] = malloc(cols * sizeof *array->data[i]); if (!array->data[i]) { while (i-->0) { free(array->data[i]); } free(array->data); free(array); return NULL; } for (size_t j = 0; j < cols; ++j) { array->data[i][j] = 0.0; } } return array; } void array_free(struct Array *array) { if (array) { assert (array->data); for (size_t i = 0; i < array->rows; ++i) { free(array->data[i]); } free(array->data); free(array); } } void array_print(const struct Array *array) { for (size_t i = 0; i < array->rows; ++i) { for (size_t j = 0; j < array->cols; ++j) { printf("%.2f ", array->data[i][j]); } printf("\n"); } return; } #include <errno.h> #include <string.h> int main(void) { struct Array *a = array_calloc(2, 4); if (!a) { fputs(strerror(ENOMEM), stderr); return EXIT_FAILURE; } array_print(a); array_free(a); } Reconsider the representation. Using a separate allocation for each row can mean that your data are spread all over the address space, which isn't very cache friendly. Consider a single linear array containing all the columns: struct Array { double *data; size_t rows; size_t cols; }; static double *array_element(struct Array *a, size_t row, size_t col) { return a->data + row * a->cols + col; } This representation also makes it much easier to clean up when one of the allocations fails. #include <stdio.h> #include <stdlib.h> struct Array { double *data; size_t rows; size_t cols; }; /* private helper */ static double *array_element(const struct Array *a, size_t row, size_t col) { return a->data + row * a->cols + col; }
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management /* public interface */ double array_value(const struct Array *a, size_t row, size_t col) { return *array_element(a, row, col); } void array_set_value(const struct Array *a, size_t row, size_t col, double v) { *array_element(a, row, col) = v; } struct Array *array_new(const size_t rows, const size_t cols) { struct Array *array = malloc(sizeof *array); if (!array) { return array; } array->data = malloc(sizeof *array->data * rows * cols); if (!array->data) { free(array); return NULL; } array->rows = rows; array->cols = cols; for (size_t j = 0; j < rows * cols; ++j) { array->data[j] = 0.0; } return array; } void array_free(struct Array *array) { if (array) { free(array->data); free(array); } } void array_print(const struct Array *array) { for (size_t i = 0; i < array->rows; ++i) { for (size_t j = 0; j < array->cols; ++j) { printf("%.2f ", array_value(array, i, j)); } printf("\n"); } } #include <errno.h> #include <string.h> int main(void) { struct Array *a = array_calloc(2, 4); if (!a) { fputs(strerror(ENOMEM), stderr); return EXIT_FAILURE; } array_print(a); array_free(a); } If you're really attached to using indexing rather than a function to access array elements, then (assuming that switching to C++ isn't an option!) we can add an array of row pointers into data. To maintain locality of reference, it's best if we can allocate the storage and pointers together, like this: struct Array { double *data; double **rows; size_t height; size_t width; };
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c, array, memory-management array->data = malloc(sizeof *array->data * height * width + sizeof *array->rows * height); if (!array->data) { free(array); return NULL; } array->rows = (double **)((char*)array->data + sizeof *array->data * height * width); array->height = height; array->width = width; for (size_t i = 0; i < height; ++i) { array->rows[i] = array->data + i * width; } No changes required to any other functions. Then we can access elements using the accessor functions or using indexing as array->rows[i][j].
{ "domain": "codereview.stackexchange", "id": 44224, "lm_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, array, memory-management", "url": null }
c++, statistics, c++20 Title: Container that orders its elements based on their frequency Question: I was inspired by Find the K most-frequent values in a vector, and originally posted an early version of this in an answer. The aim is to have a container that maintains values ordered by their frequency, so we can easily obtain the most-frequent values at any time. I've just implemented enough to be able to insert elements and obtain the N most frequent; the addition of member functions to make it a complete container (with iterators, removal, emplacement etc.) would be straightforward and might make an enjoyable exercise for the reader. The insert() function operates in O(1) time, confirmed by varying the number of iterations of the test program's loop between 100,000 and 100,000,000. When I used ten million insertions, run time was about 1.1 seconds on my system (compiled with g++-12 -O3). #include <algorithm> #include <concepts> #include <functional> #include <list> #include <map> #include <iterator> #include <ranges> #include <unordered_map> #include <utility> #include <vector> namespace { template<typename Key> concept is_hashable = requires { std::hash<Key>{}; }; } template<typename T> class frequency_ordered_multiset { template<typename Key, typename Value> using fast_map = std::conditional_t<is_hashable<Key>, std::unordered_map<Key, Value>, std::map<Key, Value>>; using key_type = std::conditional_t<sizeof (T) <= sizeof (std::reference_wrapper<const T>), T, std::reference_wrapper<const T>>; // We use a list because its iterators stay valid after modifications. // The list is always in descending order of count. struct item { const T val; std::size_t count; }; std::list<item> items = {}; // We use this map to find the list items by their value. using items_iter = decltype(items.begin()); fast_map<key_type, items_iter> by_value = {};
{ "domain": "codereview.stackexchange", "id": 44225, "lm_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++, statistics, c++20", "url": null }
c++, statistics, c++20 public: template<typename V> requires std::assignable_from<T&, V&> void insert(V&& val) { auto map_it = by_value.find(val); if (map_it == by_value.end()) { // first appearance - put it at end of list items.emplace_back(std::forward<V>(val), 1); auto list_it = items.end(); by_value.emplace(list_it->val, --list_it); return; } // Update existing item auto const list_it = map_it->second; auto const new_count = ++list_it->count; // Search backwards for the correct position auto const other_it = std::ranges::lower_bound(std::reverse_iterator{list_it}, items.rend(), new_count, std::less{}, &item::count).base(); // Move the item (without invalidating iterators) // This may be a no-op items.splice(other_it, items, list_it); } auto most_frequent(std::size_t k) { return items | std::views::take(k) | std::views::transform(&item::val); } }; #include <chrono> #include <random> #include <iostream> int main() { // check correctness frequency_ordered_multiset<int> fom; for (auto i: {1, 1, 3, 3, 2, 2, 2, 3, 3, 3, 3, 4, 4}) { fom.insert(i); std::ranges::copy(fom.most_frequent(2), std::ostream_iterator<int>(std::cout, ", ")); std::cout << '\n'; } // test performance std::mt19937 r; std::uniform_int_distribution<int> dist{0, 100}; for (auto i = 0; i < 10'000'000; ++i) { fom.insert(dist(r)); } std::ranges::copy(fom.most_frequent(10), std::ostream_iterator<int>(std::cout, ", ")); std::cout << '\n'; }
{ "domain": "codereview.stackexchange", "id": 44225, "lm_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++, statistics, c++20", "url": null }
c++, statistics, c++20 Test program output: time ./281926 1, 1, 1, 3, 1, 3, 1, 3, 2, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 2, 1, 3, 2, 1, 3, 2, 1, 3, 2, 1, 3, 2, 1, 90, 94, 71, 10, 36, 11, 15, 83, 24, 61, 1.11user 0.00system 0:01.11elapsed 100%CPU (0avgtext+0avgdata 3568maxresident)k Answer: Higher memory usage than necessary if K < N If you are only interested in the \$K\$ most frequent elements, then you only need to maintain a list of size \$K\$. You can do that if you make sure the key and counter are stored in the map, not in the list, and only use the list to maintain references to map entries sorted by the counter value: using fast_map = …; struct item { const T val; std::size_t count{}; std::list<fast_map<T, item>::iterator>::iterator it; }; fast_map<T, item> items; std::list<fast_map<T, item>::iterator> by_count; Despite the seemingly circular type definition this compiles. You can use by_count.end() as the value of it for those items that are not part of the list. You could also avoid the separate std::list entirely if you make item part of an intrusive list, like for example using Boost.Intrusive, although this could end up using more memory if \$N\$ is much larger than \$K\$. Don't use increment/decrement operators on variables used multiple times in one statement This is confusing, UB before C++17, and unspecified since C++17 (see order of evaluation): auto list_it = items.end(); by_value.emplace(list_it->val, --list_it); Just move the decrement to its own line. Alternatively, you could reverse the order of the list so you can use items.begin() and not have to modify that. Does not compile if T is small and not copyable You are storing T twice by value if its size is equal to or smaller than a reference. However, it is possible to make a small type that is not copyable. You could check for this and use a std::reference_wrapper for uncopyable types regardless of their size. Complexity
{ "domain": "codereview.stackexchange", "id": 44225, "lm_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++, statistics, c++20", "url": null }
c++, statistics, c++20 The insert() function operates in O(1) time, confirmed by varying the number of iterations of the test program's loop between 100,000 and 100,000,000. That's the average-case complexity, but not the worst-case complexity. Consider that there is a potential non-\$O(1)\$ operation in insert(), and that's the call to std::ranges::lower_bound(). On a std::list, this is \$O(N)\$. That might happen if all elements in the list so far have the same count, and then another insert happens that would increment the count of one of those existing elements. You might then think that the amortized complexity of finding the \$K\$ most-frequent elements of a vector is still \$O(N)\$, but I think that might not be the case with a worst-case input. Consider that vector having the values \$1 \dots N/2\$, in that order, repeated twice (possibly reversed the second time). That might up ending \$O(N^2)\$.
{ "domain": "codereview.stackexchange", "id": 44225, "lm_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++, statistics, c++20", "url": null }
c#, programming-challenge Title: Find largest binary gap of a number N Question: I have picked up a problem from Codility website and tried to work it out. A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. Write a function: class Solution { public int solution(int N); } that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap. I would appreciate guidance of how to refactor it and what to look for in terms of efficiency? Optimisation I'd like to achieve would be, less type conversion, no zero items in the list, would there be a better way to find the max number in a list, or .Sort(); is good enough? Any ideas welcome, thank you. using System; using System.Collections.Generic; namespace rec { class MainClass { public static void Main(string[] args) { Console.WriteLine(FindGap(777)); // } public static int FindGap(int number) { string toBinary = Convert.ToString(number, 2); char[] toChar = toBinary.ToCharArray(); string previous = ""; string current = ""; int count = 0; int answer = 0; List<int> lastGap = new List<int>(); for (int i = 0; i < toChar.Length; i++) { if (toChar[i].ToString() == "1") { // temp becomes 1 current = toChar[i].ToString(); if (current == "1") { lastGap.Add(count); count = 0; continue; } } if (toChar[i].ToString() == "0" && current == "1") { current = "0"; count++;
{ "domain": "codereview.stackexchange", "id": 44226, "lm_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#, programming-challenge", "url": null }
c#, programming-challenge count++; previous = current; } else if (toChar[i].ToString() == "0" && previous == "0") { current = "0"; count++; previous = current; } } lastGap.Sort(); answer = lastGap.Last(); if (answer > 1) { return answer; } else return 0; } } } Answer: If you're just looking for the longest stretch of zeros you don't need to use a list at all. You just iterate through the binary representation until you find a stretch of zeros. If you hit a new high score, you can overwrite the old high score with the new one and keep moving forward, forgetting about the past. This is called a "greedy algorithm." public static int FindGap(int number) { string binaryRep = Convert.ToString(number, 2); int maxGapSize = 0; int currGapSize = 0; foreach(char ch in binaryRep) { if (ch == '0') { currGapSize++; } else { maxGapSize = Math.Max(currGapSize, maxGapSize); currGapSize = 0; } } return maxGapSize; }
{ "domain": "codereview.stackexchange", "id": 44226, "lm_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#, programming-challenge", "url": null }
c#, programming-challenge return maxGapSize; } If you want to get really fancy, you don't even need to convert the number to a string. You can use bit shifts to "iterate" through the bits in the number. The number 9 is 1001 in binary. Shift the bits over one, and you've got 100. Shift it over again, and you've got 10. You can use modulus operations to see if the least significant digit is 0 or 1. This is just a fancy way to repeatedly divide by 2. In fact, you could solve this problem by dividing by 2 instead but this way works as well. (There's also probably a more terse way to write this, but this is perfectly efficient.) public static int FindGap2(int number) { int maxGapSize = 0; int currGapSize = 0; if (number == 0) return 0; while (number % 2 == 0) number = number >> 1; while (number > 0) { if(number%2 == 0) { currGapSize++; } else { maxGapSize = Math.Max(currGapSize, maxGapSize); currGapSize = 0; } number = number >> 1; } return maxGapSize; }
{ "domain": "codereview.stackexchange", "id": 44226, "lm_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#, programming-challenge", "url": null }
java, math-expression-eval, expression-trees Title: Designing a basic Binary Expression Tree structure Question: Preface I need to generate some algebraic expressions for math testing in elementary school. The test should generate a list of expressions compiled according to certain rules and check the correctness of the solution. I have decided to represent the expression as a Binary expression tree. At this stage, I only need to be able to convert the tree to infix form, as well as evaluate the result of the expression. I do not plan to expand this functionality, nor do I plan to add new types of nodes or extend existing ones. To generate expressions, a separate classes will be written that will build expressions recursively using only constructors. And I intentionally limit myself to int numbers only. I'm not a professional developer and I don't know Java very well. This is more of a self study project. I need help to understand if I'm moving in the right direction. Subject My recursive structure looks like this: ExpressionTree = Leaf | Branch Branch = ExpressionTree Operator ExpressionTree ExpressionTree interface import org.jetbrains.annotations.NotNull; public sealed interface ExpressionTree permits Leaf, Branch { @NotNull String toInfix(); int evaluate(); } And I immediately have a question. I am 100% sure that no one but me will use this interface. And I am not going to write other implementations. Are these good enough reasons not to waste time writing the obvious Javadoc? Leaf class import org.jetbrains.annotations.NotNull; public final class Leaf implements ExpressionTree { private final int value; public Leaf(int value) { this.value = value; } @Override public @NotNull String toInfix() { return String.valueOf(value); } @Override public int evaluate() { return value; } }
{ "domain": "codereview.stackexchange", "id": 44227, "lm_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, math-expression-eval, expression-trees", "url": null }
java, math-expression-eval, expression-trees @Override public int evaluate() { return value; } } Branch class This is where the main work takes place. The evaluation of the branch is obvious. To represent an expression in infix form, you need to correctly place the brackets. And this is exactly the place where I most likely overdid it. How clear is the logic of the infix() method? How can this part of the code be improved? I am primarily interested in the readability and overall style of the code. import org.jetbrains.annotations.NotNull; import java.util.function.BiPredicate; import java.util.function.Function; public final class Branch implements ExpressionTree { private final @NotNull Operator operator; private final @NotNull ExpressionTree left; private final @NotNull ExpressionTree right; public Branch(final @NotNull Operator operator, final @NotNull ExpressionTree left, final @NotNull ExpressionTree right) { this.operator = operator; this.left = left; this.right = right; } private static final BiPredicate<Operator, Operator> less = (op1, op2) -> op1.getPrecedence() < op2.getPrecedence(); private static final BiPredicate<Operator, Operator> lessOrEqual = (op1, op2) -> op1.getPrecedence() <= op2.getPrecedence(); private static final Function<Operator, BiPredicate<Operator, Operator>> selectPredicate = op -> op.isCommutative() ? less : lessOrEqual; private static boolean isParenthesisNeeded(BiPredicate<Operator, Operator> biPredicate, ExpressionTree child, Branch parent) { if (child instanceof Branch) { return biPredicate.test(((Branch) child).operator, parent.operator); } else { return false; } }
{ "domain": "codereview.stackexchange", "id": 44227, "lm_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, math-expression-eval, expression-trees", "url": null }
java, math-expression-eval, expression-trees @Override public @NotNull String toInfix() { String leftExprFormat = isParenthesisNeeded(less, left, this) ? "(%s)" : "%s"; String rightExprFormat = isParenthesisNeeded(selectPredicate.apply(operator), right, this) ? "(%s)" : "%s"; String format = String.join(" ", leftExprFormat, "%s", rightExprFormat); return format.formatted(left.toInfix(), operator.getSymbol(), right.toInfix()); } @Override public int evaluate() { return operator.apply(left.evaluate(), right.evaluate()); } } Operator enum import org.jetbrains.annotations.NotNull; import java.util.function.IntBinaryOperator; public enum Operator { ADD("+", (a, b) -> a + b, 5, true), SUB("-", (a, b) -> a - b, 5, false), MUL("*", (a, b) -> a * b, 7, true), DIV("/", (a, b) -> a / b, 7, false); private final @NotNull String symbol; private final @NotNull IntBinaryOperator op; private final int precedence; private final boolean commutative; Operator(@NotNull String symbol, @NotNull IntBinaryOperator op, int precedence, boolean commutative) { this.symbol = symbol; this.op = op; this.precedence = precedence; this.commutative = commutative; } public int apply(int left, int right) { return op.applyAsInt(left, right); } public @NotNull String getSymbol() { return symbol; } public int getPrecedence() { return precedence; } public boolean isCommutative() { return commutative; } } I wrote tests and they are all green. I also already have an expression generator, but it still needs some work. I am mainly interested in my Branch and Operator classes. Is it OK to implement calculation logic directly in enum? Thanks for any feedback.
{ "domain": "codereview.stackexchange", "id": 44227, "lm_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, math-expression-eval, expression-trees", "url": null }
java, math-expression-eval, expression-trees Answer: While the expression tree is in fact a tree-structure, the elements in the tree are operators and operands. Using overly generic non-representative names makes it more difficult to follow the code. If you revise it as follows, the names describe the function of the classes (and you will not have a hard time trying to figure out a name for unary operator class when you decide to add it :)). Expression = Operand | BinaryOperator BinaryOperator = BiFunction Expression Expression
{ "domain": "codereview.stackexchange", "id": 44227, "lm_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, math-expression-eval, expression-trees", "url": null }
java, math-expression-eval, expression-trees K.H.'s suggestion for separating the infix formatting into a separate InfixFormatter class is a good one and you should do it. Putting the formatting code in the expression tree violates single responsibility principle and makes it difficult to add different kinds of formatting. Are these good enough reasons not to waste time writing the obvious Javadoc? You don't need a reason to not write obvious documentation. Obvious documentation should never be written. The trick is to know when documentation is non-obvious and needs to be written. For example, if you don't rename your classes, you would have to write documentation for the Branch class to explain that is in fact a binary operator. If you rename it, the class name already tells it's function and you don't need documentation for it. An easy way to figure out what needs to be documented is to leave the code alone and come back to it a year later. You will instantly see the places you should have documented. The lambdas used in the infix formatting sure look like something that might need to be explained to future you. Is it OK to implement calculation logic directly in enum? It depends. Personally I don't like code in enums. For this case it may be justifiable. But the question probably should be that is it a good idea to define the calculation logic as enums? My opinion is that it's not. Enums are closed classes and you can't add any operators now without changing the enum. Going to extreme, one might argue whether the Operators even need to know what their symbols are? The symbols exist only for display purposes and isn't displaying the responsibility of InfixFormatter and InfixParser? Should division use / or ÷? Should multiplication use * or ×? But I digress... :)
{ "domain": "codereview.stackexchange", "id": 44227, "lm_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, math-expression-eval, expression-trees", "url": null }
java, math-expression-eval, expression-trees Using IDE-specific annotations is not a long-term solution. While they provide static code validation help, they don't provide any runtime assistance if your classes are used by someone else. Also they add an unnecessary dependency to a third party library. It is better to use Objects.requireNonNull(...) in public APIs. A good static code analyzer will be able to follow the execution path and show warnings about misuse. Also having @NotNull annotation on both final class fields and the constructor parameters that are assigned to them is redundant. The @NotNull annotations in the Operator enum are mostly unnecessary as the fields and the constructor are not public.
{ "domain": "codereview.stackexchange", "id": 44227, "lm_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, math-expression-eval, expression-trees", "url": null }
python, sorting, reinventing-the-wheel Title: Optimizing my sorting function Question: I created my own list sorting function with Python: def mysort(l): for i, (x, y) in enumerate(zip(l, l[1:])): if y < x: l[i], l[i + 1] = l[i + 1], l[i] mysort(l) else: return l And: >>> mysort(l) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> I was thinking that how I would be able to optimize this function. This function is recursive, thus it runs many times + it has a for loop. Would it be possible to optimize like with O(log(n))? Answer: The sorting function that you have implemented is a variant of bubble sort, which has a time complexity of O(n^2) in the worst case. This means that the time taken by the algorithm grows quadratically with the size of the input. To optimize this function, you can use a more efficient sorting algorithm such as quicksort, which has a time complexity of O(n * log(n)) in the average case and O(n^2) in the worst case. Quicksort works by selecting a pivot element and partitioning the list around it, such that all the elements smaller than the pivot are placed before it and all the elements larger than the pivot are placed after it. This process is then repeated recursively on the left and right partitions until the list is fully sorted. Here's an example of how you can implement quicksort in Python: def quicksort(l): if len(l) <= 1: return l pivot = l[0] left = [x for x in l[1:] if x < pivot] right = [x for x in l[1:] if x >= pivot] return quicksort(left) + [pivot] + quicksort(right) This implementation has a time complexity of O(n * log(n)) in the average case, and it can be optimized further by using techniques such as pivot selection and in-place sorting. I hope this helps! Let me know if you have any questions.
{ "domain": "codereview.stackexchange", "id": 44228, "lm_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, sorting, reinventing-the-wheel", "url": null }
c#, beginner, console Title: Select Menu in Command Prompt Question: I want to make small console app where you can choose an option from a list using the arrows on the keyboard. Here is my code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CMD_menu_select { internal class Program { static void Main(string[] args) { var cities = new List<string>() { "New York", "London", "Mumbai", "Chicago" }; int index = 0; ConsoleKeyInfo keyinfo; while (true) { WriteCities(cities, index); keyinfo = Console.ReadKey(); if (keyinfo.Key == ConsoleKey.DownArrow) { if (index + 1 < cities.Count) { index++; } } else if (keyinfo.Key == ConsoleKey.UpArrow) { if (index - 1 >= 0) { index--; } } else if (keyinfo.Key == ConsoleKey.Enter) { // there will be another logic in the future here. For now it is irrelevant. Console.WriteLine($"{cities[index]} was chosen as an option"); break; } }
{ "domain": "codereview.stackexchange", "id": 44229, "lm_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#, beginner, console", "url": null }
c#, beginner, console } void WriteCities(List<string> _cities, int _index) { Console.Clear(); foreach (var city in _cities) { string selectOptionSymbol = " "; if (city == _cities[_index]) { selectOptionSymbol = "> "; Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; } Console.WriteLine($"{selectOptionSymbol}{city}"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; } } } } } It works fine. However I am not sure if this is the way to go about things like this. Do I need different approach, can my code be shorter(not so repetitive), naming convention etc... Keep in mind I am just beginner. Any improvements will be greatly appreciated. Answer: First let me share with you the revised version of your code. Please note that this version contains a bug. The fixed version can be found under the update #2 section. Then I will guide you through the changes. static readonly string[] Cities = new [] { "New York", "London", "Mumbai", "Chicago" }; static void Main() { int selectedLineIndex = 0; ConsoleKey pressedKey; do { UpdateMenu(selectedLineIndex); pressedKey = Console.ReadKey().Key; if (pressedKey == ConsoleKey.DownArrow && selectedLineIndex + 1 < Cities.Length) selectedLineIndex++; else if (pressedKey == ConsoleKey.UpArrow && selectedLineIndex - 1 >= 0) selectedLineIndex--; } while (pressedKey != ConsoleKey.Enter); Console.WriteLine($"{Cities[selectedLineIndex]} was chosen as an option"); }
{ "domain": "codereview.stackexchange", "id": 44229, "lm_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#, beginner, console", "url": null }
c#, beginner, console Console.WriteLine($"{Cities[selectedLineIndex]} was chosen as an option"); } static void UpdateMenu(int index) { Console.Clear(); foreach (var city in Cities) { bool isSelected = city == Cities[index]; ChangeLineColor(isSelected); Console.WriteLine($"{(isSelected ? "> " : " ")}{city}"); } } static void ChangeLineColor(bool shouldHighlight) { Console.BackgroundColor = shouldHighlight ? ConsoleColor.White : ConsoleColor.Black; Console.ForegroundColor = shouldHighlight ? ConsoleColor.Black : ConsoleColor.White; } Cities It seems like this collection is fairly static, so you can define it as a class-level static field In order to emphasize that the collection should not be changed during runtime you can mark the field as readonly I would also suggest to use a simple array rather than a List for this simple use case Index and KeyInfo I would suggest to aim for more meaningful names I've used selectedLineIndex and pressedKey to express the intent of the variables I've also changed the data type of keyinfo from ConsoleKeyInfo to ConsoleKey The infinite loop You have a single exit condition when the user has pressed Enter So, we could use that in a do-while construction Nested if statements Your nested (two levels) if statements can be combined by using the && operator With this change the conditions become a bit more complex but the your intention will remain clear Write Cities Since we have moved the cities collection to class level that's why we don't need to pass it as a parameter I've also changed the name of the method to UpdateMenu to express the intent I've declared the UpdateMenu as a static method outside of Main Please note that in case of C# the parameter's naming convention is camel casing I've refactored your code a bit to streamline your logic Changing Colors
{ "domain": "codereview.stackexchange", "id": 44229, "lm_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#, beginner, console", "url": null }
c#, beginner, console Changing Colors I've extract your line color changing logic into its own method to reduce code duplication I've used conditional ternary operators to choose the right colors UPDATE #1 I just noticed that there is some problem with this code. When you press down and the last city is already selected the background changes to white and the city black According to my understanding you were referring to this bug The root cause of the problem is that the UpdateMenu is called unconditionally inside the do-while loop. It should be called only if the selection is changed. One way to fix this problem is to store the previously selected line index and the current index. The update of the menu will be called only if the numbers differ. static void Main() { int previousLineIndex = -1 , selectedLineIndex = 0; ConsoleKey pressedKey; do { if(previousLineIndex != selectedLineIndex) { UpdateMenu(selectedLineIndex); previousLineIndex = selectedLineIndex; } pressedKey = Console.ReadKey().Key; ... } while (pressedKey != ConsoleKey.Enter); ... } UPDATE #2 Yes that is the bug a was talking about. However it still has this problem when you are on the last element and you go up the list. This strange background colouring issue drive my attention to the ChangeLineColor method. After re-reading the code I've just realised that we don't need to change all the time the Background and Foreground colors. It is enough to do that only once when we draw the selected menu: Change colors to the inverted ones Print the selected line Change colors to the original ones After the above code change the code looks like this static readonly string[] Cities = new [] { "New York", "London", "Mumbai", "Chicago" }; static void Main() { int previousLineIndex = -1 , selectedLineIndex = 0; ConsoleKey pressedKey;
{ "domain": "codereview.stackexchange", "id": 44229, "lm_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#, beginner, console", "url": null }
c#, beginner, console do { if(previousLineIndex != selectedLineIndex) { UpdateMenu(selectedLineIndex); previousLineIndex = selectedLineIndex; } pressedKey = Console.ReadKey().Key; if (pressedKey == ConsoleKey.DownArrow && selectedLineIndex + 1 < Cities.Length) selectedLineIndex++; else if (pressedKey == ConsoleKey.UpArrow && selectedLineIndex - 1 >= 0) selectedLineIndex--; } while (pressedKey != ConsoleKey.Enter); Console.WriteLine($"{Cities[selectedLineIndex]} was chosen as an option"); } static void UpdateMenu(int index) { Console.Clear(); foreach (var city in Cities) { bool isSelected = city == Cities[index]; if (isSelected) DrawSelectedMenu(city); else Console.WriteLine($" {city}"); } } static void DrawSelectedMenu(string city) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine($"> {city}"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; } And gladly the bug is gone
{ "domain": "codereview.stackexchange", "id": 44229, "lm_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#, beginner, console", "url": null }
r Title: Convert dataset from wide to a longer format for two different set of columns Question: I have a dataset that is a bit too wide for the EDA plots I would like to make. The data can be found here: https://www.massey.ac.nz/~kgovinda/data/Bill_Colour.RData But looks something like this: CommonName r_ChromaticityFemaleLowerMandible r_ChromaticityFemaleUpperMandible r_ChromaticityMaleLowerMandible r_ChromaticityMaleUpperMandible many more column ... African_Broadbill 0.3331 0.3109 0.3584 0.3573 etc... I am pivoting it longer so that three columns are tacked on to the end while removing the fourr_* Chromaticity columns LowerMandible UpperMandible Sex 0.3331 0.3109 Female 0.3584 0.3573 Male 0.3473 0.340 Male My current method of doing this requires two pivot_longer for upper and lower and then they are bonded together. library(tidyverse) load(url("https://www.massey.ac.nz/~kgovinda/data/Bill_Colour.RData")) lowerMandible <- Bill_Colour %>% pivot_longer(c(r_ChromaticityFemaleLowerMandible, r_ChromaticityMaleLowerMandible), values_to = "LowerMandible") %>% select(-name) upperMandible <- Bill_Colour %>% select(r_ChromaticityFemaleUpperMandible, r_ChromaticityMaleUpperMandible) %>% pivot_longer(c(r_ChromaticityFemaleUpperMandible, r_ChromaticityMaleUpperMandible), values_to = "UpperMandible") %>% mutate(Sex = as.factor(str_sub(name,15,-14))) %>% select(-name) upperAndLowerBySex <- cbind.data.frame(lowerMandible, upperMandible) %>% select(-r_ChromaticityFemaleUpperMandible, -r_ChromaticityMaleUpperMandible) I feel like there should be a way to do this with one set of pivot_longer rather than making multiple datasets.
{ "domain": "codereview.stackexchange", "id": 44230, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "r", "url": null }
r Answer: We can do this by renaming the columns to appropriate strings which can be processed by pivot_longer and its names_sep argument. We need to rename the desired columns; e.g. from r_ChromaticityMaleLowerMandible to LowerMandible_Male. See this https://regex101.com/r/6QstQq/1 to better understand the regex pattern. Then we can simply use pivot_longer and apply it on the columns that contain Mandible in their names. By providing multiple values to names_to and a parser to names_sep we can break the pivoted columns. library(tidyverse) load(url("https://www.massey.ac.nz/~kgovinda/data/Bill_Colour.RData")) Bill_Colour %>% select(contains("r_Chromaticity")) %>% ## you can select other columns as needed rename_with(~str_replace(.x, "(r_Chromaticity)(.*ale)(.*)", "\\3_\\2"), contains("r_Chromaticity")) %>% pivot_longer(., cols = contains("Mandible"), names_to = c(".value", "sex"), names_sep = "_") #> # A tibble: 3,210 x 3 #> sex LowerMandible UpperMandible #> <chr> <dbl> <dbl> #> 1 Female 0.333 0.311 #> 2 Male 0.358 0.357 #> 3 Female 0.347 0.341 #> 4 Male 0.359 0.394 #> 5 Female 0.352 0.430 #> 6 Male 0.370 0.443 #> 7 Female 0.370 0.375 #> 8 Male 0.378 0.351 #> 9 Female 0.336 0.329 #> 10 Male 0.343 0.335 #> # ... with 3,200 more rows Created on 2022-12-17 by the reprex package (v2.0.1)
{ "domain": "codereview.stackexchange", "id": 44230, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "r", "url": null }
array, swift, search Title: Swift - efficient array searching Question: I am trying to find a way to search an Int array (all numbers are > 0) and identify sequences where the sum of each element is a specific number. One element can be in more than one sequence. This works: let input = [2, 52, 23, 52, 28, 47, 13, 15] let target = 75 var result: [[Int]] = [] let count = input.count var start = 0 while start < count { for index in start..<count { let temp = Array(input[start...index]) let sum = temp.reduce(0, +) if sum == target { result.append(temp) break } if sum > target { break } } start += 1 } print(result) // [[52, 23], [23, 52], [28, 47], [47, 13, 15]] However, when the array gets longer and the target higher, it obviously slows down. For instance an array of 10000 elements and a target of 400 takes about 2 seconds. The above example takes 0.008 seconds. Is there anyway I can improve on my code so that it doesn't slow down so much for larger arrays and targets? Answer: Instead of putting everything into the “main” unit it is better to put the search algorithm in a dedicated function: func subarrays(in input:[Int], withSum target: Int) -> [[Int]] { // ... } print(subarrays(in: [2, 52, 23, 52, 28, 47, 13, 15], withSum: 75))
{ "domain": "codereview.stackexchange", "id": 44231, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, search", "url": null }
array, swift, search print(subarrays(in: [2, 52, 23, 52, 28, 47, 13, 15], withSum: 75)) That is clearer and allows to add test cases easily. You use a while loop for iterating over the start index, and a for loop for iterating over the end index. I would use a for loop for both. If the lower index is called start end the upper index is better called end (alternatively: startIndex, endIndex or lowIndex, highIndex). Since all input numbers are positive, a target <= 0 can never be achieved, so one can check that case first. You add the input numbers between start and end index with reduce(), which can be done directly on the array slice. This saves some array creations (which copy the elements). The code would then look like this: func subarrays(in input:[Int], withSum target: Int) -> [[Int]] { if target <= 0 { return [] } var result: [[Int]] = [] let count = input.count for start in 0..<count { for end in start..<count { let sum = input[start...end].reduce(0, +) if sum == target { result.append(Array(input[start...end])) break } if sum > target { break } } } return result } Instead of calculating the sum over every slice one can update the sum when the end index is incremented. This allows to get rid of the reduce() call and reduces (!) the complexity from \$ O(N^3) \$ to \$ O(N^2) \$ (where \$ N \$ is the length of the input array): func subarrays(in input:[Int], withSum target: Int) -> [[Int]] { if target <= 0 { return [] }
{ "domain": "codereview.stackexchange", "id": 44231, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, search", "url": null }
array, swift, search var result: [[Int]] = [] let count = input.count for start in 0..<count { var sum = 0 for end in start..<count { sum += input[end] if sum == target { result.append(Array(input[start...end])) break } if sum > target { break } } } return result } But there is a better algorithm: Instead of two nested loops it suffices to increment the end index if the current sum is too small, and to increment the start index if the current sum is too large. The current sum is always kept up to date by incrementing or decrementing it accordingly: func subarrays(in input:[Int], withSum target: Int) -> [[Int]] { var result: [[Int]] = [] let count = input.count var start = 0 var end = 0 var sum = 0 // Loop invariants: // 0 <= start <= end <= count // sum = input[start] + ... + input[end - 1] while start < count { while end < count { sum += input[end] ; end += 1 if sum == target { result.append(Array(input[start..<end])) break } else if sum > target { break } } while start < end { sum -= input[start] ; start += 1 if sum == target { result.append(Array(input[start..<end])) break } else if sum < target { break } } } return result } Documenting the loop invariants help to understand the logic of the nested while loops. This algorithm has \$ O(N) \$ complexity, and should be considerably faster for large arrays.
{ "domain": "codereview.stackexchange", "id": 44231, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, search", "url": null }
strings, formatting, clojure Title: Clean up improperly formatted phone numbers Question: This is a problem from Exercism here, the goal is to clean up badly formatted phone numbers. The rules are: If the phone number is less than 10 digits assume that it is a bad number If the phone number is 10 digits assume that it is good If the phone number is 11 digits and the first number is 1, trim the 1 and use the first 10 digits If the phone number is 11 digits and the first number is not 1, then it is a bad number If the phone number is more than 11 digits assume that it is a bad number A function should pretty-print the numbers in the form (123) 456-7890. Here is my solution. I'm very new to Clojure and am sure it's not idiomatic in parts. For example, should I have stored the different parts of the number as separate variables? I would also be interested in tips on how to format the code to make it easier to read, I'm only aware of lispy-multiline which I find a bit too aggressive. All feedback much appreciated. (ns phone-number) (defn digit-not-one-or-zero [digit] (and (not (= \0 digit)) (not (= \1 digit)))) (defn clean-number [num-string] ;; strip all non-digit characters from a string (filter #(Character/isDigit %) num-string)) (defn check-valid [num-string] ;; number is valid only if: ;; a) length is between 10-11 chars ;; b) if 11 chars, first digit must be 1 ;; c) (after stripping first digit if 11), first and fourth can't be 0 or 1 (let [clean-string (clean-number num-string) len (count clean-string)] (if (or (< len 10) (> len 11)) false (if (= len 11) (if (= \1 (first clean-string)) (check-valid (rest clean-string)) false) (if (and (digit-not-one-or-zero (first clean-string)) (digit-not-one-or-zero (nth clean-string 3))) true false)))))
{ "domain": "codereview.stackexchange", "id": 44232, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, formatting, clojure", "url": null }
strings, formatting, clojure (defn number [num-string] (if (check-valid num-string) (let [clean-string (clean-number num-string)] (if (= (count clean-string) 10) (apply str (clean-number clean-string)) (apply str (rest (clean-number clean-string))))) "0000000000")) (defn area-code [num-string] ;; get the first 3 chars of the cleaned up number (apply str (take 3 (number num-string)))) (defn pretty-print [num-string] (let [formatted-number (number num-string)] (apply str (concat "(" (area-code num-string) ")" " " (subs formatted-number 3 6) "-" (subs formatted-number 6))))) Answer: I suggest you to look at Clojure Cheatsheet and get familiar with the functions dedicated for working with strings. There is also the library clojure.string, containing a few more. With these functions, you won't have to convert your string into sequence and then back repeatedly. Take for example your pretty-print- subs returns string, concat returns sequence, apply str returns string again. Pick the correct data structure at the beginning, use dedicated functions and convert as little as possible. Use :require in ns to include clojure.string library: (ns phone-number (:require [clojure.string :as s]) (:gen-class)) I will start with the area-code. This function could be improved with ->> (thread-last macro) and clojure.string/join like this: (defn area-code [num-string] (->> (number num-string) (take 3) s/join)) But you can also use subs: (defn area-code [num-string] (subs (number num-string) 0 3)) Next, pretty-print. You can use format here: (defn pretty-print [num-string] (let [validated (number num-string)] (format "(%s) %s-%s" (area-code validated) (subs validated 3 6) (subs validated 6)))) Next, digit-not-one-or-zero. You usually create a set with these elements and call it on your argument, something like: (defn digit-not-one-or-zero [digit] (not (#{\0 \1} digit)))
{ "domain": "codereview.stackexchange", "id": 44232, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, formatting, clojure", "url": null }
strings, formatting, clojure Or even shorter: (def digit-not-one-or-zero (complement #{\0 \1})) Your clean-number is ok (I would just add s/join at the end to ensure it will return a string, as any other function here), unless you want to use some regex: (defn clean-number [num-string] (s/replace num-string #"\D" "")) Next, number and check-valid. Don't use nested ifs- learn about cond, condp and case and use these. When can be also useful here. Don't use (if ... true false). In Clojure, all values are logically true or false. The only "false" values are false and nil - all other values are logically true. So, take this example: (if (and (digit-not-one-or-zero (first clean-string)) (digit-not-one-or-zero (nth clean-string 3))) true false) You can just write: (and (digit-not-one-or-zero (first clean-string)) (digit-not-one-or-zero (nth clean-string 3))) check-valid is too long- you should break it into smaller functions. So, here is my version you can study. Note how using short functions, idioms and proper flow-control macros increased readability: (ns phone-number (:require [clojure.string :as s]) (:gen-class)) (def allowed-digits (complement #{\0 \1})) (defn clean-number [num-string] (s/replace num-string #"\D" "")) (defn validate10 [s] (and (allowed-digits (.charAt s 0)) (allowed-digits (.charAt s 3)) s)) (defn validate11 [s] (when (= \1 (.charAt s 0)) (validate10 (subs s 1)))) (defn validate [num-string] (condp = (count num-string) 11 (validate11 num-string) 10 (validate10 num-string) false)) (defn number [num-string] (if-let [valid (validate (clean-number num-string))] valid "0000000000")) (defn area-code [num-string] (subs (number num-string) 0 3)) (defn pretty-print [num-string] (let [validated (number num-string)] (format "(%s) %s-%s" (area-code validated) (subs validated 3 6) (subs validated 6))))
{ "domain": "codereview.stackexchange", "id": 44232, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, formatting, clojure", "url": null }
strings, formatting, clojure EDIT: Alternative solution with regexes: (defn number [num-string] (if-let [valid (->> (s/replace num-string #"\D" "") (re-matches #"1?([^01]..[^01].{6})") second)] valid "0000000000")) (defn area-code [num-string] (subs (number num-string) 0 3)) (defn pretty-print [num-string] (s/replace (number num-string) #"(\d{3})(\d{3})(\d{4})" "($1) $2-$3"))
{ "domain": "codereview.stackexchange", "id": 44232, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, formatting, clojure", "url": null }
strings, unit-testing, rust, vectors Title: Protein Translation Learning Exercise from exercism.org Question: I'm learning Rust by solving exercises from different tracks on Exercism. The below code is an implementation of "Protein Translation" from the Python track. I split protein into separate functions - nucleotide_sequence and codon_translation, which I think improves readability. fn nucleotide_sequence(rna: &str) -> Vec<&str> { let mut position = 0; let mut codons = Vec::<&str>::with_capacity(rna.len()); if rna.len() % 3 != 0 { return codons; } else { while position < rna.len() { let mut sequence_length = 0; for codon in rna.chars().by_ref().take(3) { sequence_length += codon.len_utf8(); } codons.push(&rna[position..position + sequence_length]); position += sequence_length; } codons } } fn codon_translation(sequence_chunks: Vec<&str>) -> Vec<&str> { let mut polypeptide = Vec::new(); for codon in sequence_chunks.iter() { match *codon { "AUG" => polypeptide.push("Methionine"), "UUU" | "UUC" => polypeptide.push("Phenylalanine"), "UUA" | "UUG" => polypeptide.push("Leucine"), "UCU" | "UCC" | "UCA" | "UCG" => polypeptide.push("Serine"), "UAU" | "UAC" => polypeptide.push("Tyrosine"), "UGU" | "UGC" => polypeptide.push("Cysteine"), "UGG" => polypeptide.push("Tryptophan"), "UAA" | "UAG" | "UGA" => break, _ => break, } } polypeptide } fn proteins(rna: &str) -> Vec<&str> { let chunks = nucleotide_sequence(rna); let sequence = codon_translation(chunks); sequence }
{ "domain": "codereview.stackexchange", "id": 44233, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, unit-testing, rust, vectors", "url": null }
strings, unit-testing, rust, vectors #[test] fn test_nucleotide_sequence() { let data = [ ( "AUG", vec!["AUG"], "RNA has one codon (nucleotide sequence)", ), ( "AUGUUUUCU", vec!["AUG", "UUU", "UCU"], "RNA has three codons", ), ( "XY", vec![], "RNA cannot be broken into 3 nucleotide sequences", ), ("", vec![], "RNA doesn't exist; no codons can be formed ..."), ]; for (rna, codon_chunks, description) in data { assert_eq!(nucleotide_sequence(rna), codon_chunks, "{}", description) } } #[test] fn test_codon_translation() { let data = [ ( vec!["UUU", "UUU"], vec!["Phenylalanine", "Phenylalanine"], "Codon 'UUUUUU' translates to RNA sequence ['Phenylalanine', 'Phenylalanine']" ), ( vec!["AUG", "UUU", "UGG"], vec!["Methionine", "Phenylalanine", "Tryptophan"], "Codon 'AUGUUUUGG' translates to RNA sequence ['Methionine', 'Phenylalanine', 'Tryptophan']" ), ( vec!["UAG", "UGG"], vec![], "First codon corresponds to STOP, so others are not taken into consideration" ), ( vec!["UGG", "UAG"], vec!["Tryptophan"], "Codon 'UGGUAG' correponds to only 'Tryptophan'"), ( vec!["UGG", "UGU", "UAU", "UAA", "UGG", "UUU"], vec!["Tryptophan", "Cysteine", "Tyrosine"], "Codon corresponding to STOP is in the middle, whihch makes the RNA sequence '['Tryptophan', 'Cysteine', 'Tyrosine']" ), ( vec!["ABC", "XYZ"], vec![], "Invalid codon, no matching polypeptides found ...", ), ]; for (codon_chunks, protein, description) in data { assert_eq!(codon_translation(codon_chunks), protein, "{}", description); } }
{ "domain": "codereview.stackexchange", "id": 44233, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, unit-testing, rust, vectors", "url": null }
strings, unit-testing, rust, vectors #[test] fn test_proteins() { let data = [ ( "AUGUUUUCU", vec!["Methionine", "Phenylalanine", "Serine"], "RNA 'AUGUUUUCU' translates to proteins 'Methionine', 'Phenylalanine', 'Serine'", ), ( "AUGUUUUCUUAAAUG", vec!["Methionine", "Phenylalanine", "Serine"], "RNA 'AUGUUUUCUUAAAUG' translates to proteins 'Methionine', 'Phenylalanine', 'Serine'", ), ]; for (codons, polypeptides, description) in data { assert_eq!(proteins(codons), polypeptides, "{}", description); } } I'm executing this program as a test binary: rustc --test protein_translation.rs --verbose -o protein_translation_test.exe .\protein_translation_test.exe My approach while learning Rust has been to practice test-driven development, write idiomatic code, and (re)learn common programming concepts correctly. Is there a better way of breaking down the functionality of protein, solving this problem, or writing tests? Answer: Good call on splitting that function, it helps with readability. At a higher level, it appears you are not yet familiar with iterators, and this problem would benefit a lot from some iterator goodness. Why is the codon translation in a loop? It would be more natural to extract the actual translation to its own function. I'd also advise creating a proper enum to describe the codon (with their own string translation); but for now I'll just adjust the lifetime of the result to be 'static: fn translate_codon(codon: &str) -> Option<&'static str> { match codon { "AUG" => Some("Methionine"), "UUU" | "UUC" => Some("Phenylalanine"), "UUA" | "UUG" => Some("Leucine"), "UCU" | "UCC" | "UCA" | "UCG" => Some("Serine"), "UAU" | "UAC" => Some("Tyrosine"), "UGU" | "UGC" => Some("Cysteine"), "UGG" => Some("Tryptophan"), _ => None, } }
{ "domain": "codereview.stackexchange", "id": 44233, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, unit-testing, rust, vectors", "url": null }
strings, unit-testing, rust, vectors Then, we can alter nucleotide_sequence to prepare an iterator of sequences, instead of a vector: fn sequence_nucleotides(rna: &str) -> impl Iterator<Item = &str> { rna.as_bytes() .chunks_exact(3) .map(|bytes| std::str::from_utf8(bytes).expect("Valid UTF-8")) } Note: impl Iterator<...> in return position means that this function returns "something" which implements the Iterator trait, without specifying its exact type. And finally, we can pull it together in: fn proteins(rna: &str) -> impl Iterator<Item = &str> { sequence_nucleotide(rna) .map_while(|codon| translate_codon(nucleotide)) } And that's it. Simple, ain't it? The key thing here is to postpone materialization for as long as possible. Iterators are very flexible, with plenty of built-in functionality, and a number of extension crates for more, which is a good reason in itself, but avoiding materialization also means avoiding memory allocations, which is another very good reason. The second thing is that it is best to split-up "logic" functions (which do the computations) and "orchestrator" functions (which tie things together), in general. Notably to test them separately. It helps that Iterators provide a lot of "orchestrator" functionality -- such as map_while, which maps until the first None then cuts things short -- and thus using them you can focus on "logic". This also helps readers because the orchestration functions provided by Iterators are widely known, and therefore users don't have to decrypt the intent of your custom-built orchestration, remaining in chartered waters so to speak, and can focus on the logic.
{ "domain": "codereview.stackexchange", "id": 44233, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, unit-testing, rust, vectors", "url": null }
performance, c, parsing, chess Title: Chess position representation with FEN parser Question: I'm developing a UCI chess engine and as part of my engine I need a position representation that stores the position of every piece on the board and all the information about the game, like castling rights, en passant square, etc. The standard way of representing a chess position in a human readable format is the Forsyth–Edwards Notation (FEN), which is also used in the UCI protocol and takes the following form: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 The first part is the piece placement, following by the side to move, castling rights (if any), en passant square (if any), halfmove clock, and finally the fullmove counter. Here is the FEN grammar according to the Chess Programming Wiki: <FEN> ::= <Piece Placement> ' ' <Side to move> ' ' <Castling ability> ' ' <En passant target square> ' ' <Halfmove clock> ' ' <Fullmove counter> <Piece Placement> ::= <rank8>'/'<rank7>'/'<rank6>'/'<rank5>'/'<rank4>'/'<rank3>'/'<rank2>'/'<rank1> <ranki> ::= [<digit17>]<piece> {[<digit17>]<piece>} [<digit17>] | '8' <piece> ::= <white Piece> | <black Piece> <digit17> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' <white Piece> ::= 'P' | 'N' | 'B' | 'R' | 'Q' | 'K' <black Piece> ::= 'p' | 'n' | 'b' | 'r' | 'q' | 'k' <Side to move> ::= {'w' | 'b'} <Castling ability> ::= '-' | ['K'] ['Q'] ['k'] ['q'] (1..4) <En passant target square> ::= '-' | <epsquare> <epsquare> ::= <fileLetter> <eprank> <fileLetter> ::= 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' <eprank> ::= '3' | '6' <Halfmove Clock> ::= <digit> {<digit>} <digit> ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' <Fullmove counter> ::= <digit19> {<digit>} <digit19> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' <digit> ::= '0' | <digit19>
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess Also, since this is part of a chess engine, the position representation must be small for cache performance, and the operations like moving pieces, getting castling rights, etc, must be fast because the position is modified in a recursive function that searches for the best next move. Here's the code for pos.c: #include <ctype.h> #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <check.h> #include "pos.h"
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess /* * The piece placement is stored in two formats, in piece-centric bitboard * arrays and in a square-centric array. * * In the piece-centric format there are two arrays, one indexed by the color * and one indexed by the piece type, both storing bitboards where the set bits * represent a piece of that color or type at a square, where the square is * counted from the least significant bit to the most significant bit, from 0 * to 63. The bitboards store pieces using a Little-Endian Rank-File mapping * (LERF), which means each byte, from the least significant byte to the most * significant byte represent a rank, and each bit of these bytes represent a * square on that rank. Which means that A1 is square 0, H1 is square 7, A2 is * square 8, H2 is square 15 and so on. * * The square-centric format is just a flat array indexed by the square number * in a LERF mapping and each element of the array is a piece, or PIECE_NONE if * the square is empty. * * The castling rights are stored in a nibble, the 2 least significant bits are * for white and the next 2 bits for black, the least significant and most * significant bits of each are for the queen and king sides respectively. A * set bit means that the king has the right to castle. Notice that having * right to castle does not mean that castling really is possible * (castling ability), it only means that neither the king nor the rook * corresponding to the castling side have moved throughout the game. In order * for castling to be possible, the following conditions must be met: * - The side must have castling rights; * - There are no pieces between the king and rook; * - The king will not be in check after castling. * * The en passant square is not stored, but instead only its file. This is to * save space, since it is possible to recover the square by using the color of * the side to move. Because there are only 8 files the file is stored in just
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess * the side to move. Because there are only 8 files the file is stored in just * the 3 least significant bits of a nibble and the most significant bit of the * nibble is set when there is an en passant square and unset otherwise. Since * both the castling rights and en passant file are stored in a nibble, I * stored both together in one byte. * * Because changes to some of the position data can't be undone, like the * castling ability (if the rook moves back and forth there's no way to know * that it happened later on), all this irreversibe state is stored in a stack * where the top is the current state and to undo a move one only has to pop * the last irreversible state off the stack and undo the changes to the * reversibe data. */
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess struct irreversible_state { u8 castling_rights_and_enpassant; u8 halfmove_clock; u8 captured_piece; struct irreversible_state *previous; }; struct position { struct irreversible_state *irreversible; u8 side_to_move; short fullmove_counter; u64 color_bb[2]; u64 type_bb[6]; Piece board[64]; }; static size_t parse_fen(Position *pos, const char *fen); static size_t parse_fullmove_counter(Position *pos, const char *str); static size_t parse_halfmove_clock(Position *pos, const char *str); static size_t parse_enpassant(Position *pos, const char *str); static size_t parse_castling(Position *pos, const char *str); static size_t parse_side(Position *pos, const char *str); static size_t parse_pieces(Position *pos, const char *str); static int is_one_of(const char *str, char ch); static char *trim(char *str); static int get_index_of_first_bit(u64 n); static int count_bits(u64 n); int main(int argc, char **argv) { if (argc > 1) { if (!strlen(argv[1])) { fprintf(stderr, "FEN not provided.\n"); return EXIT_FAILURE; } Position *pos = pos_create(trim(argv[1])); if (!pos) { fprintf(stderr, "Invalid FEN.\n"); return EXIT_FAILURE; } pos_print(pos); pos_destroy(pos); } else { fprintf(stderr, "FEN not provided.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } void pos_print(const Position *pos) { const char piece_table[] = { [PIECE_TYPE_PAWN ] = 'p', [PIECE_TYPE_KNIGHT] = 'n', [PIECE_TYPE_ROOK ] = 'r', [PIECE_TYPE_BISHOP] = 'b', [PIECE_TYPE_QUEEN] = 'q', [PIECE_TYPE_KING ] = 'k', }; Rank rank = RANK_8; File file = FILE_A; for (rank = RANK_8, file = FILE_A; file <= FILE_H || rank > RANK_1;) { if (file > FILE_H) { --rank; file = FILE_A; putchar('\n'); }
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess Square sq = pos_file_rank_to_square(file, rank); Piece piece = pos_get_piece_at(pos, sq); char ch = '\0'; if (piece == PIECE_NONE) { ch = '0'; } else { PieceType piece_type = pos_get_piece_type(piece); Color color = pos_get_piece_color(piece); ch = piece_table[piece_type]; if (color == COLOR_WHITE) ch = toupper(ch); } printf("%c ", ch); ++file; } printf("\n\n"); Color color = pos_get_side_to_move(pos); if (color == COLOR_WHITE) printf("Turn: white\n"); else printf("Turn: black\n"); printf("En passant: "); if (pos_enpassant_possible(pos)) { Square sq = pos_get_enpassant(pos); file = pos_get_file_of_square(sq); rank = pos_get_rank_of_square(sq); printf("%c%d\n", file + 'A', rank + 1); } else { printf("-\n"); } printf("Castling rights: "); if (pos_has_castling_right(pos, COLOR_WHITE, CASTLING_SIDE_KING)) putchar('K'); if (pos_has_castling_right(pos, COLOR_WHITE, CASTLING_SIDE_QUEEN)) putchar('Q'); if (pos_has_castling_right(pos, COLOR_BLACK, CASTLING_SIDE_KING)) putchar('k'); if (pos_has_castling_right(pos, COLOR_BLACK, CASTLING_SIDE_QUEEN)) putchar('q'); printf("\n"); printf("Halfmove clock: %d\n", pos_get_halfmove_clock(pos)); printf("Fullmove counter: %d\n", pos_get_fullmove_counter(pos)); } void pos_decrement_fullmove_counter(Position *pos) { --pos->fullmove_counter; } void pos_increment_fullmove_counter(Position *pos) { ++pos->fullmove_counter; } void pos_remove_castling(Position *pos, Color c, CastlingSide side) { pos->irreversible->castling_rights_and_enpassant &= ~(1 << side << 2 * c); }
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess void pos_add_castling(Position *pos, Color c, CastlingSide side) { pos->irreversible->castling_rights_and_enpassant |= 1 << side << 2 * c; } void pos_flip_side_to_move(Position *pos) { if (pos->side_to_move == COLOR_WHITE) pos->side_to_move = COLOR_BLACK; else pos->side_to_move = COLOR_WHITE; } void pos_set_captured_piece(Position *pos, Piece piece) { pos->irreversible->captured_piece = piece; } /* * Remove a piece from a square. */ void pos_remove_piece(Position *pos, Square sq) { const Piece piece = pos_get_piece_at(pos, sq); const u64 bb = U64(0x1) << sq; pos->color_bb[pos_get_piece_color(piece)] &= ~bb; pos->type_bb[pos_get_piece_type(piece)] &= ~bb; pos->board[sq] = PIECE_NONE; } /* * Place a piece at a square, if another piece is at this square, it will be * removed first. * * There's an important detail about this function. The bitboards are stored in * a piece centric format, so we can't just overwrite the old piece with the * new one if the pieces are of different types, the bitboard of the piece * being replaced would still store the piece as if it's still on the board, * because only the new piece's board would be modified. Because of that, the * old piece must be removed first with the pos_remove_piece function by the * caller. The reason why this is not done here is to avoid slowing down code * that places a piece in an empty square. */ void pos_place_piece(Position *pos, Square sq, Piece piece) { const u64 bb = U64(0x1) << sq; if (pos->board[sq] != PIECE_NONE) pos_remove_piece(pos, sq); pos->color_bb[pos_get_piece_color(piece)] |= bb; pos->type_bb[pos_get_piece_type(piece)] |= bb; pos->board[sq] = piece; } void pos_reset_halfmove_clock(Position *pos) { pos->irreversible->halfmove_clock = 0; } void pos_increment_halfmove_clock(Position *pos) { ++pos->irreversible->halfmove_clock; }
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess void pos_increment_halfmove_clock(Position *pos) { ++pos->irreversible->halfmove_clock; } void pos_unset_enpassant(Position *pos) { pos->irreversible->castling_rights_and_enpassant &= 0xf; } /* * Set the possibility of en passant and store the file. */ void pos_set_enpassant(Position *pos, File file) { pos->irreversible->castling_rights_and_enpassant &= 0x8f; pos->irreversible->castling_rights_and_enpassant |= 0x80; pos->irreversible->castling_rights_and_enpassant |= (file & 0x7) << 4; } Piece pos_get_captured_piece(const Position *pos) { return pos->irreversible->captured_piece; } int pos_has_castling_right(const Position *pos, Color c, CastlingSide side) { return (pos->irreversible->castling_rights_and_enpassant & 0x1 << side << 2 * c) != 0; } int pos_get_fullmove_counter(const Position *pos) { return pos->fullmove_counter; } int pos_get_halfmove_clock(const Position *pos) { return pos->irreversible->halfmove_clock; } int pos_enpassant_possible(const Position *pos) { return pos->irreversible->castling_rights_and_enpassant & 0x80; } Square pos_get_enpassant(const Position *pos) { const File f = (pos->irreversible->castling_rights_and_enpassant & 0x70) >> 4; const Rank r = pos->side_to_move == COLOR_WHITE ? RANK_6 : RANK_3; return pos_file_rank_to_square(f, r); } Color pos_get_side_to_move(const Position *pos) { return pos->side_to_move; } Square pos_get_king_square(const Position *pos, Color c) { const Piece piece = pos_make_piece(PIECE_TYPE_KING, c); const u64 bb = pos_get_piece_bitboard(pos, piece); return get_index_of_first_bit(bb); } Piece pos_get_piece_at(const Position *pos, Square sq) { return pos->board[sq]; } int pos_get_number_of_pieces(const Position *pos, Piece piece) { const u64 bb = pos_get_piece_bitboard(pos, piece); return count_bits(bb); }
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess return count_bits(bb); } u64 pos_get_piece_bitboard(const Position *pos, Piece piece) { const PieceType type = pos_get_piece_type(piece); const Color color = pos_get_piece_color(piece); const u64 bb = pos->type_bb[type] & pos->color_bb[color]; return bb; } u64 pos_get_color_bitboard(const Position *pos, Color c) { return pos->color_bb[c]; } void pos_backtrack_irreversible_state(Position *pos) { struct irreversible_state *const current = pos->irreversible; pos->irreversible = pos->irreversible->previous; free(current); } /* * This function must be called before externally calling any function that * modifies the irreversible state of the position. * * It creates a new copy of the old irreversible state and pushes * it onto the stack, making it the current one. The reversible state is * preserved since changes can be undone. */ void pos_start_new_irreversible_state(Position *pos) { struct irreversible_state *current = pos->irreversible; struct irreversible_state *new = malloc(sizeof(*new)); if (!new) { fprintf(stderr, "Could not allocate memory.\n"); exit(1); } memcpy(new, current, sizeof(struct irreversible_state)); new->previous = current; pos->irreversible = new; }
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess /* * Create a new position using FEN. It returns NULL if the FEN is invalid. It is * assumed that the string it not empty and that there are no leading or trailing * white spaces. Keep in mind that whether the position is actually valid * according to the rules of chess is not checked, so even if the FEN string is a * valid FEN string according to the grammar, the position might be illegal. For * example, the number of pawns in the board is not checked, so it is possible to * set up a position using a FEN string that describes a board with 9 pawns. This * is intentional, as the user might want to set up a non-standard board. */ Position *pos_create(const char *fen) { Position *pos = malloc(sizeof(Position)); if (!pos) { fprintf(stderr, "Could not allocate memory.\n"); exit(1); } pos->irreversible = malloc(sizeof(struct irreversible_state)); if (!pos->irreversible) { fprintf(stderr, "Could not allocate memory.\n"); exit(1); } pos->fullmove_counter = 0; pos->irreversible->previous = NULL; pos->irreversible->captured_piece = PIECE_NONE; pos_reset_halfmove_clock(pos); pos_unset_enpassant(pos); pos_remove_castling(pos, COLOR_WHITE, CASTLING_SIDE_KING); pos_remove_castling(pos, COLOR_WHITE, CASTLING_SIDE_QUEEN); pos_remove_castling(pos, COLOR_BLACK, CASTLING_SIDE_KING); pos_remove_castling(pos, COLOR_BLACK, CASTLING_SIDE_QUEEN); for (Square sq = A1; sq <= H8; ++sq) pos->board[sq] = PIECE_NONE; for (size_t i = 0; i < 6; ++i) pos->type_bb[i] = 0; for (size_t i = 0; i < 2; ++i) pos->color_bb[i] = 0; size_t rc = parse_fen(pos, fen); if (rc != strlen(fen)) { pos_destroy(pos); return NULL; } return pos; } void pos_destroy(Position *pos) { struct irreversible_state *prev = NULL;
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess void pos_destroy(Position *pos) { struct irreversible_state *prev = NULL; for (struct irreversible_state *p = pos->irreversible; p; p = prev) { prev = p->previous; free(p); } free(pos); } Square pos_file_rank_to_square(File f, Rank r) { return 8 * r + f; } File pos_get_file_of_square(Square sq) { return sq % 8; } Rank pos_get_rank_of_square(Square sq) { return sq / 8; } Color pos_get_piece_color(Piece piece) { return piece & 0x1; } PieceType pos_get_piece_type(Piece piece) { return piece >> 1; } Piece pos_make_piece(PieceType pt, Color c) { return pt << 1 | c; } /* * Modifies a position by parsing a FEN string and returns the number of * characters read, if it's less than the length then an error ocurred. Each of * the parse_* functions return the number of characters that were read, and if * the sequence of characters is invalid they return 0. */ static size_t parse_fen(Position *pos, const char *fen) { size_t (*const steps[])(Position *, const char *) = { parse_pieces, parse_side, parse_castling, parse_enpassant, parse_halfmove_clock, parse_fullmove_counter, }; const size_t num_steps = sizeof(steps) / sizeof(steps[0]); size_t rc = 0, ret = 0; for (size_t i = 0; i < num_steps; ++i) { ret = steps[i](pos, fen); if (!ret) return 0; fen += ret; rc += ret; if (i < num_steps - 1) { if (fen[0] != ' ') return 0; else ++rc; } ++fen; } return rc; }
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess return rc; } /* * Both the parse_fullmove_counter and parse_halfmove_clock functions parse the * number up to the first invalid character (a character that is not part of a * number). So the functions will not fail because of the space character after * the number in the FEN string. */ static size_t parse_fullmove_counter(Position *pos, const char *str) { char *endptr = NULL; errno = 0; unsigned long counter = strtoul(str, &endptr, 10); if (errno == ERANGE) return 0; else if (endptr == str) return 0; else if (counter > SHRT_MAX) return 0; pos->fullmove_counter = (short)counter; return endptr - str; } static size_t parse_halfmove_clock(Position *pos, const char *str) { char *endptr = NULL; errno = 0; unsigned long clock = strtoul(str, &endptr, 10); if (errno == ERANGE) return 0; else if (endptr == str) return 0; else if (clock > SHRT_MAX) return 0; pos->irreversible->halfmove_clock = (u8)clock; return endptr - str; } static size_t parse_enpassant(Position *pos, const char *str) { if (str[0] == '-') return 1; if (!str[0] || !str[1]) return 0; else if (str[0] < 'a' || str[0] > 'h' || (str[1] != '3' && str[1] != '6')) return 0; File file = str[0] - 'a'; pos_set_enpassant(pos, file); return 2; }
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess static size_t parse_castling(Position *pos, const char *str) { if (str[0] == '-') return 1; int Kcnt = 0, Qcnt = 0, kcnt = 0, qcnt = 0; size_t rc = 0; for (; str[rc] && str[rc] != ' '; ++rc) { switch (str[rc]) { case 'K': pos_add_castling(pos, COLOR_WHITE, CASTLING_SIDE_KING); ++Kcnt; break; case 'Q': pos_add_castling(pos, COLOR_WHITE, CASTLING_SIDE_QUEEN); ++Qcnt; break; case 'k': pos_add_castling(pos, COLOR_BLACK, CASTLING_SIDE_KING); ++kcnt; break; case 'q': pos_add_castling(pos, COLOR_BLACK, CASTLING_SIDE_QUEEN); ++qcnt; break; default: return 0; } if (Kcnt > 1 || Qcnt > 1 || kcnt > 1 || qcnt > 1) return 0; } return rc; } static size_t parse_side(Position *pos, const char *str) { switch (str[0]) { case 'w': pos->side_to_move = COLOR_WHITE; break; case 'b': pos->side_to_move = COLOR_BLACK; break; default: return 0; } return 1; } static size_t parse_pieces(Position *pos, const char *str) { const Piece table[] = { ['P'] = PIECE_WHITE_PAWN, ['p'] = PIECE_BLACK_PAWN, ['N'] = PIECE_WHITE_KNIGHT, ['n'] = PIECE_BLACK_KNIGHT, ['R'] = PIECE_WHITE_ROOK, ['r'] = PIECE_BLACK_ROOK, ['B'] = PIECE_WHITE_BISHOP, ['b'] = PIECE_BLACK_BISHOP, ['Q'] = PIECE_WHITE_QUEEN, ['q'] = PIECE_BLACK_QUEEN, ['K'] = PIECE_WHITE_KING, ['k'] = PIECE_BLACK_KING, }; size_t rc = 0; File file = FILE_A; Rank rank = RANK_8; for (size_t i = 0; file <= FILE_H || rank > RANK_1; ++i) { if (!str[i]) return 0; char ch = str[i]; ++rc;
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess if (file > FILE_H) { if (str[i] && str[i] != '/') return 0; --rank; file = FILE_A; continue; } if (isdigit(ch)) { int digit = ch - '0'; if (digit > 8 || digit < 1 || !digit || file + digit > 8) return 0; file += digit; } else if (is_one_of("PNRBQKpnrbqk", ch)) { Piece piece = table[(size_t)ch]; Square sq = pos_file_rank_to_square(file, rank); pos_place_piece(pos, sq, piece); ++file; } else { return 0; } } return rc; } /* * Check if ch is one of the characters in str, where str is a string containing * all characters to be checked and not separated by space. * For example: * is_one_of("ar4h", 'r') * returns 1, but * is_one_of("r57g", '9') * returns 0. */ static int is_one_of(const char *str, char ch) { if (!ch || !strchr(str, ch)) return 0; return 1; } static char *trim(char *str) { char *end; while (isspace(*str)) ++str; if (!*str) return str; end = str + strlen(str) - 1; while (end > str && isspace(*end)) --end; end[1] = '\0'; return str; } static int get_index_of_first_bit(u64 n) { #if defined(__clang__) || defined(__GNUC__) return __builtin_ffsll(n) - 1; #else static const int index[64] = { 0, 47, 1, 56, 48, 27, 2, 60, 57, 49, 41, 37, 28, 16, 3, 61, 54, 58, 35, 52, 50, 42, 21, 44, 38, 32, 29, 23, 17, 11, 4, 62, 46, 55, 26, 59, 40, 36, 15, 53, 34, 51, 20, 43, 31, 22, 10, 45, 25, 39, 14, 33, 19, 30, 9, 24, 13, 18, 8, 12, 7, 6, 5, 63, }; static const u64 debruijn = U64(0x03f79d71b4cb0a89); return index[((n ^ (n - 1)) * debruijn) >> 58]; #endif }
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess return index[((n ^ (n - 1)) * debruijn) >> 58]; #endif } static int count_bits(u64 n) { #if defined(__clang__) || defined(__GNUC__) return __builtin_popcountll(n); #else static const u64 m1 = 0x5555555555555555; static const u64 m2 = 0x3333333333333333; static const u64 m4 = 0x0f0f0f0f0f0f0f0f; static const u64 m8 = 0x00ff00ff00ff00ff; static const u64 m16 = 0x0000ffff0000ffff; static const u64 m32 = 0x00000000ffffffff; static const u64 h01 = 0x0101010101010101; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; #endif } And here's the code for pos.h: #ifndef POSITION_H #define POSITION_H #define U64(n) n##ull typedef uint64_t u64; typedef uint8_t u8; typedef enum direction { NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST, } Direction; typedef enum file { FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H, } File; typedef enum rank { RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8, } Rank; typedef enum square { A1, B1, C1, D1, E1, F1, G1, H1, A2, B2, C2, D2, E2, F2, G2, H2, A3, B3, C3, D3, E3, F3, G3, H3, A4, B4, C4, D4, E4, F4, G4, H4, A5, B5, C5, D5, E5, F5, G5, H5, A6, B6, C6, D6, E6, F6, G6, H6, A7, B7, C7, D7, E7, F7, G7, H7, A8, B8, C8, D8, E8, F8, G8, H8, } Square; /* * It's safe to get the opposite color with the ! operator on the color. */ typedef enum color { COLOR_WHITE, COLOR_BLACK, } Color; typedef enum piece_type { PIECE_TYPE_PAWN, PIECE_TYPE_KNIGHT, PIECE_TYPE_ROOK, PIECE_TYPE_BISHOP, PIECE_TYPE_QUEEN, PIECE_TYPE_KING, } PieceType;
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess typedef enum piece { PIECE_WHITE_PAWN = COLOR_WHITE | PIECE_TYPE_PAWN << 1, PIECE_WHITE_KNIGHT = COLOR_WHITE | PIECE_TYPE_KNIGHT << 1, PIECE_WHITE_ROOK = COLOR_WHITE | PIECE_TYPE_ROOK << 1, PIECE_WHITE_BISHOP = COLOR_WHITE | PIECE_TYPE_BISHOP << 1, PIECE_WHITE_QUEEN = COLOR_WHITE | PIECE_TYPE_QUEEN << 1, PIECE_WHITE_KING = COLOR_WHITE | PIECE_TYPE_KING << 1, PIECE_BLACK_PAWN = COLOR_BLACK | PIECE_TYPE_PAWN << 1, PIECE_BLACK_KNIGHT = COLOR_BLACK | PIECE_TYPE_KNIGHT << 1, PIECE_BLACK_ROOK = COLOR_BLACK | PIECE_TYPE_ROOK << 1, PIECE_BLACK_BISHOP = COLOR_BLACK | PIECE_TYPE_BISHOP << 1, PIECE_BLACK_QUEEN = COLOR_BLACK | PIECE_TYPE_QUEEN << 1, PIECE_BLACK_KING = COLOR_BLACK | PIECE_TYPE_KING << 1, PIECE_NONE = 0xff /* Only used for the array board. */ } Piece; typedef enum castling_side { CASTLING_SIDE_QUEEN, CASTLING_SIDE_KING, } CastlingSide; struct position; typedef struct position Position;
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess struct position; typedef struct position Position; void pos_print(const Position *pos); void pos_decrement_fullmove_counter(Position *pos); void pos_increment_fullmove_counter(Position *pos); void pos_remove_castling(Position *pos, Color c, CastlingSide side); void pos_add_castling(Position *pos, Color c, CastlingSide side); void pos_flip_side_to_move(Position *pos); void pos_set_captured_piece(Position *pos, Piece piece); void pos_remove_piece(Position *pos, Square sq); void pos_place_piece(Position *pos, Square sq, Piece piece); void pos_reset_halfmove_clock(Position *pos); void pos_increment_halfmove_clock(Position *pos); void pos_unset_enpassant(Position *pos); void pos_set_enpassant(Position *pos, File file); Piece pos_get_captured_piece(const Position *pos); int pos_has_castling_right(const Position *pos, Color c, CastlingSide side); int pos_get_fullmove_counter(const Position *pos); int pos_get_halfmove_clock(const Position *pos); int pos_enpassant_possible(const Position *pos); Square pos_get_enpassant(const Position *pos); Color pos_get_side_to_move(const Position *pos); Square pos_get_king_square(const Position *pos, Color c); Piece pos_get_piece_at(const Position *pos, Square sq); int pos_get_number_of_pieces(const Position *pos, Piece piece); u64 pos_get_piece_bitboard(const Position *pos, Piece piece); u64 pos_get_color_bitboard(const Position *pos, Color c); void pos_backtrack_irreversible_state(Position *pos); void pos_start_new_irreversible_state(Position *pos); Position *pos_create(const char *fen); void pos_destroy(Position *pos); Square pos_file_rank_to_square(File f, Rank r); File pos_get_file_of_square(Square sq); Rank pos_get_rank_of_square(Square sq); Color pos_get_piece_color(Piece piece); PieceType pos_get_piece_type(Piece piece); Piece pos_make_piece(PieceType pt, Color c); #endif
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess #endif I added that main function just to have an output, it is not part of the final program, and the get_index_of_first_bit and count_bits functions along with the type definitions of u8 and u64 are supposed to be part of another file, I added them to pos.c just to avoid adding another file to the question. If you run this program on a terminal with a FEN string as the first argument the output should look like this: r n b q k b n r p p p p p p p p 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 P P P P P P P P R N B Q K B N R Turn: white En passant: - Castling rights: KQkq Halfmove clock: 0 Fullmove counter: 1 This is the output for the input string "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1". If no input is provided or the string is not a valid FEN string the program will complain. I want some feedback on the correctness of the code, the board representation and the looks of the code in general, while keeping in mind that the code was written for performance. Note that the FEN parser does not need to be fast since it's only run once when the chess GUI sends a command for setting a position to the engine.
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess Answer: Doc review It is possible code takes some of these issues into account. What if rook has not moved but is not there With "it only means that neither the king nor the rook corresponding to the castling side have moved throughout the game", a rook should be considered moved if it is taken, even if from its original square. Else one could castle with the ghost rook since it never moved. 50 move rule FEN lacks info indicating the last time a piece taken or pawn advanced. 3 repetitions FEN lacks info needed for check of the possible outcomes repeating 3 times. For this and the pervious 50-move concern, a collection of prior and current FEN lines would be enough to record the state. One FEN is not enough to house the state. Castling Needs 2 more: The king is not in check when attempting to castle. The king will not move across check. Stalemate and others What if the side lacks a legal move? What if the FEN state is invalid due to position? (castling flag OK yet no rook, en pass with no pawn, white to move yet no piece.) How much error checking is desired?
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess Code review Good use of const Good use of pop prefix Could de more. pop.h creates many named items like NORTH, FILE_A, A1, Square, Color, etc. that may conflict with other code. Consider a more universal use of pop prefix. Good use of sizeof Use standard names u8, u64 may be useful to quickly code, yet lack the clarity of uint8_t, uint64_t. Use the standard. Avoid assuming unsigned long long and uint64_t are the same unsigned long long is common today as uint64_t yet is specified to be at least 64-bit. Rather than make unsigned long long constants with #define U64(n) n##ull, use the standard UINT64_C(value) from <stdint.h>. Allocate to the referenced object, not type Consider the 2 below. Which do you find easier to code, review and maintain? Which one requires coder to correctly sync type and object? pos->irreversible = malloc(sizeof(struct irreversible_state)); // vs. pos->irreversible = malloc(sizeof pos->irreversible[0]); Magic numbers Why 6? for (size_t i = 0; i < 6; ++i) pos->type_bb[i] = 0; Instead: size_t n = sizeof type_bb / sizeof type_bb[0]; for (size_t i = 0; i < n; ++i) pos->type_bb[i] = 0; Or simply memset(pos->type_bb, sizeof pos->type_bb, 0); Style: Why hex? Surprising use of 0x. // return piece & 0x1; return piece & 1; Style: () Even after years of C, code like pt << 1 | c cause me to pause and review those precedence rules. Consider (pt << 1) | c for code that otherwise relies on the less common precedence rules. Style: {} Even for 1 line blocks, consider {}. //if (!ret) // return 0; if (!ret) { return 0; }
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
performance, c, parsing, chess Documentation The various static functions lack documentation. Pedantic: is...(negative) if (isdigit(ch)) is UB when ch < 0 (and not EOF). Use unsigned char ch. enum size Note that Piece board[64]; may be wider than 64-bytes as enum piece, which only needs 8-bits, may be wider. Use uint8_t board[64] if reduced size is important. Speed vs. space Do not assume smaller memory footprint is faster - often it is the other way around. In general, use minimal width objects when an array of them is needed. Otherwise use int, unsigned, double and then wider as needed. For a balance of speed vs. space, consider dropping the bit dibbling of castling, en passant and use struct members. Yet use uint8_t board[64]. short? Little reason for short // short fullmove_counter int fullmove_counter Non-standard board support Hmm, with more than 2 rooks, 1 king, I see a need for more than 2 castling flags.
{ "domain": "codereview.stackexchange", "id": 44234, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, parsing, chess", "url": null }
c++ Title: How could you make this UUID generator more efficient? Question: I just coded the implementation of a UUID generator in C++ after the definition from Wikipedia. I am intermediate in C++ programming and don't know all the tricks and best practices for this language. Any suggestions are welcome! PS: I am also not sure how to display the char array as a hex string, like in 123e4567-e89b-12d3-a456-426614174000 // UUIDGenerator.cpp : Defines the functions for the static library. // #include "pch.h" #include "framework.h" const char* generateUUID() { char uuid[16]; auto now = std::chrono::system_clock::now(); auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now); auto epoch = now_ms.time_since_epoch(); auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch); long duration = value.count(); unsigned int time_low = duration & 0xFFFFFFFF; unsigned short int time_mid = (duration >> 32) & 0xFFFF; // UUID Version 1 unsigned short int time_hi_and_version = (duration >> 48) & 0xFFF | 0x1000; // UUID Variant 1 unsigned short int clock_seq_hi_and_res = (duration >> 60) & 0x7FF | 0xa000; // Just some random 48 bit number instead of the MAC address unsigned long int node = 0x23F8E9B5550A; uuid[0] = time_low & 0xFF; uuid[1] = (time_low >> 8) & 0xFF; uuid[2] = (time_low >> 16) & 0xFF; uuid[3] = (time_low >> 24) & 0xFF; uuid[4] = time_mid & 0xFF; uuid[5] = (time_mid >> 8) & 0xFF; uuid[6] = time_hi_and_version & 0xFF; uuid[7] = (time_hi_and_version >> 8) & 0xFF; uuid[8] = clock_seq_hi_and_res & 0xFF; uuid[9] = (clock_seq_hi_and_res >> 8) & 0xFF; uuid[10] = node & 0xFF; uuid[11] = (node >> 8) & 0xFF; uuid[12] = (node >> 16) & 0xFF; uuid[13] = (node >> 24) & 0xFF; uuid[14] = (node >> 32) & 0xFF; uuid[15] = (node >> 40) & 0xFF; return uuid; }
{ "domain": "codereview.stackexchange", "id": 44235, "lm_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++", "url": null }
c++ return uuid; } I have tried to include the library in the project I write this for, but it didn't work. Answer: I have tried to include the library in the project I write this for, but it didn't work. You didn't specify what happens when you try to use it, but I would guess that the problem is that you're declaring the uuid array as a local variable so it becomes invalid when it goes out of scope of scope and using that array is undefined behavior. What actually happens in the end is platform dependent, but usually the local variable is stored in the function's stack-frame and when the function returns this stack-frame "destroyed" and that stack space will be used by other functions that are called, and they might overwrite the memory where uuid was. You can return uuid by allocating memory for it with new, but the way I recommend doing it is to make the function receive an array as argument and write to it. You should also use std::uint8_t defined in cstdint instead of char because char is defined as 1 byte, but there are obscure platforms where 1 byte is not 8 bits, and std::uint8_t is guaranteed to be 8 bits. Though, if you think your code is never going to be used on those platforms, you shouldn't worry about that, it's reasonable to consider 1 byte as 8 bits. But another problem with char is that the standard does not define if it is signed or unsigned, so char may be equivalent to signed char instead of unsigned char, which isn't what you want when you're dealing with bits. I am also not sure how to display the char array as a hex string You can do it with std::hex: int main() { std::uint8_t uuid[16]{};
{ "domain": "codereview.stackexchange", "id": 44235, "lm_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++", "url": null }
c++ You can do it with std::hex: int main() { std::uint8_t uuid[16]{}; generateUUID(uuid); size_t n = 0; for (size_t i: {4, 2, 2, 2, 6}) { for (size_t j = n; j < n + i; ++j) std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast<unsigned>(uuid[j]); if (i == 6) std::cout << std::endl; else std::cout << '-'; n += i; } } It's calling generateUUID with an argument like I recommended and using std::setw to set the width of the output (2 characters for each byte) and std::setfill to set the fill character when the byte doesn't use 2 characters. I cast uuid[j] to avoid having the byte interpreted as a char How could you make this UUID generator more efficient? By more efficient you mean significantly faster? I don't think you can, at least not in a way I can think of. I tried doing it with AVX on x86 but the code ended up having to do a lot more operations. Speaking of, you don't need the & operator in those assignments to uuid because the elements of uuid are 8 bits so the values will be truncated and only 8 bits will be used. So you can do this: uuid[0] = time_low; uuid[1] = time_low >> 8; uuid[2] = time_low >> 16; uuid[3] = time_low >> 24; uuid[4] = time_mid; uuid[5] = time_mid >> 8; uuid[6] = time_hi_and_version; uuid[7] = time_hi_and_version >> 8; uuid[8] = clock_seq_hi_and_res; uuid[9] = clock_seq_hi_and_res >> 8; uuid[10] = node; uuid[11] = node >> 8; uuid[12] = node >> 16; uuid[13] = node >> 24; uuid[14] = node >> 32; uuid[15] = node >> 40;
{ "domain": "codereview.stackexchange", "id": 44235, "lm_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++", "url": null }
python, python-3.x, database, websocket Title: How to structure in handling websocket and inserting data to databse in Python Question: I connected to the websocket, and the data response in the callback function handle_message. I wish to insert all the data to influxdb using write_api.write(), since I need with InfluxClient() to wrap the whole CRUD function, I wrote like this: from time import sleep from pybit import usdt_perpetual from dataclasses import dataclass from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS @dataclass class Trade: tick_direction: str side: float is_block_trade: str price: float size: float timestamp: int ws_linear = usdt_perpetual.WebSocket( test=False, ping_interval=30, ping_timeout=10, domain="bybit" ) with InfluxDBClient( url="http://localhost:8086", token="fake_token_id", org="organization") as client: write_api = client.write_api(write_options=SYNCHRONOUS) def handle_message(msg: dict) -> None: for data in msg["data"]: trade = Trade(data["tick_direction"], data["side"], data["is_block_trade"], float(data["price"]), float(data["size"]), data["timestamp"]) write_api.write(bucket="test5", record=trade, record_measurement_name="tradeBTCUSDT", record_time_key="timestamp", record_tag_keys=["tick_direction", "side", "is_block_trade"], record_field_keys=["price", "size"]) ws_linear.trade_stream( handle_message, "BTCUSDT" ) while True: sleep(1) I think it is messy that I wrap handle_message by with InfluxClient, how can I improve it and the overall structure of the program? Answer: I find it unlikely this program works as expected. You have written approximately:
{ "domain": "codereview.stackexchange", "id": 44236, "lm_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, database, websocket", "url": null }
python, python-3.x, database, websocket Answer: I find it unlikely this program works as expected. You have written approximately: Open a database connection, & assign that to client Get write_api from client Define a function which (at some point in the future) uses write_api Call client.close() due to the exit of the with statement! Ask another function to handle messages by calling your defined function which uses an api on a “now closed” client! As you can see, the with statement is not doing anything but giving you a false sense of security. You need to either: open a new database connection inside handle_message, or indent the subsequent code such that client is not closed until after your while True: loop exits (presumably by a KeyboardInterrupt) Here is a toy demonstration of the issue: class Client: def __init__(self): self.opened = False def __enter__(self): self.opened = True print("Client opened") return self def __exit__(self, *args): self.opened = False print("Client closed") def write_api(self): return WriteApi(self) class WriteApi(): def __init__(self, client): self.client = client def use_api(self): print("Using API. Client open =", self.client.opened) def trade_stream(handler): handler(None) print("About to enter with-statement") with Client() as client: print("Entered with-statement") write_api = client.write_api() def handle_message(msg): write_api.use_api() print("Exiting with-statement") print("Exited with-statement") trade_stream(handle_message) Output: About to enter with-statement Client opened Entered with-statement Exiting with-statement Client closed Exited with-statement Using API. Client open = False Note that using the API happens after the client has been closed. So why do you appear to have working code? From the documentation ... from influxdb_client import InfluxDBClient
{ "domain": "codereview.stackexchange", "id": 44236, "lm_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, database, websocket", "url": null }
python, python-3.x, database, websocket # Initialize background batching instance of WriteApi with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: with client.write_api() as write_api: pass ... it appears client.write_api() returns an object which itself can behave as a context manager, and so should be used in a with-statement. If the write_api is "open", and then the client is closed, whether or not the write_api is invalid will depend on how the library is written. It may internally hold the client open, until the write_api is explicitly closed (which you are not doing), or it may be Undefined Behaviour and might appear to work at the moment, and start failing in the future. As stated earlier, the fix could be to indent the subsequent code, as in: with InfluxDBClient( url="http://localhost:8086", token="fake_token_id", org="organization") as client: write_api = client.write_api(write_options=SYNCHRONOUS) def handle_message(msg: dict) -> None: ... # still indented, so still inside the `with client` ws_linear.trade_stream( handle_message, "BTCUSDT" ) # still indented, so still inside the `with client` while True: sleep(1) # with statement ends here # client will be closed here
{ "domain": "codereview.stackexchange", "id": 44236, "lm_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, database, websocket", "url": null }
c++, object-oriented Title: CRUD for array of Objects Question: I'm trying a simple exercise where I want to Generate Solar Systems, and store them on an array for ease of iteration and accessability. I've create the following classes: class System { private: std::string m_Name; unsigned int m_ID; //... load system data from file. public: System() {}; System(unsigned int ID, std::string name) : m_Name(name), m_ID(ID) { std::cout << "Generated System" << std::endl; }; ~System() {}; const inline std::string GetSystemName() { return m_Name; } }; Then I created the class SystemArray to group all the systems under the same galaxy. class SystemArray { private: std::map<unsigned int, System> m_Systems {}; std::string m_Name; unsigned int m_SystemCount = 0; public: SystemArray(std::string name) : m_Name(name) { System defaultSystem(m_SystemCount,"DEFAULT"); m_Systems[m_SystemCount] = defaultSystem; m_SystemCount++; } ~SystemArray() {}; void CreateNewSystem(std::string name) { System newSystem(m_SystemCount,name); m_Systems[m_SystemCount] = newSystem; m_SystemCount++; } std::string GetSystemName(unsigned int systemID) { if(m_Systems.count(systemID) > 0) { return m_Systems[systemID].GetSystemName(); }; return "Unable to get name"; } const inline std::map<unsigned int,System> GetSystemArray() { return m_Systems; } }; Now I'm trying to access my systems via the Array, which is fine: SystemArray newGalaxy("Milky Way"); newGalaxy.CreateNewSystem("Sol"); newGalaxy.CreateNewSystem("Tol"); newGalaxy.CreateNewSystem("Foo"); for(auto [key, value ] : newGalaxy.GetSystemArray()) { std::cout << key << ": " << value.GetSystemName() << std::endl; }
{ "domain": "codereview.stackexchange", "id": 44237, "lm_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++, object-oriented", "url": null }
c++, object-oriented Now I'm developing the API to be able to edit the values of the systems inside the SystemArray. And here starts my problem. I'm acessing the Systems via the SystemArray so I need to create the functions inside the System and then replicate them on the System Array, copying the values around. I'm stuck here, since my poor knowledge to design this is failling me. For example editing the System Name: Class System added: inline bool ChangeSystemName(std::string newName) { m_Name = newName;} Class SystemArray added: void ChangeSystemName(unsigned int systemID,std::string newName) { std::string oldName = GetSystemName(systemID); if(m_Systems[systemID].ChangeSystemName(newName)) { std::cout << "Name of system: " << oldName << " changed to: " << GetSystemName(systemID) << std::endl; } } Is this the correct way to handle this? Are there any other options? Answer: Missing headers I needed to add these includes: #include <iostream> #include <map> #include <string>
{ "domain": "codereview.stackexchange", "id": 44237, "lm_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++, object-oriented", "url": null }
c++, object-oriented Uninitialised members The default constructor of System leaves both m_Name and m_ID uninitialised, which is dangerous. Does it make any sense to default-construct a solar system? I would just remove that constructor. We'll need to change how we add to maps, of course, so as not to need default-construction. Use std::move() to construct members Instead of initialising mn_Name by copy-constructing from name, note that we don't use name afterwards. So we can initialise using m_Name{std::move(name)}, reducing the amount of copying going on. Pointless destructors The empty destructors could be written = default, but simpler still is to not write them at all. The compiler-generated destructors will do the same, but better. Unnecessary flushing We use a std::endl in a lot of places where there's no need to flush output buffers. These can all be replaced by plain newline. Unused member m_ID is never used, so we don't need to store it. Wrong stream The tracing output from the constructor looks like it should be sent to the standard log stream std::clog rather than to standard output. Naming SystemArray is a bit misleading, because it doesn't represent an array. I'd give it a name that shows what it's for, such as Galaxy. On a related note, "system" is a highly-overloaded term in software, so I'd rename that to SolarSystem. Don't return constant objects There's no need to return a constant string from GetSystemName(); there's no reason that callers shouldn't be able to do what they like with their copy. We could return a reference to constant string or a mutable string. However, we should treat the System object as constant in this function. Also, let the compiler choose which functions to inline - they usually make better choices than humans. Simplify creation of SystemArray We can initialise the std::map with its first member: private: std::string m_Name; std::map<unsigned int, SolarSystem> m_Systems; unsigned int m_SystemCount = 1;
{ "domain": "codereview.stackexchange", "id": 44237, "lm_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++, object-oriented", "url": null }
c++, object-oriented public: SystemArray(std::string name) : m_Name{std::move(name)}, m_Systems{{0, {0, "DEFAULT"}}} { } Choose containers wisely I really can't see why we're using a std::map and then populating it sequentially. That looks much better suited to a std::vector. And we don't need m_SystemCount, because that's always the same as the collection's size. Improved code #include <string> #include <utility> #include <vector> class SolarSystem { std::string m_name; unsigned int m_id; public: SolarSystem(unsigned int id, std::string name) : m_name{std::move(name)}, m_id{id} { std::clog << "Generated SolarSystem\n"; }; std::string name() const { return m_name; } unsigned id() const { return m_id; } }; class Galaxy { std::string m_Name; std::vector<SolarSystem> m_Systems; public: Galaxy(std::string name) : m_Name{std::move(name)}, m_Systems{{0, "DEFAULT"}} { } void create(std::string name) { m_Systems.emplace_back(m_Systems.size(), name); } std::string name(unsigned int systemID) const { if (systemID >= m_Systems.size()) { return "Unable to get name"; } return m_Systems[systemID].name(); } auto begin() const { return m_Systems.begin(); } auto end() const { return m_Systems.end(); } }; int main() { Galaxy newGalaxy("Milky Way"); newGalaxy.create("Sol"); newGalaxy.create("Tol"); newGalaxy.create("Foo"); for(auto const& s: newGalaxy) { std::cout << s.id() << ": " << s.name() << "\n"; } }
{ "domain": "codereview.stackexchange", "id": 44237, "lm_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++, object-oriented", "url": null }
c++, object-oriented for(auto const& s: newGalaxy) { std::cout << s.id() << ": " << s.name() << "\n"; } } Adding the rename functionality Now let's look at how we change a name. We don't need to involve Galaxy in this at all, if it's able to give use a reference to a solar system - we just get that reference and change it ourselves: class SolarSystem { ⋮ public: void set_name(std::string name) { m_name = std::move(name); } }; class Galaxy { ⋮ public: auto& operator[](unsigned int id) { return m_Systems[id]; } } Completed code #include <iostream> #include <string> #include <utility> #include <vector> class SolarSystem { std::string m_name; unsigned int m_id; public: SolarSystem(unsigned int id, std::string name) : m_name{std::move(name)}, m_id{id} { std::clog << "Generated SolarSystem\n"; }; std::string name() const { return m_name; } unsigned id() const { return m_id; } void set_name(std::string name) { m_name = std::move(name); } }; class Galaxy { std::string m_Name; std::vector<SolarSystem> m_Systems; public: Galaxy(std::string name) : m_Name{std::move(name)}, m_Systems{{0, "DEFAULT"}} { } void create(std::string name) { m_Systems.emplace_back(m_Systems.size(), name); } auto& operator[](unsigned int id) { return m_Systems[id]; } std::string name(unsigned int systemID) const { if (systemID >= m_Systems.size()) { return "Unable to get name"; } return m_Systems[systemID].name(); } auto begin() const { return m_Systems.begin(); } auto end() const { return m_Systems.end(); } }; int main() { Galaxy newGalaxy("Milky Way"); newGalaxy.create("Sol"); newGalaxy.create("Tol"); newGalaxy.create("Foo");
{ "domain": "codereview.stackexchange", "id": 44237, "lm_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++, object-oriented", "url": null }
c++, object-oriented newGalaxy[0].set_name("Kol"); for(auto const& s: newGalaxy) { std::cout << s.id() << ": " << s.name() << "\n"; } }
{ "domain": "codereview.stackexchange", "id": 44237, "lm_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++, object-oriented", "url": null }
c#, beginner, console Title: Choose item from list Question: I wrote small console application where you can choose an item from given list of strings. Works fine so far but since I am beginner I have some questions if I am doing this right. My biggest concerns are if I should use fields here or properties, if I am using the static keyword correctly, if I should use the fields in the methods directly (like I am doing it now) or I should pass them as parameters. In future this class I want to use in multiple places so it makes sense to be static I think. If you have suggestions on some other parts also please comment. ConsoleSelectMenu.cs: namespace ConsoleApp { class ConsoleSelectMenu { static int selectedLineIndex = 0; static ConsoleKey pressedKey; static bool readyToSelectUp = true; static bool readyToSelectDown = true; static bool haveWeStarted = false; public static string DrawSelectMenu(SelectMenuOptions options) { Console.WriteLine(options.Question); do { UpdateMenu(options.Choices); pressedKey = Console.ReadKey().Key; Console.Write("\b \b"); readyToSelectUp = pressedKey == ConsoleKey.DownArrow && selectedLineIndex + 1 < options.Choices.Count; readyToSelectDown = pressedKey == ConsoleKey.UpArrow && selectedLineIndex - 1 >= 0; if (readyToSelectUp) selectedLineIndex++; else if (readyToSelectDown) selectedLineIndex--; } while (pressedKey != ConsoleKey.Enter); return options.Choices[selectedLineIndex]; } private static void UpdateMenu(List<string> list) { if (!readyToSelectUp && !readyToSelectDown) return; if (haveWeStarted) ClearList(list);
{ "domain": "codereview.stackexchange", "id": 44238, "lm_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#, beginner, console", "url": null }
c#, beginner, console foreach (var item in list) { bool isSelected = item == list[selectedLineIndex]; Console.WriteLine($"{(isSelected ? "> " : " ")}{item}"); } haveWeStarted = true; } private static void ClearList(List<string> list) { for (int i = 0; i < list.Count; i++) { int currentLineCursor = Console.CursorTop; Console.SetCursorPosition(0, Console.CursorTop - (i + 1)); Console.Write(new string(' ', Console.WindowWidth)); Console.SetCursorPosition(0, currentLineCursor); } Console.SetCursorPosition(0, Console.CursorTop - list.Count); } } public class SelectMenuOptions { public string Question { get; set; } public List<string> Choices { get; set; } } } Programs.cs var options = new SelectMenuOptions { Question = "Please choose an option", Choices = new List<string>() { "Opt_1", "Opt_2", "Opt_3" } }; var result = ConsoleSelectMenu.DrawSelectMenu(options); Console.WriteLine(result); Answer: Firstly, about fields vs. properties: properties are methods in disguise - they allow you to use logic when changing a variable. Personally, I would almost always use the standard Property property { get; set; } so it's faster to customize the way to read and update a property - unless we want the property to be private. Secondly, and more importantly, I wouldn't make DrawSelectMenu a static class. The reason for that is when you make a class static, you no longer get the benefits of abstraction, and Dependency Injection. Instead, I would create the following abstract class: internal abstract class SelectMenu { public string Title { get; set; } = ""; public List<Option> Options { get; set; } = new List<Option>(); public Option? SelectedOption { get; set; }
{ "domain": "codereview.stackexchange", "id": 44238, "lm_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#, beginner, console", "url": null }
c#, beginner, console public SelectMenu(string title, List<Option> options) { this.Title = title; this.Options = options; } public abstract void Display(); public void SelectPrevious() { if (this.SelectedOption != null) { int indexOfSelected = this.Options.IndexOf(this.SelectedOption); if (indexOfSelected != -1) this.SelectedOption = this.Options.ElementAt(Modulus((indexOfSelected - 1), this.Options.Count)); } } public void SelectNext() { if (this.SelectedOption != null) { int indexOfSelected = this.Options.IndexOf(this.SelectedOption); if (indexOfSelected != -1) this.SelectedOption = this.Options.ElementAt(Mod((indexOfSelected + 1), this.Options.Count)); } } private static int Modulus(int a, int b) { return (Math.Abs(a * b) + a) % b; } } And then, I would create the following derived class: internal class ConsoleSelectMenu : SelectMenu { public ConsoleSelectMenu(string title, List<Option> options) : base(title, options) { this.SelectedOption = this.Options[0]; } public override void Display() { Console.Clear(); this.Options.ForEach((option) => Console.WriteLine(this.GetPrefix(option) + option.Name)); } private string GetPrefix(Option option) { return this.SelectedOption == option ? "> " : " "; } } And so Program.cs main function becomes: var options = new List<Option>() { new Option { Name = "opt 1" }, new Option { Name = "opt 2" }, new Option { Name = "opt 3" } }; string title = "Please choose an option"; SelectMenu selectMenu = new ConsoleSelectMenu(title, options); while (true) { selectMenu.Display(); var key = Console.ReadKey().Key;
{ "domain": "codereview.stackexchange", "id": 44238, "lm_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#, beginner, console", "url": null }
c#, beginner, console while (true) { selectMenu.Display(); var key = Console.ReadKey().Key; if (key == ConsoleKey.UpArrow) selectMenu.SelectPrevious(); else if (key == ConsoleKey.DownArrow) selectMenu.SelectNext(); else if (key == ConsoleKey.Enter) break; } Console.WriteLine(selectMenu?.SelectedOption?.Name); And that solution allows flexibility; if we'd want, for example, a WindowSelectMenu, we could simply create a class that implements the required methods, and just replace the type of SelectMenu when we create it: SelectMenu selectMenu = WindowSelectMenu(title, options) We can also refactor the user input handling, and create a generic system for handling input and dispatching events (for example, an OnEnterKeyPressed event). Thirdly, you can still use a class even if it's not static; you just need to pass a reference to the instance or create a new one. For example: public Option petOwnershipSurvey() { SelectMenu selectMenu = ConsoleSelectMenu("Do you own a pet", new List<Option>() { new Option { Name = "Yes" }, new Option { Name = "No" }, new Option { Name = "I don't know" }}); selectMenu.Display(); /* insert here a code that gets input from the user */ return selectMenu.SelectedOption; } here's the Option class I created: internal class Option { public string Name { get; set; } = ""; public string Description { get; set; } = ""; } Also, please note that I haven't addressed all edge cases in my code in order to focus on what's relevant to the question.
{ "domain": "codereview.stackexchange", "id": 44238, "lm_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#, beginner, console", "url": null }
c++, c++14, casting Title: An explicit cast for narrowing numeric conversions Question: Inspired by gsl::narrow_cast, I created my own implementation with the addition of a couple of features: a static assert on the types to ensure the cast is actually narrowing (if future changes to the code mean the cast is no longer narrowing, we don't want to still have a narrow_cast there) the version without a runtime check still has an assert, so it's checked in debug mode #include <cassert> #include <exception> #include <iostream> #include <type_traits> namespace details { template <typename T, typename U> constexpr bool is_same_signedness = std::is_signed<T>::value == std::is_signed<U>::value; template <typename T, typename U> constexpr bool can_fully_represent = std::is_same<T, U>::value || ( std::is_integral<T>::value && std::is_integral<U>::value && ( ( std::is_signed<T>::value && sizeof(T) > sizeof(U) ) || ( is_same_signedness<T, U> && sizeof(T) >= sizeof(U) ) ) ) || ( std::is_floating_point<T>::value && std::is_floating_point<U>::value && sizeof(T) >= sizeof(U) ); template <typename T, typename U> constexpr bool static_cast_changes_value(U u) noexcept { const auto t = static_cast<T>(u); // this should catch most cases, but may miss dodgy unsigned to signed conversion or vice-versa if (static_cast<U>(t) != u) return true; if (std::is_signed<T>::value != std::is_signed<U>::value && ((t < T{}) != (u < U{}))) return true; return false; } } // namespace details // TODO: unchecked cast for types where some loss of precision (and therefore assertion failure) is expected? template <typename T, typename U> constexpr T narrow_cast(U&& u) noexcept { static_assert(!details::can_fully_represent<T, U>, "we shouldn't be using narrow_cast for casts that aren't actually narrowing"); assert(!details::static_cast_changes_value<T>(u)); return static_cast<T>(std::forward<U>(u)); }
{ "domain": "codereview.stackexchange", "id": 44239, "lm_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++, c++14, casting", "url": null }
c++, c++14, casting struct narrowing_error : public std::exception {}; template <typename T, typename U> constexpr T narrow_cast_checked(U u) { static_assert(!details::can_fully_represent<T, U>, "we shouldn't be using narrow_cast for casts that aren't actually narrowing"); if (details::static_cast_changes_value<T>(u)) throw narrowing_error(); return static_cast<T>(u); } Answer: The first thing I noticed: you only support basic arithmetic types (integral and floating point). This isn't apparent from the name narrow_cast. Either enforce this with a static assert, or provide a mechanism to provide extensions for user defined types. Here's what you write: template <typename T, typename U> constexpr bool can_fully_represent = std::is_same<T, U>::value || ( std::is_integral<T>::value && std::is_integral<U>::value && ( ( std::is_signed<T>::value && sizeof(T) > sizeof(U) ) || ( is_same_signedness<T, U> && sizeof(T) >= sizeof(U) ) ) ) || ( std::is_floating_point<T>::value && std::is_floating_point<U>::value && sizeof(T) >= sizeof(U) ); Here's what I think should be sufficient: template <typename T, typename U> constexpr bool can_fully_represent = std::numeric_limits<T>::min() <= std::numeric_limits<U>::min() && std::numeric_limits<T>::max() >= std::numeric_limits<U>::max(); OK, maybe I overlooked some edge cases, but that's the idea. The unchecked version uses a forwarding reference, whereas the check version does not. Try to keep the interface consistent. std::is_same<T, U>::value can be simplified to std::is_same_v<T, U>.
{ "domain": "codereview.stackexchange", "id": 44239, "lm_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++, c++14, casting", "url": null }
c++, c++20 Title: Draw a histogram of the characters in input Question: It's sometimes fun to implement the exercises from K&R in C++. It's certainly interesting to see what C++ makes easier and what's still difficult. I've had a go at Exercise 1-14 in the second edition: Exercise 1-14. Write a program to print a histogram of the frequencies of different characters in its input. The extra challenge from 1-13 also applies here: It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging. I also chose to make my histogram bars logarithmic. My code looks fairly slick for gathering the data, but I wasn't very satisfied with the output half: // A program to print a histogram of the frequencies of different // characters in its input. K&R(2) exercise 1-14. #include <algorithm> #include <cctype> #include <cmath> #include <cstddef> #include <iostream> #include <iomanip> #include <iterator> #include <map> #include <ranges> template<typename T> using counter = std::map<T, std::size_t>; static bool isprint(char c) { return std::isprint(static_cast<unsigned char>(c)); } int main() { auto hist = counter<char>{}; std::ranges::for_each(std::istreambuf_iterator<char>{std::cin}, std::istreambuf_iterator<char>{}, [&hist](char c){ ++hist[c]; }); auto const keys = hist | std::views::keys; auto const values = hist | std::views::values; auto const max_val = std::ranges::max(values); // width of the scale column unsigned count_width = static_cast<unsigned>(std::ceil(std::log10(max_val))); // scale to fit a 24-line display (but just assume it's wide enough) auto constexpr rows = 23u; auto const scale = std::log(static_cast<double>(max_val - 1)) / rows;
{ "domain": "codereview.stackexchange", "id": 44240, "lm_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++, c++20", "url": null }
c++, c++20 std::cout << std::fixed << std::setprecision(0); for (auto i = rows; i; --i) { // scale bar auto const threshold = static_cast<std::size_t>(std::exp(i * scale)); std::cout << std::setw(count_width); if (i % 2 == rows % 2) { std::cout << threshold; } else { std::cout << ""; } std::cout << '|'; // character columns for (auto v: values) { std::cout << (v >= threshold ? '*' : ' '); } std::cout << '\n'; } // histogram key std::cout << std::setw(count_width + 1) << '|'; for (auto k: keys) { std::cout << (isprint(k) ? k : ' '); } }
{ "domain": "codereview.stackexchange", "id": 44240, "lm_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++, c++20", "url": null }
c++, c++20 When fed its own source code, it produces this output: 406| * | * 241| * | * 143| * | * * 84| * ** | * * * * * * ** 50|** * * *** * * *** |** * * * *** * ** **** 29|** * * * *** * * ** **** |** ** *** * *** ** * ** **** 17|** ** *** * * *** ** **** **** |** ** * ***** ** ******* ***** **** 10|** *** * ***** ** ******* ***** ****** * * |** * *** * ***** ** ******* ***** ******* * * 6|** * *** * ***** ** ************* ******** * * |** * *** * * ** ***** **************** ******** *** 3|** * *** *** * ** ***** **************** ******** *** |****************** ******* ** ***************** ************ 2|****************** ******* ** ***************** ************ |************************************************************** 1|************************************************************** | "#%&'()*+,-./01234:;<=>?AKRT[\]_abcdefghiklmnopqrstuvwxyz{|} N.B. The C++20 library support in GCC 11 is not sufficiently complete for this, so GCC 12 is required (or any other compiler with good C++20 support).
{ "domain": "codereview.stackexchange", "id": 44240, "lm_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++, c++20", "url": null }
c++, c++20 Answer: That's some surprisingly compact but still very readable code! Very good use of C++20's ranges. Casting numbers You are performing several explicit casts. While I don't think there is anything wrong with them, one is at least unnecessary: std::log() and many other math functions have overloads that take integers, and will cast to double automatically for you. So you don't have to do that yourself. You use auto foo = static_cast<sometype>(somevalue) in many places, which is good, but you didn't do this for count_width, where you specified the type twice. This is a bit dangerous, as if the two types don't match you will might have an undesirable implicit cast happening. Also, since you use count_width as an argument for std::set(), which takes an int, it might be better have it be an int itself: const auto count_width = static_cast<int>(std::ceil(std::log10(max_val))); Use a std::array while counting When counting how many times each character occurs, a std::map is inefficient. Since you know there are only UCHAR_MAX + 1 possible characters, you can create a std::array of that size. This avoids expensive lookups every time you want to update a counter. After counting you can consider either converting the result into a std::map, or just iterating over the std::array and ignoring any element that has a count of zero. The latter would make your code a bit more complicated, although you could probably still do it with ranges. While a std::views::enumerate would have been very helpful, you can still do things in C++20 like: std::array<std::size_t, UCHAR_MAX + 1> hist{}; std::ranges::for_each(std::istreambuf_iterator<char>{std::cin}, std::istreambuf_iterator<char>{}, [&hist](char c){ ++hist[static_cast<unsigned char>(c)]; }); auto values = hist | std::views::filter([](auto count){ return count != 0; });
{ "domain": "codereview.stackexchange", "id": 44240, "lm_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++, c++20", "url": null }
c++, c++20 auto values = hist | std::views::filter([](auto count){ return count != 0; }); for (auto& value: values) { auto key = static_cast<char>(&value - &hist[0]); std::cout << key << ": " << value << "\n"; } You could create some helper functions to make that look less hacky. Split the code into multiple functions You can split main() into a function that calculates the histogram and one that prints it. Missing newline Your program doesn't print a newline after the histogram key. Infinite loop when the input is empty Your program goes into an infinite loop when the input is completely empty. This is caused by applying std::ranges::max() to an empty view. I think the solution is just to check if hist.empty() right after the for_each(), and quit the program if that returns true. Incorrect output when every count is 1 When every character in the input occurs exactly once, then count_width is zero, which causes every other line of the output to be shifted by one. The simple solution is just to add a std::max(1u, ...) to the calculation of count_width. y-axis count is off by one The y-axis only shows the maximum count minus 1. This is because you literally subtract 1 from max_val when calculating scale, not because of floating point imprecision, although the latter is something you should worry about as well. Instead of subtracting 1, I would just add 0.5 to max_val when calculating scale. Consider using std::format() Since your code relies on C++20, you could consider using std::format() (or {fmt} if your standard library doesn't support it yet); it makes aligning text much easier. For example: for (auto i = rows; i; --i) { auto const threshold = static_cast<std::size_t>(std::exp(i * scale)); if ((i - rows) % 2) std::cout << fmt::format("{:{}}|", "", count_width); else std::cout << fmt::format("{:{}}|", threshold, count_width); for (auto v: values) { std::cout << (v >= threshold ? '*' : ' '); std::cout << '\n'; }
{ "domain": "codereview.stackexchange", "id": 44240, "lm_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++, c++20", "url": null }
c++, c++20 With C++23, you can even format ranges. This would allow you to do something like: for (auto i = rows; i; --i) { auto const threshold = static_cast<std::size_t>(std::exp(i * scale)); std::print("{:{}}|{::s}\n", threshold, count_width, values | std::views::transform([threshold](auto v){ return v >= threshold ? '*' : ' '; } ); }
{ "domain": "codereview.stackexchange", "id": 44240, "lm_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++, c++20", "url": null }
c, strings Title: Resizable string object Question: #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct String { char* string; long long unsigned capacity; // uint32_t had trouble printing long long unsigned len; } String; String string_new(char* stuff) { int len = strlen(stuff); String ret = { stuff, len, len, }; return ret; } void string_push(String* s, char push) { if(s->len <= s->capacity) { s->capacity *= 2; char* new_stuff = calloc(sizeof(char), s->capacity); memcpy(new_stuff, s->string, s->capacity); s->string = new_stuff; } s->len += 1; s->string[s->len-1] = push; } int main(void) { String hello = string_new(""); char* text = "Hello, World!"; // because c treats integers as booleans, i could easily obfuscate this to just `text[i]` but i // chose readability over code size. for(int i = 0; text[i] != '\0'; i++) { string_push(&hello, text[i]); puts(hello.string); } return 0; } I'm a complete beginner to the C programming language, so any feedback would be appreciated. From what I've heard, implementing vectors involves: create: allocate some memory push: allocate more memory, place previous string in new memory pop: decrement length Answer: In principle this is the right approach, however there are some issues:
{ "domain": "codereview.stackexchange", "id": 44241, "lm_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, strings", "url": null }
c, strings In string_new you need to allocate/duplicate memory. This is because your String assumes ownership of the string data buffer, so you cannot store a pointer wich is passed by argument into the field string. I would suggest a strdup(stuff) here. Because of the null termination character capacity would also be `len+1``. You need to check for memory allocation failure (return value of NULL) from the realloc/ calloc call in string_push and the strdup in in string_new. You need to decide what to do on failure, e.g. return a flag indicating the status or even terminating the program. string_push is missing a free of the old buffer. string_push is not wrong (apart from not checking return value and not freeing buffer) but I would prefer using realloc as it is more efficient and shorter: new_string = realloc(s->string, s->capacity) and after error checking assign s->string = new_string. This will enlarge the buffer if possible and avoid the copy or if a new buffer had to be allocated, includes the memcpy and frees old buffer. Probably you want to include more functions such as string_cat which concatenates a whole string as repeatedly calling string_push is inefficient. Also a deallocation would be needed like string_free. Of course this is not strictly wrong, but needs to be included for proper design, I would say.
{ "domain": "codereview.stackexchange", "id": 44241, "lm_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, strings", "url": null }
c, strings You should also be aware that your type of string is different from the nullterminated strings in C. You have an explicit length field, which theoretically allows having a \0 character in the string. Also your string is not necessarily including a null termination character. So you cannot pass your string to standard library string functions, including e.g. printf, and puts. While string_new ensures that a null termination char is included, this is not the case for string_push. I would suggest that string push always writes a null termination character as well, so that you can actually pass the string to standard library string functions. (Please be careful to get the len & capacity logic correct in this case).
{ "domain": "codereview.stackexchange", "id": 44241, "lm_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, strings", "url": null }
algorithm, c, hash-map Title: Implementation of Hash Function in C language Question: I'm new to programming. and I'm learning a C language. Currently working on Harvard's CS50 problem set (this one: https://cs50.harvard.edu/x/2022/psets/5/speller/). In that problem, they want us to store every word in dictionary inside Hash Table. In which we need a Hash Function to access the table. So, I'm trying to figure out how to write a hash function. And what I do is: I want to store each word by using their first three letter as a bucket (or keys?) in a Table (Table is an array). Explanation: N = 17576 Table[N] // Each index position in a Table Array act as first three letter in alphabetical order [0] : Aaa | [1] : Aab ... [25] : Aaz [676] : Baa | [677] : Bab ... [701] : Baz Example storing a Name: Hermione [4853] : Her = Hermione So this is the code I wrote to get what I want. This code is run successfully for that CS50 problem. And give me fast enough running time when execute it. Code: // Hashes word to a number unsigned int hash(const char *word) { /* Hash Function that uses first three letter in word as a bucket number in a Table Store in a table in which each bucket start with the first three letter in word ex: Hermione | [Her] = Hermione F = (l1 * 676) + (l2 * 26) + l3 l1: H (72) - (65) A = 7 l2: E (69) - (65) A = 4 l3: R (82) - (65) A = 17 F = (7 * 676 ) + (4 * 26) + 17 = 4732 + 104 + 17 = 4853 Hermione in bucket 4.853 in 17.576 Table */ int next_letter = 0; int l1 = 0, l2 = 0, l3 = 0;
{ "domain": "codereview.stackexchange", "id": 44242, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, hash-map", "url": null }
algorithm, c, hash-map int next_letter = 0; int l1 = 0, l2 = 0, l3 = 0; for (int i = 0, n = strlen(word); i < n; i++) { /* We need to check if letter in word may apostrophe, if that's the case go to next letter Ex: Ab's | [Abs] = Ab's a1: A | a2: b | a3: s We ignore apostrophe, go to next letter */ if (isalpha(word[i])) { // Get first letter in word // Actually no need to concern about apostrophe, every word in dictionary start with alphabet if (next_letter == 0) { // Get index postion of word by substract it with ASCII Code l1 = toupper(word[i]) - 'A'; // If we success get first word, it's time for second word next_letter++; } // Get second letter in word else if (next_letter == 1) { // Get index postion of word by substract it with ASCII Code l2 = toupper(word[i]) - 'A'; // If we success get second word, it's time for third word next_letter++; } // Get third letter in word else { // Get index postion of word by substract it with ASCII Code l3 = toupper(word[i]) - 'A'; // When found just break the loop since the third letter is end of it break; } } } // Get index number for a bucket using our Formula unsigned int index = (l1 * 676) + (l2 * 26) + l3; return index; } So what you guys think about my hash function? Is it good enough? or too complicated? or maybe there's a good hash function that I didn't know. Thank you. I hope you understand my explanation and have a time to review it.
{ "domain": "codereview.stackexchange", "id": 44242, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, hash-map", "url": null }
algorithm, c, hash-map Answer: Don't compute strlen(word)! A call to strlen is O(n) in time, where n is the length of the string. By calling this function you get overall time complexity comparable with a hash function that depends on all characters of the input. And so you loose the presumed performance gain of hashing only 3 letters. Just terminate the loop if you happen to encounter the \0 character. Use array for l1, l2, l3 You can simplify your code if you treat those 3 as an array. Don't create unnecessary variables only to return them on the next line Just return the expression. It's probably just a matter of preference, personally I'd even strip the unnecessary parenthesis. Seems much more readable, basically because there is much less to read... Use the pointer as iterator You get some small performance gain if you iterate over the word pointer rather then introducing integer iterator i. Guard against NULL pointer It may be wise to handle the case when word is NULL to avoid possible segmentation fault. Overuse of comments You don't have to comment on every line of your code. It creates disturbance and gets out of date easily. Describe all important about the function in the comment above the function. Add comments inside the implementation only when "why" is not obvious. The "how" is never needed in the comment because that's what you discover by reading the code. For example here // Get index postion of word by substract it with ASCII Code l2 = toupper(word[i]) - 'A'; The comment says the same as what the code does. If I were to write a comment for this line I would rather explain WHY toupper needs to be used there. But the info belongs to the main comment anyway... Modified code - Putting it all together: hash.c #include <ctype.h> #include "hash.h" #define MAX_HASHED_LETTERS 3 unsigned int hash(const char *word) { if (word == NULL) { return 0; } unsigned int L[MAX_HASHED_LETTERS] = {0, 0, 0}; unsigned int letter_index = 0;
{ "domain": "codereview.stackexchange", "id": 44242, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, hash-map", "url": null }
algorithm, c, hash-map unsigned int L[MAX_HASHED_LETTERS] = {0, 0, 0}; unsigned int letter_index = 0; for (char c = *word; c != '\0'; c = *(++word)) { if (isalpha(c)) { L[letter_index++] = toupper(c) - 'A'; if (letter_index == MAX_HASHED_LETTERS) { break; } } } return L[0] * 676 + L[1] * 26 + L[2]; } The macro MAX_HASHED_LETTERS is there to improve readability, but it should be private to the hash function. And so I placed it into the module hash.c while a forward declaration of the function should be placed in header file hash.h. hash.h #pragma once /** * Returns a hash of the word's first up to 3 "isalpha" characters. * The function is case-insensitive meaning the returned value is the same for any case variation of the input. * It returns 0 for NULL pointer, words that don't contain "isalpha" characters and words whose first up to 3 letters are all "a" or "A". * * Example: .... */ unsigned int hash(const char *word); Generalize In case it is needed we can generalize to be able to hash any number of first letters. We just need to get rid of the fixed size array L and compute the hash incrementally. Although this will probably overflow for larger n (which may not be a problem though). #define ALPHABET_SIZE ('Z' - 'A' + 1)
{ "domain": "codereview.stackexchange", "id": 44242, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, hash-map", "url": null }
algorithm, c, hash-map unsigned int hash_first_n_letters_ci(const char *word, unsigned int n) { if (word == NULL) { return 0; } unsigned int letter_index = 0; unsigned int hash = 0; for (char c = *word; c != '\0'; c = *(++word)) { if (isalpha(c)) { hash = hash * ALPHABET_SIZE + (toupper(c) - 'A'); if (++letter_index == n) { // skip the finalizing loop as all n letters were found and so the hash is already final return hash; } } } // finalize the hash if less then n letters were found for (; letter_index < n; ++letter_index) { hash *= ALPHABET_SIZE; } return hash; } unsigned int hash_first_3_letters_ci(const char *word) { return hash_first_n_letters_ci(word, 3); } Test your code It is good to add some tests to make sure everything works during refactoring. Actually it would be even better to write tests first. Let them fail. Then keep writing the implementation until all the tests succeed. Then improve the implementation while being sure everything still works. A simple test suite can be carried out using assert. #include <assert.h>
{ "domain": "codereview.stackexchange", "id": 44242, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, hash-map", "url": null }
algorithm, c, hash-map int main() { assert(hash_first_3_letters_ci(NULL) == 0); assert(hash_first_3_letters_ci("") == 0); assert(hash_first_3_letters_ci("a") == 0); assert(hash_first_3_letters_ci("aa") == 0); assert(hash_first_3_letters_ci("aaa") == 0); assert(hash_first_3_letters_ci("aaabcde") == 0); assert(hash_first_3_letters_ci("'a") == 0); assert(hash_first_3_letters_ci("'aa") == 0); assert(hash_first_3_letters_ci("'aaa") == 0); assert(hash_first_3_letters_ci("'aaabcde") == 0); assert(hash_first_3_letters_ci("A") == 0); assert(hash_first_3_letters_ci("AA") == 0); assert(hash_first_3_letters_ci("AAA") == 0); assert(hash_first_3_letters_ci("AAABCDE") == 0); assert(hash_first_3_letters_ci("'A") == 0); assert(hash_first_3_letters_ci("'AA") == 0); assert(hash_first_3_letters_ci("'AAA") == 0); assert(hash_first_3_letters_ci("'AAABCDE") == 0); assert(hash_first_3_letters_ci("aab") == 1); assert(hash_first_3_letters_ci("AAB") == 1); assert(hash_first_3_letters_ci("aabbbbb") == 1); assert(hash_first_3_letters_ci("AABBBBB") == 1); assert(hash_first_3_letters_ci("'aab") == 1); assert(hash_first_3_letters_ci("'AAB") == 1); assert(hash_first_3_letters_ci("'aabbbbb") == 1); assert(hash_first_3_letters_ci("'AABBBBB") == 1); assert(hash_first_3_letters_ci("aba") == 26); assert(hash_first_3_letters_ci("ababcd") == 26); assert(hash_first_3_letters_ci("ABA") == 26); assert(hash_first_3_letters_ci("ABABCD") == 26); assert(hash_first_3_letters_ci("a'ba") == 26); assert(hash_first_3_letters_ci("a'babcd") == 26); assert(hash_first_3_letters_ci("A'BA") == 26); assert(hash_first_3_letters_ci("A'BABCD") == 26); assert(hash_first_3_letters_ci("b") == 676); assert(hash_first_3_letters_ci("B") == 676); assert(hash_first_3_letters_ci("ba") == 676); assert(hash_first_3_letters_ci("BA") == 676);
{ "domain": "codereview.stackexchange", "id": 44242, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, hash-map", "url": null }