text
stringlengths
1
2.12k
source
dict
bash, linux, networking You can read pair of variables without additional awk processes for every line of input, like this: while read -r programname path rest; do # ... done read can read multiple values separated by whitespace, and stores all excess values in the last variable (here rest). Unhelpful error message In this code: if is_in_array "$package_manager" "${dpkg_equivalents[@]}" && dpkg --version &>/dev/null; then package_manager="dpkg" elif is_in_array "$package_manager" "${rpm_equivalents[@]}" && rpm --version &>/dev/null; then package_manager="rpm" else fatal "No supported package manager found! Try specifying one with -p --package-manager" fi It seems to me that the error message is not helpful. When a package manager is not specified, the if-else chain will try to use dpkg or rpm if possible. If not possible, then I don't see what value a user could possibly set that will not result in the failure. I think you need to rethink the logic of this validation, and either tell the user that their system is not supported (and why), or make the message more specific to be helpful. Use consistent style Some functions are using modern style, for example fatal() { ... }, while others use old style, for example function is_in_array { ... }. Use consistently modern style. Avoid redundant return 0 The return 0 at the end of this function is unnecessary, you can simply drop it: function is_empty_array { local array="$1[@]" for element in "${!array}"; do return 1 done return 0 } awk tips Instead of: awk 'NR>1 && !seen[$1]++ { print }' I suggest: awk 'NR > 1 && !seen[$1]++' print is the default action to do when the filter is true, that's why it can be dropped. And it's easier to read when there are spaces around the operator in NR>1. Why the hacky readarray now? The previous iteration of your code already used readarray, under the same Bash 3.2+ requirements. So I'm puzzled why bring in a hacky implementation now...
{ "domain": "codereview.stackexchange", "id": 43798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, linux, networking", "url": null }
performance, c, reinventing-the-wheel, matrix Title: Need for matrix multiplication speed Question: I need help to make matrix multiplication in C run as fast as possible. On my AMD Phenom(tm) II X6 1090T, my program multiplies two square singe precision 4096x4096 matrices in about 6.9 seconds. NumPy, which is based on OpenBLAS, multiplies the same sized matrices in about 1.5 seconds. So I think it should be possible to double the speed of my program. Since my processor is old, only 128-bit SIMD instructions are available. Original program #include <math.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define SIZE 4096 #define N_ELS (SIZE * SIZE) #define N_BYTES (sizeof(float) * N_ELS) #define MIN(a, b) ((a > b) ? (b) : (a)) #define N_THREADS 6 #define TILE_SIZE 32 static void mul_tile(int i0, int i1, int j0, int j1, int k0, int k1, float * restrict A, float * restrict B, float * restrict C) { for (int i = i0; i < i1; i++) { for (int k = k0; k < k1; k++) { float a = A[SIZE * i + k]; __builtin_prefetch(&C[SIZE * i + j0]); __builtin_prefetch(&B[SIZE * (k + 1) + j0]); __builtin_prefetch(&B[SIZE * (k + 2) + j0]); for (int j = j0; j < j1; j++) { float b = B[SIZE * k + j]; C[SIZE * i + j] += a * b; } } } } typedef struct { float *A, *B, *C; int start_i, end_i; } mul_job_t;
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
performance, c, reinventing-the-wheel, matrix typedef struct { float *A, *B, *C; int start_i, end_i; } mul_job_t; void *mul_thread(void *arg) { mul_job_t *job = (mul_job_t *)arg; int start_i = job->start_i; int end_i = job->end_i; for (int i = start_i; i < end_i; i += TILE_SIZE) { int imax = MIN(i + TILE_SIZE, SIZE); for (int j = 0; j < SIZE; j += TILE_SIZE) { int jmax = MIN(j + TILE_SIZE, SIZE); for (int k = 0; k < SIZE; k += TILE_SIZE) { int kmax = MIN(k + TILE_SIZE, SIZE); mul_tile(i, imax, j, jmax, k, kmax, job->A, job->B, job->C); } } } return 0; } static void mul(float * restrict A, float * restrict B, float * restrict C) { pthread_t threads[N_THREADS]; mul_job_t jobs[N_THREADS]; memset(C, 0, N_BYTES); int n_i_tiles = (int)ceil((float)SIZE / (float)TILE_SIZE); int tiles_per_thread = (int)ceil((float)n_i_tiles / (float)N_THREADS); for (int i = 0; i < N_THREADS; i++) { int start = TILE_SIZE * i * tiles_per_thread; int end = MIN(start + TILE_SIZE * tiles_per_thread, SIZE); jobs[i] = (mul_job_t){A, B, C, start, end}; pthread_create(&threads[i], NULL, mul_thread, &jobs[i]); } for (int i = 0; i < N_THREADS; i++) { pthread_join(threads[i], NULL); } } int main(int argc, char *argv[]) { float *A = (float *)malloc(N_BYTES); float *B = (float *)malloc(N_BYTES); float *C = (float *)malloc(N_BYTES); for (int i = 0; i < SIZE * SIZE; i++) { A[i] = ((float)rand() / (float)RAND_MAX) * 10; B[i] = ((float)rand() / (float)RAND_MAX) * 10; } struct timespec begin, end; clock_gettime(CLOCK_MONOTONIC_RAW, &begin); mul(A, B, C); clock_gettime(CLOCK_MONOTONIC_RAW, &end); double delta = (end.tv_nsec - begin.tv_nsec) / 1000000000.0 + (end.tv_sec - begin.tv_sec); printf("%.6lfs\n", delta); free(A); free(B); free(C); }
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
performance, c, reinventing-the-wheel, matrix For best results, compile with clang -o mul mul.c -O3 -fomit-frame-pointer -march=native -mtune=native -lpthread. Here is my cache hierarchy: Any answer that significantly improves the performance is acceptable to me. I'm only interested in performance and not other issues the code might have. Notes and additions: gcc 12.2 is about 0.4 seconds slower than clang 14.0 at 7.2 seconds. The machine has a Radeon HD 4200 card, so if someone could optimize the code using GPU instructions that would be cool too. The code is veeery cache sensitive; setting TILE_SIZE to 64 quadruples the execution time, for example. Optimized program #include <math.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define SIZE 4096 #define N_ELS (SIZE * SIZE) #define N_BYTES (sizeof(float) * N_ELS) #define MIN(a, b) ((a > b) ? (b) : (a)) #define N_THREADS 6 #define TILE_SIZE 32 typedef unsigned int uint_t; static void mul_tile(uint_t i0, uint_t i1, uint_t j0, uint_t j1, uint_t k0, uint_t k1, float * restrict A, float * restrict B, float * restrict C ) { for (uint_t i = i0; i < i1; i ++) { for (uint_t k = k0; k < k1; k++) { float a = A[SIZE * i + k]; for (uint_t j = j0; j < j1; j++) { float b = B[SIZE * k + j]; C[SIZE * i + j] += a * b; } } } } typedef struct { float *A, *B, *C; uint_t start_i, end_i; } mul_job_t;
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
performance, c, reinventing-the-wheel, matrix typedef struct { float *A, *B, *C; uint_t start_i, end_i; } mul_job_t; void *mul_thread(void *arg) { mul_job_t *job = (mul_job_t *)arg; uint_t start_i = job->start_i; uint_t end_i = job->end_i; for (uint_t i = start_i; i < end_i; i += TILE_SIZE) { uint_t imax = MIN(i + TILE_SIZE, SIZE); for (uint_t j = 0; j < SIZE; j += TILE_SIZE) { uint_t jmax = MIN(j + TILE_SIZE, SIZE); for (uint_t k = 0; k < SIZE; k += TILE_SIZE) { uint_t kmax = MIN(k + TILE_SIZE, SIZE); mul_tile(i, imax, j, jmax, k, kmax, job->A, job->B, job->C); } } } return 0; } static void mul(float * restrict A, float * restrict B, float * restrict C) { pthread_t threads[N_THREADS]; mul_job_t jobs[N_THREADS]; memset(C, 0, N_BYTES); int n_i_tiles = (int)ceil((float)SIZE / (float)TILE_SIZE); int tiles_per_thread = (int)ceil((float)n_i_tiles / (float)N_THREADS); for (int i = 0; i < N_THREADS; i++) { int start = TILE_SIZE * i * tiles_per_thread; int end = MIN(start + TILE_SIZE * tiles_per_thread, SIZE); jobs[i] = (mul_job_t){A, B, C, start, end}; pthread_create(&threads[i], NULL, mul_thread, &jobs[i]); } for (int i = 0; i < N_THREADS; i++) { pthread_join(threads[i], NULL); } }
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
performance, c, reinventing-the-wheel, matrix int main(int argc, char *argv[]) { float *A = (float *)malloc(N_BYTES); float *B = (float *)malloc(N_BYTES); float *C = (float *)malloc(N_BYTES); for (int i = 0; i < SIZE * SIZE; i++) { A[i] = ((float)rand() / (float)RAND_MAX) * 10; B[i] = ((float)rand() / (float)RAND_MAX) * 10; } struct timespec begin, end; clock_gettime(CLOCK_MONOTONIC_RAW, &begin); mul(A, B, C); clock_gettime(CLOCK_MONOTONIC_RAW, &end); double delta = (end.tv_nsec - begin.tv_nsec) / 1000000000.0 + (end.tv_sec - begin.tv_sec); printf("%.6lfs\n", delta); free(A); free(B); free(C); } Answer: High level The code implements tiling, which is good, but there is only one TILE_SIZE. In my experience, there is benefit from allowing tiles to be non-square. The A tiles and B tiles do not have to be the same size either, they only need to be compatible. So there are really 3 different tile dimensions to choose/tune. The code doesn't implement tile repacking (copying a tile into contiguous memory), which can be useful to reduce TLB thrashing, depending on whether that is happening and how big the impact is. In the current code it's probably not relevant, but it may become so after other changes are done. Low level AMD Phenom(tm) II X6 1090T So the K10 family, here are some relevant performance parameters: 2 movaps (load) per cycle 1 movaps (store) and it costs 2 mops 1 mulps per cycle 1 addps per cycle (latency: 4) 2 shufps per cycle Not all of them at the same time, the shuffle can take the place of an addition or multiplication or both. IDK about the load, there's a question mark in the execution unit column. Additionally, K10 can only decode up to 3 instructions per cycle. I suggest the design goals should be:
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
performance, c, reinventing-the-wheel, matrix reduce the number of stores and loads, making the code consist as much as possible/reasonable of mulps and addps juggle at least 4 independent dependency chains of additions, to avoid bottlenecking on their latency (not a problem in the original code, but it will be when rearranging the code so that stores are avoided in the inner loop) no horizontal sums (which are not SIMD-friendly) do not exceed the number of vector registers (spill/reload would conflict with the first design goal)
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
performance, c, reinventing-the-wheel, matrix Reducing the number of stores can be done by making the k-loop the inner loop, it will then sum up a bunch of products that are then summed into one entry of C. So, no stores in the inner loop. That degrades the access pattern to B, but with tile repacking that doesn't matter, actually repacking makes the access pattern even better than it is now: a purely sequential scan (rather than several sequential pieces). Unfortunately this also ruins the "load a outside of the loop"-strategy, but that will be fixed in a different way. This also creates a loop-carried dependency through the addition, but that will be fixed by using multiple accumulators. To avoid horizontal sums, the factor-of-4 unroll for SIMD won't be across the k-loop, but across the j-loop. So SIMD will be used to compute 4 entries to sum into C, not to compute one entry faster (which would require a horizontal sum). Though the unroll factor will get bigger. To avoid loads (obviously we cannot avoid all of them), the result of a load must be reused several times. This can be done by loading several entries from B (horizontally), and several entries from A (vertically), and then computing every relevant product between those entries. For example by loading 4 entries from B (4 SSE vectors actually, so 16 floats) and 4 entries from A (broadcasted into full vectors with shufps) then there are 16 products to compute. 4x4 doesn't fit in the register budget, but 3x4 and 2x4 are possible. 3 is an annoying number so let's go for 2x4 (by contrast, on Haswell the choice of 3x4 is more or less forced: it requires at least 10 independent dependency chains, due to having an FMA with a latency of 5 and a throughput of 2 per cycle). Important: for 32-bit code, even 2x4 is too much.
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
performance, c, reinventing-the-wheel, matrix So 2 loads from A, vertically (note that this is an unroll of the i-loop by a factor of 2), and then broadcast using shufps (in the code this will be represented by _mm_set1_ps). And 4 loads from B, horizontally, which is already 16 floats at once. It looks likely that the B tiles will "want" to be wider than 32, otherwise the j-loop makes only 2 iterations. 32x32 is really tiny anyway, only 4KB per tile. If I haven't made any mistakes, the important part of the codes comes out roughly like this (treat this more as a sketch of a solution rather than copy-and-paste code though, I just wrote this roughly without testing) #include <xmmintrin.h>
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
performance, c, reinventing-the-wheel, matrix void mul_tile(int i0, int i1, int j0, int j1, int k0, int k1, float * restrict A, float * restrict B, float * restrict C) { for (int i = i0; i < i1; i += 2) { float *Bptr = B; for (int j = j0; j < j1; j += 16) { __m128 acc0 = _mm_load_ps(&C[SIZE * i + j]); __m128 acc1 = _mm_load_ps(&C[SIZE * i + (j + 4)]); __m128 acc2 = _mm_load_ps(&C[SIZE * i + (j + 8)]); __m128 acc3 = _mm_load_ps(&C[SIZE * i + (j + 12)]); __m128 acc4 = _mm_load_ps(&C[SIZE * (i + 1) + j]); __m128 acc5 = _mm_load_ps(&C[SIZE * (i + 1) + (j + 4)]); __m128 acc6 = _mm_load_ps(&C[SIZE * (i + 1) + (j + 8)]); __m128 acc7 = _mm_load_ps(&C[SIZE * (i + 1) + (j + 12)]); for (int k = k0; k < k1; k++) { // broadcast 2 entries from A __m128 A0 = _mm_set1_ps(A[SIZE * i + k]); __m128 A1 = _mm_set1_ps(A[SIZE * (i + 1) + k]); // assuming that B is a repacked tile, memory is accessed perfectly sequentially __m128 B0 = _mm_load_ps(Bptr); __m128 B1 = _mm_load_ps(Bptr + 4); __m128 B2 = _mm_load_ps(Bptr + 8); __m128 B3 = _mm_load_ps(Bptr + 12); Bptr += 16; // perform all products and sum them into the accumulators acc0 = _mm_add_ps(acc0, _mm_mul_ps(A0, B0)); acc1 = _mm_add_ps(acc1, _mm_mul_ps(A0, B1)); acc2 = _mm_add_ps(acc2, _mm_mul_ps(A0, B2)); acc3 = _mm_add_ps(acc3, _mm_mul_ps(A0, B3)); acc4 = _mm_add_ps(acc4, _mm_mul_ps(A1, B0)); acc5 = _mm_add_ps(acc5, _mm_mul_ps(A1, B1)); acc6 = _mm_add_ps(acc6, _mm_mul_ps(A1, B2)); acc7 = _mm_add_ps(acc7, _mm_mul_ps(A1, B3)); }
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
performance, c, reinventing-the-wheel, matrix // store results to C _mm_store_ps(&C[SIZE * i + j], acc0); _mm_store_ps(&C[SIZE * i + (j + 4)], acc1); _mm_store_ps(&C[SIZE * i + (j + 8)], acc2); _mm_store_ps(&C[SIZE * i + (j + 12)], acc3); _mm_store_ps(&C[SIZE * (i + 1) + j], acc4); _mm_store_ps(&C[SIZE * (i + 1) + (j + 4)], acc5); _mm_store_ps(&C[SIZE * (i + 1) + (j + 8)], acc6); _mm_store_ps(&C[SIZE * (i + 1) + (j + 12)], acc7); } } } I neglected to handle cases where the tile size is not divisible by the unroll factor. All wide loads are aligned loads, K10 isn't really that picky about using the unaligned load instruction as long as the actual address is aligned, but you should align the addresses (tile repacking fixes alignment as well, assuming you allocate the memory properly). I cannot predict the best way to prefetch, you would have to try it out. I did not assume that A is repacked, the access pattern isn't that bad and wouldn't cost that many TLB entries at once, you can repack it though. The resulting asm looks reasonable to me, but I'm certainly no K10 expert. Loop variable type int doesn't work out too badly if it is the same size as a pointer, which in various cases it is, but notably not on 64-bit Windows. When int is smaller than a pointer, using an int to offset a pointer (ie accessing an array) likely results in a sign-extension. That may sound insignificant, but these sign-extensions are purely overhead, conferring absolutely no benefit. The cost can be significant especially in small loops. Using an unsigned integer or pointer-sized integer avoids this penalty.
{ "domain": "codereview.stackexchange", "id": 43799, "lm_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, reinventing-the-wheel, matrix", "url": null }
beginner, linked-list, rust Title: basic singly-linked list in rust Question: I'm new to rust and tried to implement a singly-linked list as exercise. Is this code so far suitable to solve the problem? What elements of the language should I consider to make the code more elegant? #![allow(dead_code)] use std::{ fmt::{Debug, Display}, ops::Index, }; struct List { value: u8, next: Option<Box<List>>, } impl List { fn new(value: u8) -> Self { let next = None; Self { value, next } } fn append(&mut self, value: u8) { let new = List::new(value); let last = self.get_last_element_mut(); last.next = Some(Box::new(new)); } fn get_last_element_mut(&mut self) -> &mut Self { if self.next.is_none() { self } else { self.next.as_mut().unwrap().get_last_element_mut() } } fn get_last_element(&self) -> &Self { if self.next.is_none() { self } else { self.next.as_ref().unwrap().get_last_element() } } fn len(&self) -> usize { if self.next.is_none() { 1 } else { 1 + self.next.as_ref().unwrap().len() } } fn get_mut(&mut self, index: usize) -> &mut Self { if index == 0 { self } else { self.next.as_mut().unwrap().get_mut(index - 1) } } } impl Index<usize> for List { type Output = List; fn index(&self, index: usize) -> &Self::Output { if index == 0 { self } else { &self .next .as_ref() .expect("line should have {index} more elements")[index - 1] } } } impl PartialEq for List { fn eq(&self, other: &Self) -> bool { self.value == other.value && self.next == other.next } }
{ "domain": "codereview.stackexchange", "id": 43800, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, linked-list, rust", "url": null }
beginner, linked-list, rust impl Display for List { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.next.is_none() { f.write_fmt(format_args!("{}", self.value)) } else { f.write_fmt(format_args!("{} -> ", self.value))?; std::fmt::Display::fmt(&self.next.as_ref().unwrap(), f) } } } impl Debug for List { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("List") .field("value", &self.value) .field("next", &self.next) .finish() } } impl From<Vec<u8>> for List { fn from(vec: Vec<u8>) -> Self { let mut result = List::new(vec[0]); for item in &vec[1..] { result.append(*item); } result } } fn main() { let mut l = List::new(5); l.append(8); l.append(1); println!("{}", l[0]); println!("{}", l[1]); println!("{}", l[2]); } #[cfg(test)] mod tests { use super::List; #[test] fn append() { let mut l = List::new(5); assert_eq!(l.len(), 1); assert_eq!(l.get_last_element().value, 5); l.append(8); assert_eq!(l.len(), 2); assert_eq!(l.get_last_element().value, 8); } #[test] fn mutable() { let mut l = List::new(0); l.append(1); assert_eq!(l.get_last_element().value, 1); assert_eq!(l.len(), 2); l.get_last_element_mut().value = 5; assert_eq!(l.get_last_element().value, 5); assert_eq!(l.len(), 2); } #[test] fn representation() { let mut l = List::new(1); l.append(2); l.append(3); let repr = format!("{}", l); assert_eq!(repr, "1 -> 2 -> 3"); } #[test] #[should_panic] fn out_of_bounds() { let mut l = List::new(1); l.append(2); let _ = l[l.len()]; }
{ "domain": "codereview.stackexchange", "id": 43800, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, linked-list, rust", "url": null }
beginner, linked-list, rust #[test] fn from_vec() { let input = vec![0, 3, 2, 1, 4]; let list = List::from(input); let repr = format!("{}", list); assert_eq!(repr, "0 -> 3 -> 2 -> 1 -> 4"); } } ``` Answer: The code is generally well-formatted and readable. Also, kudos for including unit tests since they make it easy for reviewers to tweak and test your code. #![allow(dead_code)] The reason why you got dead code warnings is (mostly like) because you did not mark public interfaces as pub. Instead of suppressing the warning, you should mark struct List and its methods as pub. struct List { value: u8, next: Option<Box<List>>, } We can easily generalize the code to handle non-u8 element types: struct List<T> { value: T, next: Option<Box<List<T>>>, } fn new(value: u8) -> Self { let next = None; Self { value, next } } A simpler alternative is Self { value, next: None }. fn get_last_element_mut(&mut self) -> &mut Self { if self.next.is_none() { self } else { self.next.as_mut().unwrap().get_last_element_mut() } } Here, we see the common anti-pattern is_none + unwrap, which appears throughout the code a few times. The latter (in theory) performs a redundant second check for is_none and leaves the impression that a panic is possible. The way to go here is to use a match directly: fn get_last_element_mut(&mut self) -> &mut Self { match self.next { None => self, Some(ref mut next) => next.get_last_element_mut(), } } (It seems that combinators such as map_or cannot be used here since self.next.as_deref_mut().map_or(self, Self::get_last_element_mut) would alias the mutable reference self.) I would, however, also consider going with an iterative version to prevent unnecessary recursion: fn get_last_element_mut(&mut self) -> &mut Self { let mut last = self; while let Some(ref mut next) = last.next { last = next; } last }
{ "domain": "codereview.stackexchange", "id": 43800, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, linked-list, rust", "url": null }
beginner, linked-list, rust impl Index<usize> for List { type Output = List; // ... } I would expect type Output = usize (or type Output = T for a generic List<T>) along with an implementation of IndexMut<usize> for consistency with other containers. I would rename the operation you implemented (get_node?) and perhaps make it return an Option instead of panicking. .expect("line should have {index} more elements") The panic message is literally "line should have {index} more elements" — no substitution is performed for {index}, which is probably not intended. (In fact, such implicit named arguments only work within the formatting macros format!, print!, write!, etc.). The fix is .unwrap_or_else(|| panic!("line should have {index} more elements")) By the way, this is a clever panic message as it mentions the quantity index - len, which conveniently stays constant during the recursion. The standard message is index out of bounds: the len is {} but the index is {}, for comparison, which I personally find more informative. impl PartialEq for List { fn eq(&self, other: &Self) -> bool { self.value == other.value && self.next == other.next } } This is equivalent to the default implementation of PartialEq, which (along with a few other default trait implementations) can be applied using derive when defining struct List: #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct List { // ... } impl Display for List { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.next.is_none() { f.write_fmt(format_args!("{}", self.value)) } else { f.write_fmt(format_args!("{} -> ", self.value))?; std::fmt::Display::fmt(&self.next.as_ref().unwrap(), f) } } } The same is_none + unwrap anti-pattern is present here. f.write_fmt(format_args!("{}", self.value)) should be write!(f, "{}", self.value)
{ "domain": "codereview.stackexchange", "id": 43800, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, linked-list, rust", "url": null }
beginner, linked-list, rust Also, fully qualifying std::fmt::Display is not necessary. For comparison, the containers in the standard library do not implement Display, since there is no one true format suitable for user-facing display. Better would be to support iterators and enable customizable formatters such as itertools::format. impl From<Vec<u8>> for List { fn from(vec: Vec<u8>) -> Self { let mut result = List::new(vec[0]); for item in &vec[1..] { result.append(*item); } result } } The usual interface for such conversions is collect, which uses the FromIterator trait. By implementing FromIterator, all kinds of iterators are supported, not just Vec: impl FromIterator<u8> for List { fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = u8>, { let mut iter = iter.into_iter(); let mut list = List::new(iter.next().expect("empty lists are not supported")); for item in iter { list.append(item); } list } } // ... let list = List::from_iter([3, 1, 4, 1, 5, 9]);
{ "domain": "codereview.stackexchange", "id": 43800, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, linked-list, rust", "url": null }
react.js, jsx Title: Design a kanban board in reactJS Question: Attempting to write a simple Kanban board in ReactJS. Omiting the css code, mostly wanted some advise on best practices in the ReactJS code itself. export default function App() { const [todo, setTodo] = React.useState(["finish xyz", "finish abc"]); const [inprogress, setInprogress] = React.useState(["hello world"]); const [done, setDone] = React.useState(["hey there!"]); const moveLeft = (type, taskname) => { if (type === "inprogress") { setInprogress([...inprogress.filter((val) => val !== taskname)]); setTodo([...todo, taskname]); } else if (type === "done") { setDone([...done.filter((val) => val !== taskname)]); setInprogress([...inprogress, taskname]); } }; const moveRight = (type, taskname) => { if (type === "todo") { setTodo([...todo.filter((val) => val !== taskname)]); setInprogress([...inprogress, taskname]); } else if (type === "inprogress") { setInprogress([...inprogress.filter((val) => val !== taskname)]); setDone([...done, taskname]); } };
{ "domain": "codereview.stackexchange", "id": 43801, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "react.js, jsx", "url": null }
react.js, jsx return ( <div className="board"> <div className="todo"> <div>TODO</div> {todo.map((curr) => ( <Task key={curr.replaceAll(" ", "-")} moveLeft={moveLeft} moveRight={moveRight} type="todo" taskName={curr} /> ))} </div> <div className="inprogress"> <div>INPROGRESS</div> {inprogress.map((curr) => ( <Task key={curr.replaceAll(" ", "-")} moveLeft={moveLeft} moveRight={moveRight} type="inprogress" taskName={curr} /> ))} </div> <div className="done"> <div>DONE</div> {done.map((curr) => ( <Task key={curr.replaceAll(" ", "-")} moveLeft={moveLeft} moveRight={moveRight} type="done" taskName={curr} /> ))} </div> </div> ); } function Task(props) { return ( <div className="task"> <div>{props.taskName}</div> <button onClick={() => props.moveLeft(props.type, props.taskName)}> left </button> <button onClick={() => props.moveRight(props.type, props.taskName)}> right </button> </div> ); } Answer: Consider use of useReducer instead of multiple state variables. It helps keep component clean by moving all this transition logic outside of the component. Extract types ("inprogress", "todo", "done") as constants. It's easy to maintain all these magic string when they are constants. filter creates copy of array, spreading is unnecessary. There are no restrictions on key value, it can contain spaces. I suggest to pass click handlers to the Task component to make it dumber.
{ "domain": "codereview.stackexchange", "id": 43801, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "react.js, jsx", "url": null }
rust, state-machine Title: Framework to create turing machines with binary increment example Question: I created a way to create turing machines and implemented one that increments a binary number as an example. This is the turing machine itself: use std::fmt::{self, Display}; pub struct TuringMachine<'state, TapeItem: Default> { tape: Tape<TapeItem>, current_state: &'state dyn State<TapeItem>, } impl<'state, TapeItem: Default> TuringMachine<'state, TapeItem> { pub fn new( tape: Tape<TapeItem>, initial_state: &'state dyn State<TapeItem>, ) -> TuringMachine<TapeItem> { Self { tape, current_state: initial_state, } } // makes progress on the turing machine (updating it) and returns whether an end state was reached pub fn update(&mut self) -> bool { let (item_replacement, mv, state_replacement, end_state) = self.current_state.process(self.tape.get_current()); if let Some(item) = item_replacement { self.tape.replace_current(item); } if let Some(mv) = mv { self.tape.apply_move(mv); } if let Some(state) = state_replacement { self.current_state = state; } end_state } } // implements the display trait for tape items which also do. Prints the state on the first line and the tape on the second impl<'state, TapeItem: Default + Display> Display for TuringMachine<'state, TapeItem> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_fmt(format_args!("{}\n{}", self.current_state, self.tape)) } } // represents the position on a tape either on the right or the left side #[derive(Debug, Clone, Copy, PartialEq)] pub enum TapePosition { RightSide(usize), LeftSide(usize), }
{ "domain": "codereview.stackexchange", "id": 43802, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, state-machine", "url": null }
rust, state-machine // represents the tape of the turing machine with a left and a right side #[derive(Debug, Clone, PartialEq)] pub struct Tape<TapeItem> { pos: TapePosition, right: Vec<TapeItem>, left: Vec<TapeItem>, } impl<TapeItem: Default> Tape<TapeItem> { // given a vector of tape items and a start position returns a tape where the items are placed on the right side and the selected item is on the right side at start_pos pub fn new(items: Vec<TapeItem>, start_pos: usize) -> Tape<TapeItem> { Self { pos: TapePosition::RightSide(start_pos), right: items, left: Vec::new(), } } // returns a reference to the currently selected tape item fn get_current(&self) -> &TapeItem { match self.pos { TapePosition::RightSide(pos) => &self.right[pos], TapePosition::LeftSide(pos) => &self.left[pos], } } // replaces the currently selected tape item fn replace_current(&mut self, replacement: TapeItem) { match self.pos { TapePosition::RightSide(pos) => self.right[pos] = replacement, TapePosition::LeftSide(pos) => self.left[pos] = replacement, } }
{ "domain": "codereview.stackexchange", "id": 43802, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, state-machine", "url": null }
rust, state-machine // applies a given move to the tape changing the currently selected tape item fn apply_move(&mut self, mv: TapeMove) { self.pos = match mv { TapeMove::Right => { match self.pos { // we are on the right side of the tape and want to move further right TapePosition::RightSide(pos) => { // we need to make sure there is enough space for the current item and the next if self.right.len() <= pos + 1 { self.right.resize_with(pos + 2, TapeItem::default); } TapePosition::RightSide(pos + 1) } TapePosition::LeftSide(pos) => { // do we need to change sides? match pos { 0 => { // if so we need to make sure the other side has at least two items if self.right.len() <= 1 { self.right.resize_with(2, TapeItem::default); } TapePosition::RightSide(0) } _ => TapePosition::LeftSide(pos - 1), } } } } // mirrored for the left side TapeMove::Left => match self.pos { TapePosition::LeftSide(pos) => { if self.left.len() <= pos + 1 { self.left.resize_with(pos + 2, TapeItem::default); } TapePosition::LeftSide(pos + 1) } TapePosition::RightSide(pos) => match pos { 0 => { if self.left.len() <= 1 { self.left.resize_with(2, TapeItem::default); }
{ "domain": "codereview.stackexchange", "id": 43802, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, state-machine", "url": null }
rust, state-machine self.left.resize_with(2, TapeItem::default); } TapePosition::LeftSide(0) } _ => TapePosition::RightSide(pos - 1), }, }, } } }
{ "domain": "codereview.stackexchange", "id": 43802, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, state-machine", "url": null }
rust, state-machine impl<TapeItem: Display> Display for Tape<TapeItem> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result { // format the left side of the tape if let Some(r) = self .left .iter() .enumerate() // we need the index to tell if this item is selected .rev() // since the index of the innermost item is 0 and that of the outermost item the highest, we need to reverse it .map(|(i, item)| -> fmt::Result { if let TapePosition::LeftSide(pos) = self.pos { if pos == i { // if an item on the left side of the tape is selected and this is that item, mark it with underscores on either site f.write_fmt(format_args!("_{item}_")) } else { item.fmt(f) // otherwise format it normally } } else { item.fmt(f) // also if an item on the other site is selected } }) .find(|r| r.is_err()) { // find the first error (if any) and return it r } else { // otherwise continue with the right side if let Some(r) = self .right .iter() .enumerate() .map(|(i, item)| -> fmt::Result { if let TapePosition::RightSide(pos) = self.pos { if pos == i { f.write_fmt(format_args!("_{item}_")) } else { item.fmt(f) } } else { item.fmt(f) } }) .find(|r| r.is_err()) { r } else { Ok(()) } } } }
{ "domain": "codereview.stackexchange", "id": 43802, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, state-machine", "url": null }
rust, state-machine // represents a movement of the tape either to the right or the right #[derive(Debug, Clone, Copy, PartialEq)] pub enum TapeMove { Right, Left, } // represents a state of the turing machine which may move the tape, change the current item on the tape, change the state and reports whether it transitioned into an end state // it also needs to implement display pub trait State<TapeItem>: Display { fn process( &self, item: &TapeItem, ) -> ( Option<TapeItem>, // optionally replace the current tape item Option<TapeMove>, // optionally move on the tape Option<&dyn State<TapeItem>>, // optionally change state bool, // is this an end state ); } And this is an example for a TM that increments a binary number: use std::fmt::{self, Display}; pub mod turing_machine; use crate::turing_machine::{Tape, TuringMachine}; use turing_machine::{State, TapeMove}; fn main() { let mut tm = TuringMachine::new( Tape::new( vec![ BinaryTapeItem::One, BinaryTapeItem::One, BinaryTapeItem::One, ], 0, ), &Q0 {}, ); loop { println!("{tm}\n"); if tm.update() { // if we reached the end state of the turing machine we are done break; } } println!("{tm}"); } #[derive(Debug, Clone, Copy, PartialEq)] enum BinaryTapeItem { Default, One, Zero, } impl Default for BinaryTapeItem { fn default() -> Self { BinaryTapeItem::Default } } impl Display for BinaryTapeItem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { BinaryTapeItem::Default => "?", BinaryTapeItem::One => "1", BinaryTapeItem::Zero => "0", }) } }
{ "domain": "codereview.stackexchange", "id": 43802, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, state-machine", "url": null }
rust, state-machine // image of the implemented turing machine: https://media.geeksforgeeks.org/wp-content/uploads/20200924004938/GFGArticles.png struct Q0 {} impl Display for Q0 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result { f.write_str("Q0") } } impl State<BinaryTapeItem> for Q0 { fn process( &self, item: &BinaryTapeItem, ) -> ( Option<BinaryTapeItem>, // optionally replace the current tape item Option<TapeMove>, // optionally move on the tape Option<&dyn State<BinaryTapeItem>>, // optionally change state bool, // is this an end state ) { match item { // 0/0,R BinaryTapeItem::Zero => (None, Some(TapeMove::Right), None, false), // 1/1,R BinaryTapeItem::One => (None, Some(TapeMove::Right), None, false), // B/B,L BinaryTapeItem::Default => (None, Some(TapeMove::Left), Some(&Q1 {}), false), } } } struct Q1 {} impl Display for Q1 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Q1") } }
{ "domain": "codereview.stackexchange", "id": 43802, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, state-machine", "url": null }
rust, state-machine impl State<BinaryTapeItem> for Q1 { fn process( &self, item: &BinaryTapeItem, ) -> ( Option<BinaryTapeItem>, // optionally replace the current tape item Option<TapeMove>, // optionally move on the tape Option<&dyn State<BinaryTapeItem>>, // optionally change state bool, // is this an end state ) { match item { // 1/0,L BinaryTapeItem::One => ( Some(BinaryTapeItem::Zero), Some(TapeMove::Left), None, false, ), // B/1,N BinaryTapeItem::Default => (Some(BinaryTapeItem::One), None, None, true), // 0/1,N BinaryTapeItem::Zero => (Some(BinaryTapeItem::One), None, None, true), } } } This is what it outputs: Q0 _1_11 Q0 1_1_1 Q0 11_1_ Q0 111_?_ Q1 11_1_? Q1 1_1_0? Q1 _1_00? Q1 ?_?_000? Q1 ?_1_000? Answer: // represents the position on a tape either on the right or the left side #[derive(Debug, Clone, Copy, PartialEq)] pub enum TapePosition { RightSide(usize), LeftSide(usize), } // represents the tape of the turing machine with a left and a right side #[derive(Debug, Clone, PartialEq)] pub struct Tape<TapeItem> { pos: TapePosition, right: Vec<TapeItem>, left: Vec<TapeItem>, } Your approach to the tape is complicated here by having left and right side of the tape. You've got to handle both cases of TapePosition in a lot of places. Instead, I'd suggest either: Use VecDeque to hold a single tape. You can add onto either end of a VecDeque to grow the tape on either side. Use left and right stacks along with a current item. Move left by popping the left stack and pushing onto the right stack, and move right by popping the right stack and pushing onto the left stack.
{ "domain": "codereview.stackexchange", "id": 43802, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, state-machine", "url": null }
rust, state-machine Next: pub trait State<TapeItem>: Display { fn process( &self, item: &TapeItem, ) -> ( Option<TapeItem>, // optionally replace the current tape item Option<TapeMove>, // optionally move on the tape Option<&dyn State<TapeItem>>, // optionally change state bool, // is this an end state ); } Firstly, I'd suggest defining and returning a struct here rather than a tuple. There's a lot of different parts here without an obvious order, so I think name fields would benefit it. Secondly, it contains a borrow in the return. Due to Rust's rules, this means that it has to return something with the same lifetime as self. But in practice that would be tricky. You can either return something that is inside the original state (which seems unlikely to be helpful), or something with a static lifetime. In your case, you return constants with a static lifetime. Your code would be simpler to simply require the 'static lifetime here. Then TuringMachine wouldn't need the special lifetime. However, you'd gain flexibility by return something like a Box instead of a borrow. However, a rustier solution would be use enums. In particular, rather then defining seperate Q0 and Q1 traits and dynamically dispatching over them in your example, you'd define something like: enum State { Q0, Q1, } Then you can define your transition rules as a method on State.
{ "domain": "codereview.stackexchange", "id": 43802, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, state-machine", "url": null }
c++, performance, array, cache Title: Implementation of a multi-dimensional array as a single memory buffer Question: There is an updated version of this code with some of the recommended changes made here. I have created an implementation of a multi-dimensional array which utilizes a single continuous memory buffer to improve cache locality. My intention is for this to behave in a similar way to a multi-dimensional vector in c++, and so I have overloaded Tensor::operator[] to return another Tensor object of dimension one less, which can then be indexed again with Tensor::operator[]. There is a base template specialization for the case where the dimension count is 1. Please give me some tips on how this implementation can be improved. My main concerns with the code are that I use raw malloc and free statements, however I am not quite sure how I could implement this efficiently without using raw pointers and mallocs as I do not want to have to copy memory in the Tensor::operator[] function. Also I am not using the c++ equivalents of new and delete as they do not have an analogue to realloc. #include <iostream> template<typename Ty, size_t N> class Tensor { private: Ty *data; size_t *offset; bool owner; public: Tensor() : data(nullptr), offset((size_t*)malloc((N+1)*sizeof(size_t))), owner(true) {} Tensor(Ty *data, size_t *offset) : data(data), offset(offset), owner(false) {} ~Tensor() { if (owner) { free(offset); free(data); } } Tensor<Ty, N-1> operator[] (size_t i) { return Tensor<Ty, N-1>(&data[i*offset[N-1]], offset); }
{ "domain": "codereview.stackexchange", "id": 43803, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, array, cache", "url": null }
c++, performance, array, cache void resize(size_t* size) { if (!owner) { std::cerr << "cannot resize - memory is not owned" << std::endl; return; } offset[0] = 1; for (size_t i = 1; i <= N; ++i) { offset[i] = offset[i-1]*size[N-i]; } data = (Ty*)realloc(data, offset[N] * sizeof(double)); } }; template<typename Ty> class Tensor<Ty, 1> { private: Ty *data; size_t len; bool owner; public: Tensor() : data(nullptr), len(0), owner(true) {} Tensor(Ty *data, size_t *offset) : data(data), len(offset[1]), owner(false) {} ~Tensor() { if (owner) { free(data); } } Ty &operator[](size_t i) { return data[i]; } void resize(size_t* size) { if (!owner) { std::cerr << "cannot resize - memory is not owned" << std::endl; return; } len = size[0]; data = (Ty*)realloc(data, len*sizeof(double)); } }; Answer: Do not use malloc() and free() in C++ My main concerns with the code are that I use raw malloc and free statements, [...] I am not using the c++ equivalents of new and delete as they do not have an analogue to realloc.
{ "domain": "codereview.stackexchange", "id": 43803, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, array, cache", "url": null }
c++, performance, array, cache There is a good reason for that. While in C you only have so-called plain-old-data structs, in C++ a type can be a class that has constructors, destructors, copy and move operators. By using the C memory management functions, you are bypassing all these things, and can cause problems when you use this for classes that do have these things. You should use new and delete, and indeed do realloc() by creating a new allocation, copying everything over, and deleting the old one. That might be inefficient, but it is more correct. You could specialize your class for trivial types to get performance back. However, even better is to avoid doing your own memory management, whether it's C or C++ style. Instead, rely on existing containers to do it for you. I would use a std::vector to provide the single contiguous memory buffer for you: template<typename Ty, size_t N> class Tensor { private: std::vector<Ty> data; std::vector<size_t> offsets(N + 1); ... } This also avoids a bug in your code: when you call realloc(), you assume the size of an element is equal to sizeof(double), but you should have used sizeof(Ty). With std::vector<Ty>, you don't have to worry about this. Create a separate view class Instead of having class Tensor handle both the actual tensor and a lesser-dimensional view into the actual data, create two separate classes: class Tensor that owns the whole tensor, and a class TensorView that is a non-owning view into a Tensor: template<typename Ty, size_t N> class TensorView { Ty *data; size_t *offsets; public: TensorView(Ty *data, size_t *offsets): data(datra), offsets(offsets) {} TensorView<Ty, N - 1> operator[](size_t i) { return {&data[i * offsets[N - 1]], offsets}; } }; ... template<typename Ty, size_t N> class Tensor { private: std::vector<Ty> data; std::vector<size_t> offsets(N + 1); public: TensorView<Ty, N - 1> operator[](size_t i) { return {&data[i * offset[N - 1]], offset}; }
{ "domain": "codereview.stackexchange", "id": 43803, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, array, cache", "url": null }
c++, performance, array, cache void resize(const size_t *sizes) { offset[0] = 1; for (size_t i = 1; i <= N; ++i) { offset[i] = offset[i - 1] * sizes[N - i]; } data.resize(offset[N]); } }; This makes handling one-dimensional tensors a bit harder. Since C++17, you can use if constexpr to handle this, for example like so: template<typename Ty, size_t N> class Tensor { ... auto operator[](size_t i) { if constexpr (N == 1) { return data[i]; } else { return TensorView<Ty, N - 1>{&data[i * offset[N - 1]], offset}; } } ... }; Make it work like a STL container Your class supports operator[] and resize(), but it would be much nicer if it supported all the features you would expect from a typical STL container, like std::vector. Not only does it add more member functions and operator overloads, it also handles const containers correctly, it allows iterating over the container using range-for loops.
{ "domain": "codereview.stackexchange", "id": 43803, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, array, cache", "url": null }
javascript, calculator, math-expression-eval, binary-tree Title: Binary Expression Tree that evaluates Postfix input Question: My code for a Binary Expression Tree that takes postfix input from the user and recursively builds and evaluates the expression. Proper input can be assumed. class Node { constructor(data) { this.data = data, this.left = null, this.right = null } } class BinaryExpressionTree { constructor() { this.stack = [], this.operators = ['+', '-', '*', '/', '(', ')', '^'] } buildExpressionTree(expression) { expression.forEach((char) => { const node = new Node(char) if (!this.operators.includes(char)) { node.data = parseInt(node.data, 10) this.stack.push(node) } else { const r = this.stack.pop() const l = this.stack.pop() node.right = r node.left = l this.stack.push(node) } }) } operate(n1, o, n2) { // operand in middle const operations = { '^': function (a, b) { return a ** b }, '*': function (a, b) { return a * b }, '/': function (a, b) { return a / b }, '+': function (a, b) { return a + b }, '-': function (a, b) { return a - b } } return operations[o](n1, n2) } evaluate(root) { if (!root.data) { return 0 } if (!root.left && !root.right) { return root.data } let leftSum = this.evaluate(root.left) let rightSum = this.evaluate(root.right) return this.operate(leftSum, root.data, rightSum) } }
{ "domain": "codereview.stackexchange", "id": 43804, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, calculator, math-expression-eval, binary-tree", "url": null }
javascript, calculator, math-expression-eval, binary-tree const input = ['8', '2', '^', '6', '+', '2', '10', '*', '2', '/', '-'] const testTree = new BinaryExpressionTree() testTree.buildExpressionTree(input) const answer = testTree.evaluate(testTree.stack[0]) console.log('prefix input: ', input.join(' ')) console.log('answer: ', answer) Output: postfix input: 8 2 ^ 6 + 2 10 * 2 / - answer: 60 Any feedback is welcome. Answer: Validate inputs It's not mentioned if we can assume the input is always valid. Aside from parsing errors, if the input is not in valid postfix form, the parsed tree may be broken, consider for example some infix inputs such as 1 + 2. OOP and encapsulation The stack used in parsing the input is accessible outside of the class. I don't understand why, and also why is it retained at all after the parsing. When working with trees, the root is the most natural critical piece, I find it unexpected to be aware of a stack instead. I think input validation would have revealed this issue: at the end of parsing a well-formed non-empty expression, the stack should have precisely one item in it. That item could be stored as the root of the tree. Users of BinaryExpressionTree must know how to access the root, so that they can call evaluate on it. From a user's perspective, it seems a bit strange to pass the tree's own root to itself. It would be more natural to be able to call evaluate without arguments. A different kind of encapsulation issue is the definition of operations. Since these are common to all operations, it would be better to define them outside of the operate function, to avoid unnecessary repeated evaluations. After operations are removed from the operate function, it will look something like this: operate(n1, o, n2) { // operand in middle return operations[o](n1, n2) }
{ "domain": "codereview.stackexchange", "id": 43804, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, calculator, math-expression-eval, binary-tree", "url": null }
javascript, calculator, math-expression-eval, binary-tree And at this point, it will be easier to inline it, so that callers don't have to know the correct order of parameters, which reduces the mental burden and less prone to simple mistakes. Don't repeat yourself The presumably supported operators are in two places: In the constructor as a list of symbols In operate as keys in a map of functions From the constructor it looks like ( and ) are supported, but actually they are not handled during parsing. It would be better to define the operator functions once, and use that mapping during parsing. Improving some names buildExpressionTree duplicates terms from the name of the class. We know we're working with an expression tree. I'd call this parse. I find leftSum and rightSum a bit misleading, suggesting "add" operations behind. In truth these values are results of the left and right sub-expressions, so leftResult and rightResult would be better. The name l is used when parsing the expression. With some fonts, this letter can be difficult to distinguish from 1 or |, so I avoid it. left would be a good name there. Or in the posted code, inlining is also fine. Use const instead of let These should use const instead of let: let leftSum = this.evaluate(root.left) let rightSum = this.evaluate(root.right) Use arrow functions The operations could be defined more compactly using arrow functions: const operations = { '^': (a, b) => a ** b, '*': (a, b) => a * b, '/': (a, b) => a / b, '+': (a, b) => a + b, '-': (a, b) => a - b }
{ "domain": "codereview.stackexchange", "id": 43804, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, calculator, math-expression-eval, binary-tree", "url": null }
performance, strings, typescript Title: TypeScript function to compare two arrays while ignoring case and whitespace
{ "domain": "codereview.stackexchange", "id": 43805, "lm_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, strings, typescript", "url": null }
performance, strings, typescript Question: I'm just looking for general guidance on this short TypeScript function I implemented. Are there any glaring violations? Are there better practices for accomplishing this? Should I be using map/reduce/filter, or is this simple approach just fine here? I'm not sure about efficiency here because we basically just need to examine every item from each list. I don't think there is a shortcut way to make this faster, but that's why I'm asking. For what it's worth, we're only talking about examining a couple hundred items. The function takes two lists. If the source list contains items that the other list does not, we need to return those items. When comparing the lists, we need to remove leading and trailing whitespace, and we need to ignore case sensitivity. However, the returned values need to be in their original casing. /** * Returns a list of items missing from a source list. The items are compared while ignoring case and * ignoring leading and trailing whitespace. The values returned maintain their original casing though. * @param sourceList - The master list used for comparison. * @param otherList - The list to be compared to the source list. * @returns The items in the source list that are missing from the other list. */ export function getMissingItemsIgnoreCase( sourceList: string[], otherList: string[], ): string[] { const otherListLowerCaseAndTrimmed: string[] = otherList.map((x) => x.toLowerCase().trim(), ); // The key is the lower-case and trimmed provider name. The value is the same, but with original casing. // We'll return the value so we preserve the casing. const missingMap = new Map<string, string>(); for (const sourceItem of sourceList) { const sourceItemLowerCaseAndTrimmed = sourceItem.toLowerCase().trim(); if (!otherListLowerCaseAndTrimmed.includes(sourceItemLowerCaseAndTrimmed)) {
{ "domain": "codereview.stackexchange", "id": 43805, "lm_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, strings, typescript", "url": null }
performance, strings, typescript if (!otherListLowerCaseAndTrimmed.includes(sourceItemLowerCaseAndTrimmed)) { missingMap.set(sourceItemLowerCaseAndTrimmed, sourceItem.trim()); } } return Array.from(missingMap.values()); }
{ "domain": "codereview.stackexchange", "id": 43805, "lm_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, strings, typescript", "url": null }
performance, strings, typescript Answer: One glaring issue is using of .includes() for every element. AFAIK, .includes() just does linear search item by item -- it's a hidden loop. And then there is your const (const sourceItem of sourceList), an explicit loop. These loops are nested, and which means the time required to run your function is proportional to <number of items in 1st array> * <number of items in 2nd array>. To me it seems like O(n^2), which is slow for big numbers and/or additional levels of nesting -- imagine somebody uses your function in a tight loop on a big dataset. (Disclaimer: I'm not a guru on big O notation, so, I might be wrong re particulars, but I believe the main idea is still correct.) What can be done? Instead of this: const otherListLowerCaseAndTrimmed: string[] = otherList.map((x) => x.toLowerCase().trim(), ); // ... if (!otherListLowerCaseAndTrimmed.includes(sourceItemLowerCaseAndTrimmed)) { // ... } Do this (note new Set() and .has()): const otherListLowerCaseAndTrimmed = new Set( otherList.map((x) => x.toLowerCase().trim(), ) ); // ... if (!otherListLowerCaseAndTrimmed.has(sourceItemLowerCaseAndTrimmed)) { // ... }
{ "domain": "codereview.stackexchange", "id": 43805, "lm_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, strings, typescript", "url": null }
performance, strings, typescript I believe this change makes it O(n) instead of O(n^2), i.e. required time grows in a linear fashion instead of quadratic. Your original implementation seems to be fine, and with smallish datasets you won't encounter problems. If you're sure that's the most plausible scenario, then it's actually fine to leave it like that. But it's a good habit to avoid O(n^2) if possible, because in a fairly complex application these things stack, and can suddenly bite you when total amount of data you're working with hits certain limits. There is another thing which is less impactful but still could be useful: instead of building a map of results, you could make a generator and output values one by one, as they are ready, which somewhat lowers memory requirements, but also substantially changes function signature and the way client code consumes is. So, I'd recommend investigating this only if you know memory usage could be an issue (probably not for browser code, probably yes for server-side with lots of concurrent requests). And one more thing which could make your function less specific. Consider this: export function getMissingItems( sourceList: string[], otherList: string[], transform: (value: string) => string = s => s.toLowerCase().trim() ): string[] { const otherListTransformed = new Set(otherList.map(x => transform(x))); const missingMap = new Map<string, string>(); for (const sourceItem of sourceList) { const sourceItemTransformed = transform(sourceItem); if (!otherListTransformed.has(sourceItemTransformed)) { missingMap.set(sourceItemTransformed, sourceItem); } } return Array.from(missingMap.values()); }
{ "domain": "codereview.stackexchange", "id": 43805, "lm_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, strings, typescript", "url": null }
performance, strings, typescript return Array.from(missingMap.values()); } With this code your function could handle any kind of transformation, but defaults to your original behavior (minus transformation of the resulting strings, but please bear with me). This approach could be generalized to this: export const lowercase = (items: string[]): string[] => items.map(x => x.toLowerCase()); export const trim = (items: string[]): string[] => items.map(x => x.trim()); export const getMissingItems = ( sourceList: string[], otherList: string[], transformation: (x: string) => string = x => x, ): string[] => { const otherItems = new Set(otherList.map(x => transformation(x))); return sourceList.filter(x => otherItems.has(transformation(x))); }; And with this little "library" of pretty generic functions your original code can be expressed like this: export function getMissingItemsIgnoreCase( sourceList: string[], otherList: string[], ): string[] { return getMissingItems( trim(sourceList), trim(otherList), x => x.toLowerCase() ); } Please be careful, here starts the domain of functional programming, composition, and many other interesting things which might drastically change your approach to solving problems. Jokes aside, that's where people usually start to over-optimize, over-abstract, over-generalize, and many other "over-" things that hurt productivity.
{ "domain": "codereview.stackexchange", "id": 43805, "lm_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, strings, typescript", "url": null }
performance, hash-map, android, error-handling, kotlin Title: Processing charge current error messages with HashMap<> Question: I have certain error states that I am displaying in my Android TextView but only one message is displayed at a time and if all values are set to 0, no message is displayed. So, I check all the values with if-else and set the associated switch in the chargeCurrentMap. I then clear the error message if all values in the map are 0. My concern is that my Kotlin code is too long and clunky. How can I improve it? private var chargeCurrentMap = HashMap<String?, Int?>() private lateinit var chargeCurrentErrorMessage: String
{ "domain": "codereview.stackexchange", "id": 43806, "lm_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, hash-map, android, error-handling, kotlin", "url": null }
performance, hash-map, android, error-handling, kotlin private fun processChargeModes(data: ByteArray, increment: Int = 0) { deviceData.restMode = data[28].toInt() if (deviceData.restMode == 1) { chargeCurrentErrorMessage = "Battery full, charger is off" chargeCurrentMap["rest"] = 1 binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } else { chargeCurrentMap["rest"] = 0 } deviceData.misbalancedMode = data[29].toInt() if (deviceData.misbalancedMode == 1) { chargeCurrentErrorMessage = "Charging is paused, battery is resolving a minor issue" chargeCurrentMap["misbalanced"] = 1 binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } else { chargeCurrentMap["misbalanced"] = 0 } deviceData.leftChargedMode = data[30].toInt() if (deviceData.leftChargedMode == 1) { chargeCurrentErrorMessage = "Charger is off, pack left fully charged for too long. Drive golf cart until battery reaches less than 90%" chargeCurrentMap["leftCharged"] = 1 binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } else { chargeCurrentMap["leftCharged"] = 0 } deviceData.highVoltageMode = data[31].toInt() if (deviceData.highVoltageMode == 1) { chargeCurrentErrorMessage = "Charger is off, battery voltage is too high" chargeCurrentMap["highVoltage"] = 1 binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED)
{ "domain": "codereview.stackexchange", "id": 43806, "lm_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, hash-map, android, error-handling, kotlin", "url": null }
performance, hash-map, android, error-handling, kotlin binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } else { chargeCurrentMap["highVoltage"] = 0 } deviceData.highTempMode = data[32].toInt() if (deviceData.highTempMode == 1) { chargeCurrentErrorMessage = "Charger is off, battery temperature is too high" chargeCurrentMap["highTemp"] = 1 binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } else { chargeCurrentMap["highTemp"] = 0 } deviceData.lowTempMode = data[33 + increment].toInt() if (deviceData.lowTempMode == 1) { chargeCurrentErrorMessage = "Charger is off, battery temperature is too low" chargeCurrentMap["lowTemp"] = 1 binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } else { chargeCurrentMap["lowTemp"] = 0 }
{ "domain": "codereview.stackexchange", "id": 43806, "lm_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, hash-map, android, error-handling, kotlin", "url": null }
performance, hash-map, android, error-handling, kotlin if (increment == 0 && !chargeCurrentMap.containsValue(1)) { chargeCurrentErrorMessage = "" binding.textviewChargeCurrentStatus.text = "On" binding.textviewChargeCurrentStatus.setTextColor(currentTextColor) binding.questionIcon.visibility = View.GONE } else if (increment == 1) { deviceData.hotChargerMode = data[33].toInt() if (deviceData.hotChargerMode == 1) { chargeCurrentErrorMessage = "Charger resting for a moment to let the battery cool" chargeCurrentMap["hotCharger"] = 1 binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } else { chargeCurrentMap["hotCharger"] = 0 } if (!chargeCurrentMap.containsValue(1)) { chargeCurrentErrorMessage = "" binding.textviewChargeCurrentStatus.text = "On" binding.textviewChargeCurrentStatus.setTextColor(currentTextColor) binding.questionIcon.visibility = View.GONE } } } Answer: As a first step, we can move all the deviceData properties (except hotChargerMode) to the top of the method and change them to booleans, as the only thing you care about is if they are 0 or not. deviceData.restMode = data[28].toInt() != 0 deviceData.misbalancedMode = data[29].toInt() != 0 deviceData.leftChargedMode = data[30].toInt() != 0 deviceData.highVoltageMode = data[31].toInt() != 0 deviceData.highTempMode = data[32].toInt() != 0 deviceData.lowTempMode = data[33 + increment].toInt() != 0
{ "domain": "codereview.stackexchange", "id": 43806, "lm_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, hash-map, android, error-handling, kotlin", "url": null }
performance, hash-map, android, error-handling, kotlin The last else if (increment == 1) { can also be changed into an else { as increment can only be 1 or 0. Then we can clearly see that we have a lot of the following pattern: if (deviceData.something) { chargeCurrentErrorMessage = "...some message..." chargeCurrentMap["something"] = 1 binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } else { chargeCurrentMap["something"] = 0 } As we can see, some chargeCurrentMap are directly affected by the deviceData properties, so we can move them to the top as well: chargeCurrentMap["rest"] = deviceData.restMode chargeCurrentMap["misbalanced"] = deviceData.misbalancedMode chargeCurrentMap["leftCharged"] = deviceData.leftChargedMode chargeCurrentMap["highVoltage"] = deviceData.highVoltageMode chargeCurrentMap["highTemp"] = deviceData.highTempMode chargeCurrentMap["lowTemp"] = deviceData.lowTempMode Then we can see that we're basically doing the same thing if one of the values matches, and we're changing a text based on this, so we can use a when-statement for the text: val newMessage = when { deviceData.restMode -> "Battery full, charger is off" deviceData.misbalancedMode -> "Charging is paused, battery is resolving a minor issue" deviceData.leftChargedMode -> "Charger is off, pack left fully charged for too long. Drive golf cart until battery reaches less than 90%" deviceData.highVoltageMode -> "Charger is off, battery voltage is too high" deviceData.highTempMode -> "Charger is off, battery temperature is too high" deviceData.lowTempMode -> "Charger is off, battery temperature is too low" else -> null }
{ "domain": "codereview.stackexchange", "id": 43806, "lm_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, hash-map, android, error-handling, kotlin", "url": null }
performance, hash-map, android, error-handling, kotlin Then, if the message has a value, we use it, and set the textviewChargeCurrentStatus and questionIcon accordingly: if (newMessage != null) { chargeCurrentErrorMessage = newMessage binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } That leaves us with this: private var chargeCurrentMap = HashMap<String?, Int?>() private lateinit var chargeCurrentErrorMessage: String private fun processChargeModes(data: ByteArray, increment: Int = 0) { deviceData.restMode = data[28].toInt() != 0 deviceData.misbalancedMode = data[29].toInt() != 0 deviceData.leftChargedMode = data[30].toInt() != 0 deviceData.highVoltageMode = data[31].toInt() != 0 deviceData.highTempMode = data[32].toInt() != 0 deviceData.lowTempMode = data[33 + increment].toInt() != 0 chargeCurrentMap["rest"] = deviceData.restMode chargeCurrentMap["misbalanced"] = deviceData.misbalancedMode chargeCurrentMap["leftCharged"] = deviceData.leftChargedMode chargeCurrentMap["highVoltage"] = deviceData.highVoltageMode chargeCurrentMap["highTemp"] = deviceData.highTempMode chargeCurrentMap["lowTemp"] = deviceData.lowTempMode val newMessage = when { deviceData.restMode -> "Battery full, charger is off" deviceData.misbalancedMode -> "Charging is paused, battery is resolving a minor issue" deviceData.leftChargedMode -> "Charger is off, pack left fully charged for too long. Drive golf cart until battery reaches less than 90%" deviceData.highVoltageMode -> "Charger is off, battery voltage is too high" deviceData.highTempMode -> "Charger is off, battery temperature is too high" deviceData.lowTempMode -> "Charger is off, battery temperature is too low" else -> null }
{ "domain": "codereview.stackexchange", "id": 43806, "lm_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, hash-map, android, error-handling, kotlin", "url": null }
performance, hash-map, android, error-handling, kotlin if (newMessage != null) { chargeCurrentErrorMessage = newMessage binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } if (increment == 0 && !chargeCurrentMap.containsValue(1)) { chargeCurrentErrorMessage = "" binding.textviewChargeCurrentStatus.text = "On" binding.textviewChargeCurrentStatus.setTextColor(currentTextColor) binding.questionIcon.visibility = View.GONE } else { deviceData.hotChargerMode = data[33].toInt() if (deviceData.hotChargerMode == 1) { chargeCurrentErrorMessage = "Charger resting for a moment to let the battery cool" chargeCurrentMap["hotCharger"] = 1 binding.textviewChargeCurrentStatus.text = "Off" binding.textviewChargeCurrentStatus.setTextColor(Color.RED) binding.questionIcon.visibility = View.VISIBLE } else { chargeCurrentMap["hotCharger"] = 0 } if (!chargeCurrentMap.containsValue(1)) { chargeCurrentErrorMessage = "" binding.textviewChargeCurrentStatus.text = "On" binding.textviewChargeCurrentStatus.setTextColor(currentTextColor) binding.questionIcon.visibility = View.GONE } } } Which can still be shortened a bit, but I think that this is a good start. Note that you might need to re-order the when-statement conditions, as only the first matching one will be performed.
{ "domain": "codereview.stackexchange", "id": 43806, "lm_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, hash-map, android, error-handling, kotlin", "url": null }
python, python-3.x Title: Pascal's Triangle Generator Question: Pascal's triangle is a simple and effective way to expand a set of brackets in the form (a + b)ⁿ. In my code the user is asked an input for what order (n) they want and it outputs Pascal's triangle. The Code I added in comments to help you understand my reasoning. def get_super(x): # function to get superscript char. normal = "0123456789" super_s = "⁰¹²³⁴⁵⁶⁷⁸⁹" res = x.maketrans(''.join(normal), ''.join(super_s)) return x.translate(res) # the history_variable will be the variable returned when function is called. It will contain each co-efficient of every row. # the number of rows that the history_variable returns is provided by parameters(num) # I created save_variable as a variable I can use to store the previous row because I need it to create the next row. # current_variable is a variable that will contain the current row being made.
{ "domain": "codereview.stackexchange", "id": 43807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x def basic_pascals(num): history_variable = [[1], [1, 1]] save_variable = [1, 1] current_variable = [] amount = 0 # if the number given is 0 just return 1 as that is the first row. if num == 0: return([1]) # if the number given is 1 return [1, 1] as those are the coefficients of (a+b) elif num == 1: return([1, 1]) # otherwise we create a for loop that will loop through num-1 iterations - I of every loop here as the making of one row # in that loop we create a for loop over the save_variable and save_variable[1:] which will let us loop through every possible pair. # the reason I do this is because each co-efficient in the new row is equal to the addition of the two co_efficients directly above it in the previous row. # I then add every sum of every pair to the current-variable. # add 1 to the start and end and then I have the co-efficients of the row. # equate save_variable to current_variable # then append save_variable to history_variable # it repeats itself and finally history_variable is a list of lists each list containing the co-efficients of every row. for i in range(num-1): for item in zip(save_variable, save_variable[1:]): amount += sum(item) current_variable.append(amount) amount = 0 current_variable.append(1) current_variable.insert(0, 1) save_variable = current_variable current_variable = [] history_variable.append(save_variable) return history_variable # this is essentially adding the a's and b's to the co-efficients # specify the order you want and if the order == 0 or 1 then it just prints out 1 or (1a + 1b) # otherwise we make variable co-efficients and call basic_pascals to it. # power a will equal the highest power possible depending on the order of the row, i. # power b will equal 0. As you move through every term in a row, the power in a decreases and b increases
{ "domain": "codereview.stackexchange", "id": 43807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x # rest is forming f"string" to add it to the co-efficients
{ "domain": "codereview.stackexchange", "id": 43807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x def pascals_triangle(): # the n value of (a+b)^n order = int(input("Enter the order(n) you would like for (a+b)^n: ")) spacing = order*10 if order == 0: print(1) if order == 1: print(f"a{get_super('1')} + b{get_super('1')}") else: co_efficients = basic_pascals(order) for i, row in enumerate(co_efficients): power_a = i power_b = 0 result = f"" for item in row: a = f"a{power_a}" b = f"b{power_b}" if i == 0: result += f"{item}" elif power_a == 0: result += f"{item}{get_super(b)} + " elif power_b == 0: result += f"{item}{get_super(a)} + " else: result += f"{item}{get_super(a)}{get_super(b)} + " power_a -= 1 power_b += 1 result = result.strip(" + ") print(result.center(spacing)) pascals_triangle() Output Calling basic_pascals(8) [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1]] Calling pascals_triangle(8) 1 1a¹ + 1b¹ 1a² + 2a¹b¹ + 1b² 1a³ + 3a²b¹ + 3a¹b² + 1b³ 1a⁴ + 4a³b¹ + 6a²b² + 4a¹b³ + 1b⁴ 1a⁵ + 5a⁴b¹ + 10a³b² + 10a²b³ + 5a¹b⁴ + 1b⁵ 1a⁶ + 6a⁵b¹ + 15a⁴b² + 20a³b³ + 15a²b⁴ + 6a¹b⁵ + 1b⁶ 1a⁷ + 7a⁶b¹ + 21a⁵b² + 35a⁴b³ + 35a³b⁴ + 21a²b⁵ + 7a¹b⁶ + 1b⁷ 1a⁸ + 8a⁷b¹ + 28a⁶b² + 56a⁵b³ + 70a⁴b⁴ + 56a³b⁵ + 28a²b⁶ + 8a¹b⁷ + 1b⁸
{ "domain": "codereview.stackexchange", "id": 43807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x Improvements I want to make my code a bit more concise and easier to understand. I even have to think about why I do certain things sometimes. Answer: 0. Delete all the comments These paragraph-length comments make the code very hard to read. Comments should be a last resort for understanding the code since programmers only read them when they can't figure out what the code is doing. Well-written code doesn't just make the computer do the correct thing, but is also easy to understand by humans. Let's get rid of the comments and simplify the code. The fewer words written, the fewer chances for mistakes. I should expand on this. The best advice I've heard is this: comments should only explain what the code cannot. Comments that describe what the code is doing are useless because a programmer can just read the code. Here are some examples of useful types of comments: // This function implements <name of obscure algorithm> (<wikipedia link>) // You would think that doing XXX would be the obvious solution, but that doesn't work because of YYY, which means we have to do ZZZ. // This logic is required because of <business requirement> which is documented in <policy manual> on page 372. From my own experience, if I'm reading code I wrote some time ago and it takes me more than a few seconds to understand what I wrote, that's a good place for a short comment to explain what I was trying to do. Either that or it's a good place to rewrite the code into something more comprehensible. One of the longest comments I've ever written was next to a continue statement to explain why that loop iteration could be skipped. 1. Variable names Picking accurate and specific variable names makes reasoning about the code easier. Let's look at basic_pascals(): def basic_pascals(num): history_variable = [[1], [1, 1]] save_variable = [1, 1] current_variable = [] amount = 0 if num == 0: return([1]) elif num == 1: return([1, 1])
{ "domain": "codereview.stackexchange", "id": 43807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x for i in range(num-1): for item in zip(save_variable, save_variable[1:]): amount += sum(item) current_variable.append(amount) amount = 0 current_variable.append(1) current_variable.insert(0, 1) save_variable = current_variable current_variable = [] history_variable.append(save_variable) return history_variable The argument num is the degree of the last polynomial in the triangle, so use degree instead. The variable history_variable is the Pascal's Triangle, so let's rename it triangle. By tracking what happens to save_variable through the function, we see that it is always equal to the current last row of history_variable, so a natural name is last_row. The variable current_variable is the next row of the triangle being constructed, so let's call it next row. def basic_pascals(degree): triangle = [[1], [1, 1]] last_row = [1, 1] next_row = [] amount = 0 if degree == 0: return([1]) elif degree == 1: return([1, 1]) for i in range(degree-1): for item in zip(last_row, last_row[1:]): amount += sum(item) next_row.append(amount) amount = 0 next_row.append(1) next_row.insert(0, 1) last_row = next_row next_row = [] triangle.append(last_row) return triangle 2. Create variables near where they are needed Since you create the variables next_row, last_row, and amount outside of the loops, you need to reset them at the end of the loops. If you move these to inside the loop, then they will be reset automatically at the beginning of each loop and you can delete the lines that reset the variables. def basic_pascals(degree): triangle = [[1], [1, 1]] if degree == 0: return([1]) elif degree == 1: return([1, 1])
{ "domain": "codereview.stackexchange", "id": 43807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x for i in range(degree-1): next_row = [] last_row = triangle[-1] for item in zip(last_row, last_row[1:]): amount = 0 amount += sum(item) next_row.append(amount) next_row.append(1) next_row.insert(0, 1) triangle.append(next_row) return triangle Now we can see that amount in the innermost loop is always equal to sum(item), so let's just use the latter expression. def basic_pascals(degree): triangle = [[1], [1, 1]] if degree == 0: return([1]) elif degree == 1: return([1, 1]) for i in range(degree-1): next_row = [] last_row = triangle[-1] for item in zip(last_row, last_row[1:]): next_row.append(sum(item)) next_row.append(1) next_row.insert(0, 1) triangle.append(next_row) return triangle 3. Expressive loop conditions How do we know we are done constructing the triangle? An n-th degree Pascal's Triangle has n+1 rows. This makes for a more expressive loop condition that lets the programmer know when the construction is complete. Most of the time, if a loop variable is not used, i in this case, that is a good indication that there is a better way to write it. def basic_pascals(degree): triangle = [[1], [1, 1]] if degree == 0: return([1]) elif degree == 1: return([1, 1]) while len(triangle) < degree + 1: next_row = [] last_row = triangle[-1] for item in zip(last_row, last_row[1:]): next_row.append(sum(item)) next_row.append(1) next_row.insert(0, 1) triangle.append(next_row) return triangle
{ "domain": "codereview.stackexchange", "id": 43807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x 4. Consistent return values Right now, there are two possible return types: a list of lists [[]] if degree >= 2 and a list [] otherwise. If you make the types of all possible return values the same, then any code that calls this function can be simpler because it only has to handle one data type. This function should construct the full triangle, so all return statements should return a list of lists representing the full triangle. def basic_pascals(degree): triangle = [[1], [1, 1]] if degree == 0: return [[1]] elif degree == 1: return [[1], [1, 1]] while len(triangle) < degree + 1: next_row = [] last_row = triangle[-1] for item in zip(last_row, last_row[1:]): next_row.append(sum(item)) next_row.append(1) next_row.insert(0, 1) triangle.append(next_row) return triangle Now, pascals_triangle() doesn't need special cases for degrees 0 and 1. 5. Removing special cases. Now that all return values return the same data type, do we even need the special cases for degree=0 and degree=1? Let's delete the initial if block and replace the initial value of triangle with [[1]]. def basic_pascals(degree): triangle = [[1]] while len(triangle) < degree + 1: next_row = [] last_row = triangle[-1] for item in zip(last_row, last_row[1:]): next_row.append(sum(item)) next_row.append(1) next_row.insert(0, 1) triangle.append(next_row) return triangle This still returns the correct answer. 6. Replace for ... append with list comprehensions The inner for loop can be expressed as a single line to make the full list. This is called a list comprehension. def basic_pascals(degree): triangle = [[1]]
{ "domain": "codereview.stackexchange", "id": 43807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x while len(triangle) < degree + 1: last_row = triangle[-1] next_row = [sum(item) for item in zip(last_row, last_row[1:])] next_row.append(1) next_row.insert(0, 1) triangle.append(next_row) return triangle We can even incorporate the ones on the start and end. def basic_pascals(degree): triangle = [[1]] while len(triangle) < degree + 1: last_row = triangle[-1] next_row = [1] + [sum(item) for item in zip(last_row, last_row[1:])] + [1] triangle.append(next_row) return triangle I added space before the return statement to emphasize the three steps: initialize triangle, construct triangle, return triangle. Other parts of the code In pascals_triangle(), in addition to making similar changes as described above, you can create a function that takes co_efficient, power_a, and power_b as argument to make each term in the polynomial. This will simplify the loop and give you more freedom to get the notation correct. Rather than trying to build the whole expression at once, it is simpler to build a list of terms (terms = ["1a³", "3a²b¹", "3a¹b²", "1b³"]) and then use " + ".join(terms) to create the full string. Then, you don't have to use strip() at the end.
{ "domain": "codereview.stackexchange", "id": 43807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x, validation, error-handling, deque Title: Take in 10 numbers, validate each input, append then in a list and then prints the sum of the list values Question: I'm practicing loops in Python and started trying to have a better approach with user inputs, is there better ways of dealing with inputs when coding? And I tried using deques too, it worked very well, but don't know if I should or need to; are deques better in this case or should I keep using lists? sum_numbers: list = list() for question in range(1, 11): while True: try: print(f'{question}º number: ') asnwer = float(input('-> ').strip().replace(',', '.')) except ValueError: print('Invalid input! Try again...\n') continue else: sum_numbers.append(asnwer) break print( '\nNumbers:\n' f'{sum_numbers}\n'.replace('[', '').replace(']', '') + f'\nSum: {sum(sum_numbers)}.' ) Answer: performatic isn't a word, and in the software development industry this is more frequently written performant. Anyway, performance is not at all a concern in this program and you should be more concerned about correctness, maintainability and legibility. If you're trying to accommodate commas as decimals, that's localisation (L10N). Python has support for localisation, and you should use it. Consider rewriting your input loop as an iterator function. asnwer is spelled answer. Don't convert a list to a string and then .replace() on it - instead .join() the sequence with a separator of your choice. You don't need a continue/else: you can break right out of the try. Suggested from locale import atof, format_string, setlocale, LC_ALL from typing import Iterator def get_numbers(n: int) -> Iterator[float]: for question in range(1, n + 1): while True: try: yield atof(input(f'{question}º número: ')) break except ValueError: print('Entrada inválida! Tente novamente...')
{ "domain": "codereview.stackexchange", "id": 43808, "lm_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, validation, error-handling, deque", "url": null }
python, python-3.x, validation, error-handling, deque def main() -> None: setlocale(LC_ALL, 'pt-PT') numbers = tuple(get_numbers(10)) formatted_numbers = ", ".join( format_string('%.1f', x) for x in numbers ) print( '\nNúmeros:' f'\n{formatted_numbers}' f'\nSoma: {format_string("%.1f", sum(numbers))}.' ) if __name__ == '__main__': main() Output 1º número: 7.5 2º número: 3,50 3º número: 4,2 4º número: 5 5º número: 5 6º número: 5 7º número: 5 8º número: 5 9º número: 5 10º número: 5 Números: 7,5, 3,5, 4,2, 5,0, 5,0, 5,0, 5,0, 5,0, 5,0, 5,0 Soma: 50,2.
{ "domain": "codereview.stackexchange", "id": 43808, "lm_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, validation, error-handling, deque", "url": null }
c++, compression Title: Huffman Coding implementation in C++ Question: Here is an implementation of compression with Huffman coding. It works well by my testing. It compresses a 1 GB string in about 30 seconds, and decompresses in about 15 seconds with VisualStudio 2022 "Release Mode x64" on my machine. I've used std::vector<bool> as the "bitset", but simply replacing that type with boost::dynamic_bitset and leaving everything else as-is also works fine. I would appreciate all comments. [GitHub Repository] Huffman.h: // Huffman coding // https://en.wikipedia.org/wiki/Huffman_coding #ifndef HUFFMAN_H #define HUFFMAN_H #pragma once #include <cstddef> #include <cstdint> #include <span> #include <string_view> #include <vector> namespace Huffman { namespace detail { // Easily serializable: // Trivial type with well-defined size of all fields. struct Node { std::int16_t left; // Left Node in tree. -1 means 'none' std::int16_t right; // Right Node in tree. -1 means 'none' std::uint8_t value; // Char value but always unsigned [[nodiscard]] constexpr bool isLeaf() const noexcept { return (left == -1) && (right == -1); } }; } // namespace detail // This class represents fully compressed text struct Encoded { private: std::vector<bool> binary_data_; // bitset to store data compactly std::vector<detail::Node> nodes_; // the tree void init_tree(std::span<std::uint8_t const> input_data); void init_binary_data(std::span<std::uint8_t const> input_data); // Root element is always the last one. // There is _always_ at least 1 element. [[nodiscard]] auto const &root() const { return nodes_.back(); } [[nodiscard]] auto root_index() const { return static_cast<int16_t>(nodes_.size() - 1); } Encoded() = default;
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression Encoded() = default; public: static Encoded encode(std::span<std::uint8_t const> input_data); static Encoded encode(void const *source, std::size_t size); static Encoded encode(std::span<std::byte const> input_data); static Encoded encode(std::string_view input_data); [[nodiscard]] std::string decode() const; }; } // namespace Huffman #endif // HUFFMAN_H Huffman.cpp: #include "Huffman.h" #include <array> #include <cassert> #include <cstdint> #include <execution> #include <queue> #include <span> using Huffman::detail::Node, Huffman::Encoded, std::int16_t, std::uint8_t, std::size_t; // We need the counts while encoding, but not later one. struct NodeWithCount { Node node; size_t count; }; // Given a range of bytes, return the count of each unique value. constexpr auto count_bytes(std::span<uint8_t const> const bytes) noexcept { std::array<size_t, UCHAR_MAX + 1> counts = {}; for (auto const ch: bytes) { ++counts[ch]; } return counts; } // Given the number of each unique byte value, form the "leaf" nodes of our tree static auto make_leaf_nodes(std::span<size_t const> const counts) { std::vector<NodeWithCount> nodes; for (size_t i = 0, sz = counts.size(); i < sz; ++i) { if (counts[i]) { nodes.push_back(NodeWithCount{Node{-1, -1, static_cast<uint8_t>(i)}, counts[i]}); } } return nodes; } // This type is intended to store the "path" to each character // in our tree. Used to "encode" the data initially. // '\0' -> left // '\1' -> right using CharDictT = std::array<std::string, UCHAR_MAX + 1>; static auto init_dict(std::vector<Node> const &nodes, int16_t root, CharDictT &dict, std::string &key) { if (root < 0) { return; } assert(root < nodes.size()); auto const &elm = nodes[root]; if (elm.isLeaf()) { dict[elm.value] = key; return; }
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression auto const &elm = nodes[root]; if (elm.isLeaf()) { dict[elm.value] = key; return; } key.push_back(0); init_dict(nodes, elm.left, dict, key); key.back() = 1; init_dict(nodes, elm.right, dict, key); key.pop_back(); } std::string Huffman::Encoded::decode() const { // https://en.wikipedia.org/wiki/Huffman_coding#Decompression auto node = root(); std::string str; for (bool i: binary_data_) { auto const go_right = i; node = nodes_[go_right ? node.right : node.left]; if (node.isLeaf()) { str += static_cast<char>(node.value); node = root(); } } return str; } Encoded Encoded::encode(std::span<std::uint8_t const> input_data) { // https://en.wikipedia.org/wiki/Huffman_coding#Compression Encoded encoded; encoded.init_tree(input_data); encoded.init_binary_data(input_data); return encoded; } void Encoded::init_tree(std::span<std::uint8_t const> const input_data) { auto nodes_with_size = make_leaf_nodes(count_bytes(input_data)); auto const cmp = [&nodes_with_size](int16_t const lhs, int16_t const rhs) noexcept -> bool { // reverse compare return nodes_with_size[lhs].count > nodes_with_size[rhs].count; }; auto queue = std::priority_queue<int16_t, std::vector<int16_t>, decltype(cmp)>(cmp); for (int16_t i = 0, sz = static_cast<int16_t>(nodes_with_size.size()); i < sz; ++i) { if (nodes_with_size[i].count) { queue.push(i); } } // 0 and 1 are trivial cases that the later while loop does not handle. switch (queue.size()) { case 0: nodes_ = {Node{-1, -1, 0}}; return; case 1: nodes_ = {Node{-1, -1, input_data.front()}, Node{-1, 0, 0}}; return; default: break; }
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression while (queue.size() > 1) { auto back1 = queue.top(); queue.pop(); auto back2 = queue.top(); queue.pop(); nodes_with_size.push_back( NodeWithCount{Node{back1, back2, 0}, nodes_with_size[back1].count + nodes_with_size[back2].count}); queue.push(static_cast<int16_t>(nodes_with_size.size() - 1)); } nodes_.resize(nodes_with_size.size()); std::transform(nodes_with_size.begin(), nodes_with_size.end(), nodes_.begin(), [](NodeWithCount const &withCount) -> auto & { return withCount.node; }); } static auto init_dict(std::vector<Node> const &nodes, int16_t root, CharDictT &dict) { std::string key; init_dict(nodes, root, dict, key); } void Huffman::Encoded::init_binary_data(std::span<std::uint8_t const> const input_data) { // Step 1: Create a dictionary with paths for all characters CharDictT dict = {}; init_dict(nodes_, root_index(), dict); // Step 2: Calculate the final length of the binary data // This binary operator handles out-of-sequence sums for std::reduce struct BinOp { // The dictionary is just a pointer, because functors are often copied in C++, // and we don't want to copy 256 std::strings left and right. CharDictT *dict; [[nodiscard]] auto operator()(size_t const a, size_t const b) const noexcept { return a + b; } [[nodiscard]] auto operator()(size_t const a, uint8_t const b) const noexcept { return a + (*dict)[b].size(); } [[nodiscard]] auto operator()(uint8_t const a, size_t const b) const noexcept { return (*dict)[a].size() + b; } [[nodiscard]] auto operator()(uint8_t const a, uint8_t const b) const noexcept { return (*dict)[a].size() + (*dict)[b].size(); } }; auto const size = std::reduce(std::execution::par_unseq, input_data.begin(), input_data.end(), size_t{}, BinOp{&dict}); binary_data_.resize(size); // Step 3: Concat all paths
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression binary_data_.resize(size); // Step 3: Concat all paths size_t bit_iter = 0; for (uint8_t ch: input_data) { for (auto const &bit: dict[ch]) { binary_data_[bit_iter++] = !!bit; } } } Encoded Encoded::encode(void const *const source, std::size_t const size) { return encode(std::span{static_cast<std::uint8_t const *>(source), size}); } Encoded Encoded::encode(std::span<std::byte const> const input_data) { return encode(input_data.data(), input_data.size()); } Encoded Encoded::encode(std::string_view const input_data) { return encode(input_data.data(), input_data.size()); } main.cpp: #include "Huffman.h" #include <string_view> #include <iostream>
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression main.cpp: #include "Huffman.h" #include <string_view> #include <iostream> int main() { constexpr std::string_view str = "Four score and seven years ago our fathers brought forth on this continent, a new nation, " "conceived in Liberty, and dedicated to the proposition that all men are created equal.\n" "Now we are engaged in a great civil war, testing whether that nation, or any nation so " "conceived and so dedicated, can long endure.We are met on a great battle - field of that " "war.We have come to dedicate a portion of that field, as a final resting place for those " "who here gave their lives that that nation might live.It is altogether fittingand proper that we should do this.\n" "But, in a larger sense, we can not dedicate - we can not consecrate - we can not " "hallow - this ground.The brave men, livingand dead, who struggled here, have consecrated " "it, far above our poor power to add or detract.The world will little note, nor long remember " "what we say here, but it can never forget what they did here.It is for us the living, rather, " "to be dedicated here to the unfinished work which they who fought here have thus far so nobly " "advanced.It is rather for us to be here dedicated to the great task remaining before us - that " "from these honored dead we take increased devotion to that cause for which they gave the last " "full measure of devotion - that we here highly resolve that these dead shall not have died in " "vain - that this nation, under God, shall have a new birth of freedom - and that government of " "the people, by the people, for the people, shall not perish from the earth."; auto const encoded = Huffman::Encoded::encode(str); auto const decoded = encoded.decode(); if (str == decoded) { std::cout << "Test Passed\n"; } else { std::cout << "Test Failed\n"; } } Answer: Storing codewords as std::string
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression Answer: Storing codewords as std::string // This type is intended to store the "path" to each character // in our tree. Used to "encode" the data initially. // '\0' -> left // '\1' -> right using CharDictT = std::array<std::string, UCHAR_MAX + 1>;
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression Having an array of codewords is a good idea, storing them as strings is good for debugging purposes but not so good for anything else. As an alternative, you may consider storing a pair of (length, bits) as eg an pair<size_t, size_t> or some other suitable integer types. Having a pair of length and bits in hand, rather than a string, would then enable you to append those bits to your compressed storage using a couple of efficient bitwise operations, rather than an iteration through a string and a bunch of bit-by-bit appends. An approach like that wouldn't combine well with vector<bool> which unfortunately has an interface that required bit-by-bit operations to begin with, but something like an vector<uint8_t> (or some other fixed-width unsigned integer type) could be suitable. Note that with the data stored as vector<uint8_t> (or similar), the decoder would need some independent mechanism to detect the end of the data (such as storing the uncompressed length, or an end-of-data symbol, or both), otherwise it may try to decode the padding bits in the last element. As a quick test, I implemented such a thing so as to be compatible with your decoder (when each byte of the result is read bit-by-bit from the most significant bit down). The code that does the encoding looked like this: (this is just a quickly thown-together implementation of this technique) size_t out_index = 0; uint32_t buffer = 0; size_t bits_in_buffer = 0; for (uint8_t ch : input_data) { auto& code = dict[ch]; buffer <<= code.first; buffer |= code.second; bits_in_buffer += code.first; while (bits_in_buffer >= 8) { binary_data_[out_index++] = buffer >> (bits_in_buffer - 8); bits_in_buffer -= 8; } } if (bits_in_buffer) { binary_data_[out_index++] = buffer << (8 - bits_in_buffer); }
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression On my PC, compressing about 1GB of data (I used your test string, concatenated with itself a bunch of times) took around 8000 milliseconds with the string-based method, and around 1900 milliseconds with the bitmath-based method. Serializing the whole tree Serializing the whole tree could cost 8 bytes per node (thanks to alignment) or at least 5 bytes (if packed), with roughly twice as many nodes as leafs that amounts to around 10-16 bytes per symbol in the alphabet. That could be 4KB just for the tree. Using canonical Huffman code makes it easy to build a decoding table(see below) straight from merely the array of code lengths, which could be easily stored in 1 byte each, or could be compressed further if you want (eg DEFLATE uses both Huffman coding and run-length encoding to compress its table of code lengths, see section 3.2.7). Bit-by-bit decoding Bit-by-bit decoding is simple but inherently inefficient, there are more efficient alternatives based on decoding multiple bits at once using lookup tables. You can see that as turning the binary tree into a k-ary trie, eg a 4-ary trie with 4 children per node would mostly decode 2 bits at the time, though it does not perfectly halve the depth of the tree due to odd length "wasting" some of the potential (resulting in a node that has fewer than 4 unique children, with one or two being duplicated). If you set a length limit on the codes that the encoder produces (many application of Huffman coding specify a length limit for this reason), k can be set equal to that limit, meaning that the decoding trie becomes just a single-layer aka a decoding array, with which a symbol can be decoded in just one lookup. Naturally that array would be full of duplicates, having a length of 2k but only UCHAR_MAX + 1 unique values. I've explained that approach to decoding in more detail in earlier answers to different questions such as Huffman Coding library implemented in C but I'd be happy to go in whatever detail you want.
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression By the way it may be attractive to set k high or to leave it unlimited, but while that is required for the theoretical proof of optimality of Huffman coding (under the assumptions which that proof makes), increasing the length limit above 16 is typically underwhelming in practice(see below). DEFLATE sets a limit of 15, JPEG sets a limit of 16, Bzip2 sets a limit of 20 which is on the high end. High k can be supported with a small decoding table by using advanced decoding techniques. As a practical example, I took the common text compression test file "alice29.txt", concatenated it 10 times, and compressed it with length-limited Huffman codes (using a simple length limiting scheme, not optimal length-limited codes), using 32-bit output chunks instead of 8-bit but that matters little. The "natural" maximum codeword length was 17 bits, so going above that automatically makes no difference. Sizes include the file header.
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
c++, compression length limit compressed size (in bytes) 17 876948 16 876952 15 877000 14 877128 13 877504 12 877504 (not a copy&paste mistake) 11 878244 10 881016 10 bits was noticeably worse than the others, but 15 bits was already so far into the diminishing returns that increasing the codelength limit from 14 to 15 represents an improve of about one in ten thousand. Data with a more skewed distribution benefits more from a higher codelength limit, so these results should not be generalized too much.
{ "domain": "codereview.stackexchange", "id": 43809, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, compression", "url": null }
python, parsing, recursion, xml, scrapy Title: Parsing an XML tree of categories Question: I have parse function which is parsing tree of categories. I've written it in simplest way possible and now struggling with refactoring it. Every nested loop is doing the same stuff but appending object to object childs initialized at the top. I think it's possible to refactor it with recursion but I'm struggling with it. How to wrap it in recursion function to prevent code duplication? Final result should be a list of objects or just yield top level object with nested childs. for container in category_containers: root_category_a = container.xpath("./a") root_category_title = root_category_a.xpath("./*[1]/text()").get() root_category_url = self._host + root_category_a.xpath("./@href").get() root = { "title": root_category_title, "url": root_category_url, "childs": [], } subcategory_rows1 = container.xpath("./div/div") for subcat_row1 in subcategory_rows1: subcategory_a = subcat_row1.xpath("./a") subcategory_title = subcategory_a.xpath("./*[1]/text()").get() subcategory_url = self._host + subcategory_a.xpath("./@href").get() subcat1 = { "title": subcategory_title, "url": subcategory_url, "childs": [], } subcategory_rows2 = subcat_row1.xpath("./div/div")
{ "domain": "codereview.stackexchange", "id": 43810, "lm_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, parsing, recursion, xml, scrapy", "url": null }
python, parsing, recursion, xml, scrapy subcategory_rows2 = subcat_row1.xpath("./div/div") for subcat_row2 in subcategory_rows2: subcategory2_a = subcat_row2.xpath("./a") subcategory2_title = subcategory2_a.xpath("./*[1]/text()").get() subcategory2_url = self._host + subcategory2_a.xpath("./@href").get() subcat2 = { "title": subcategory2_title, "url": subcategory2_url, "childs": [], } subcategory_rows3 = subcat_row2.xpath("./div/div") for subcat_row3 in subcategory_rows3: subcategory3_a = subcat_row3.xpath("./a") subcategory3_title = subcategory3_a.xpath("./*[1]/text()").get() subcategory3_url = self._host + subcategory3_a.xpath("./@href").get() subcat3 = { "title": subcategory3_title, "url": subcategory3_url, "childs": [], } subcat2['childs'].append(subcat3) subcat1['childs'].append(subcat2) root['childs'].append(subcat1) yield root Answer: You can start by just extracting the bit that clearly is repeated into a standalone function: def get_category(category) -> dict[str, Any]: category_a = category.xpath("./a") category_title = category_a.xpath("./*[1]/text()").get() category_url = self._host + category_a.xpath("./@href").get() return { "title": category_title, "url": category_url, "childs": [], } and then turn your code into something like: for container in category_containers: root = get_category(container) for subcontainer in container.xpath("./div/div"): subcategory = get_category(subcontainer)
{ "domain": "codereview.stackexchange", "id": 43810, "lm_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, parsing, recursion, xml, scrapy", "url": null }
python, parsing, recursion, xml, scrapy for subsubcontainer in subcontainer.xpath("./div/div"): subsubcategory = get_category(subsubcontainer) for subsubsubcontainer in subcontainer.xpath("./div/div"): subsubsubcategory = get_category(subsubsubcontainer) subsubcategory["childs"].append(subsubsubcategory) subcategory["childs"].append(subsubcategory) root["childs"].append(subcategory) yield root For recursion to work with this problem you're going to need to define the maximum depth somehow - I think this might work, but also otherwise I think you'll get the jist of it: def recurse_categories(container, depth = 0): if depth > 2: return None category = get_category(container) subcategory = recurse_categories(category, depth + 1) if subcategory is not None: category["childs"].append(subcategory)
{ "domain": "codereview.stackexchange", "id": 43810, "lm_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, parsing, recursion, xml, scrapy", "url": null }
java, beginner, mvc, javafx, crud Title: JavaFX CRUD app for rescue animals Question: I'm fairly new to Java, and I've been working on the following program. It's a basic CRUD app utilizing JavaFX and MVC design pattern. I'm seeking advice because the class I took on Java only covered the fundamentals of syntax. So I need to improve when it comes to proper design and standards. Even though my program works, I don't know if I'm doing things the right way. A couple of specific points of concern: I'm getting a recommendation from the IDE that I should generify AddAnimalController. However, I'm not exactly sure how this should be done in this context. I ran into a bit of a hurdle regarding serialization. I must use SimpleStringProperty for the data I want to display within the TableView, but SimpleStringProperty isn't serializable. So as a workaround, I created String fields to store a copy of such properties for serialization. It works, but I'm sure there's a more professional way of solving this problem. Any advice on my code or things I should focus on to improve my skills is greatly appreciated. Core classes: MainViewController package com.crud.gsjavafx.controllers; import com.crud.gsjavafx.models.AnimalList; import com.crud.gsjavafx.models.RescueAnimal; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.TextFieldTableCell; import javafx.stage.Stage; import java.io.IOException; import java.net.URL; import java.util.Optional; import java.util.ResourceBundle;
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud /** Controller for MainView. Handles ListView display as well as initiating actions on listView. */ public class MainViewController implements Initializable { @FXML private TableView<RescueAnimal> tableView; @FXML private TableColumn<RescueAnimal, String> colName; @FXML private TableColumn<RescueAnimal, String> colSpecies; @FXML private TableColumn<RescueAnimal, String> colLocation; /** Initialize ListView with the saved ArrayList, AnimalList.allAnimals. */ @Override public void initialize(URL url, ResourceBundle resourceBundle) { try { AnimalList.initializeList(); colName.setCellValueFactory(data -> data.getValue().animalNameProperty()); colSpecies.setCellValueFactory(data -> data.getValue().animalSpeciesProperty()); colLocation.setCellValueFactory(data -> data.getValue().locationProperty()); colName.setCellFactory(TextFieldTableCell.forTableColumn()); colSpecies.setCellFactory(TextFieldTableCell.forTableColumn()); colLocation.setCellFactory(TextFieldTableCell.forTableColumn()); tableView.setItems(AnimalList.allAnimals); } catch(Exception e) { e.printStackTrace(); } // Set double-click event. tableView.setOnMouseClicked(click -> { if (click.getClickCount() == 2) { editAnimalWindow(getSelection()); } }); } public RescueAnimal getSelection() { return tableView.getSelectionModel().getSelectedItem(); } /** Handles action for the 'Add' Button. */ public void addNewButton() { editAnimalWindow(null); } /** Handles action for the 'Edit' Button. */ public void editButton() { editAnimalWindow(getSelection()); }
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud /** Opens new window to edit selected animal. */ public void editAnimalWindow(RescueAnimal selectedAnimal) { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/crud/gsjavafx/addAnimalView.fxml")); Parent root = loader.load(); if (selectedAnimal != null) { AddAnimalController controller = loader.getController(); controller.setSelectedAnimal(selectedAnimal); controller.setFields(); } Stage stage = new Stage(); if (selectedAnimal != null) { stage.setTitle("Updating: " + selectedAnimal.getName()); } else { stage.setTitle("Add New Animal to Record:"); } stage.setScene(new Scene(root)); stage.show(); } catch (IOException e) { e.printStackTrace(); } } /** Deletes selected animal after confirmation. */ public void deleteSelection() { RescueAnimal selectedAnimal = getSelection(); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirm deletion:"); alert.setHeaderText("Warning: Clicking 'OK' will remove " + selectedAnimal.getName() + " from record."); alert.setContentText("Click 'OK' to continue or 'Cancel' to cancel this request."); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { AnimalList.allAnimals.remove(selectedAnimal); AnimalList.saveAnimalList(); } else { alert.close(); } } } AddAnimalController package com.crud.gsjavafx.controllers;
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud AddAnimalController package com.crud.gsjavafx.controllers; import com.crud.gsjavafx.models.AnimalList; import com.crud.gsjavafx.models.RescueAnimal; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.stage.Window; import java.net.URL; import java.time.LocalDate; import java.util.ArrayList; import java.util.ResourceBundle; /** Create and add animal to AnimalList.allAnimals then serialize. */ public class AddAnimalController implements Initializable { @FXML private GridPane grid; @FXML Button saveButton; @FXML TextField animalName; @FXML TextField animalType; @FXML ChoiceBox<String> gender; @FXML Spinner<Integer> age; @FXML Spinner<Integer> weight; @FXML DatePicker acquisitionDate; @FXML TextField animalLocation; @FXML Spinner<Integer> trainingStatus; @FXML CheckBox reserved; private RescueAnimal selectedAnimal; private final ArrayList<InputValidationController<Node>> nodes = new ArrayList<>(); /** Allows MainViewController to set the instance that's being edited. */ public void setSelectedAnimal(RescueAnimal selectedAnimal) { this.selectedAnimal = selectedAnimal; }
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud @Override public void initialize(URL url, ResourceBundle resourceBundle) { for (Node node : grid.getChildren()) { if (node instanceof Spinner) { InputValidationController<Node> fieldController = new InputValidationController<>((Spinner<Integer>) node); nodes.add(fieldController); } else if (node instanceof TextField) { InputValidationController<Node> fieldController = new InputValidationController<>((TextField) node); nodes.add(fieldController); } else if (node instanceof DatePicker) { InputValidationController<Node> fieldController = new InputValidationController<>((DatePicker) node); nodes.add(fieldController); } } } /** Populates fields with the passed instance. */ public void setFields() { final int maxAge = 100; final int maxWeight = 999; final int maxTrainingLevel = 5; animalName.setText(selectedAnimal.getName()); animalType.setText(selectedAnimal.getAnimalType()); gender.setValue(selectedAnimal.getGender()); age.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(selectedAnimal.getAge(), maxAge)); weight.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(selectedAnimal.getWeight(), maxWeight)); acquisitionDate.setValue(LocalDate.parse(selectedAnimal.getAcquisitionDate())); animalLocation.setText(selectedAnimal.getLocation()); trainingStatus.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory( selectedAnimal.getTrainingStatus(), maxTrainingLevel)); reserved.setSelected(selectedAnimal.getReserved()); }
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud /** Handles action for Save button */ public void save() { for (InputValidationController<Node> node : nodes) { if (node.getError()) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error: Save Failed"); alert.setHeaderText("Please review the form and try again."); alert.setContentText("Ensure all fields are set and contain valid data."); alert.show(); return; } } saveAnimal(); } public void saveAnimal() { if (selectedAnimal != null) { selectedAnimal.setName(animalName.getText()); selectedAnimal.setAnimalType(animalType.getText()); selectedAnimal.setGender(gender.getValue()); selectedAnimal.setAge(Integer.parseInt(age.getValue().toString())); selectedAnimal.setWeight(Integer.parseInt(weight.getValue().toString())); selectedAnimal.setAcquisitionDate(acquisitionDate.getValue().toString()); selectedAnimal.setLocation(animalLocation.getText()); selectedAnimal.setTrainingStatus(Integer.parseInt(trainingStatus.getValue().toString())); selectedAnimal.setReserved(reserved.isSelected()); selectedAnimal.setSerializableName(animalName.getText()); selectedAnimal.setSerializableSpecies(animalType.getText()); selectedAnimal.setSerializableLocation(animalLocation.getText()); } else { RescueAnimal newAnimal = new RescueAnimal(animalName.getText(), animalType.getText(), gender.getValue(), Integer.parseInt(age.getValue().toString()), Integer.parseInt(weight.getValue().toString()), acquisitionDate.getValue().toString(), animalLocation.getText(), Integer.parseInt(trainingStatus.getValue().toString()), reserved.isSelected());
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud AnimalList.setAllAnimals(newAnimal); } AnimalList.saveAnimalList(); closeWindow(); } public void closeWindow() { Window window = animalName.getScene().getWindow(); window.hide(); } } InputValidationController package com.crud.gsjavafx.controllers; import javafx.scene.Node; import javafx.scene.control.*; import java.time.LocalDate; public class InputValidationController<T extends Node> { private boolean error; private final Tooltip toolTip = new Tooltip(); /** TextField constructor. */ public InputValidationController (TextField field) { validString(field); toolTip.setText("Input is required and may not contain digits."); field.setTooltip(toolTip); } /** DatePicker Constructor. */ public InputValidationController (DatePicker date) { validDate(date); toolTip.setText("Cannot choose a future date."); date.setTooltip(toolTip); } /** Spinner Constructor. */ public InputValidationController (Spinner<Integer> numField) { validNumber(numField); toolTip.setText("Input may not contain digits and must be within specified range."); numField.setTooltip(toolTip); } private void validString(TextField field) { if (field.getText() == null) { error = true; }
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud field.setTextFormatter(new TextFormatter<>(c -> { if (c.isContentChange()) { if (c.getControlNewText().length() == 0) { error = true; raiseWarning(field); return c; } if (c.getControlNewText().isEmpty()) { return c; } if (c.getControlNewText().length() > 20) { return null; } if (!c.getControlNewText().matches("^[A-Za-z]+$")) { raiseWarning(field); return null; } else { suppressError(); return c; } } return c; })); } private void validDate (DatePicker date) { LocalDate today = LocalDate.now(); date.setValue(today); date.setOnAction(e -> { if (today.isBefore(date.getValue())) { raiseWarning(date); date.setValue(today); } else { suppressError(); } }); } private void validNumber(Spinner<Integer> numField) { numField.getEditor().textProperty().addListener((observable, oldV, newV) -> { if (!newV.matches("\\d*") || newV.length() == 0) { raiseWarning(numField); numField.getEditor().setText("0"); } }); } private void raiseWarning(Node node) { double x = node.getScene().getWindow().getX() + node.getLayoutX(); double y = node.getScene().getWindow().getY() + node.getLayoutY(); toolTip.setAutoHide(true); toolTip.show(node, x, y); } private void suppressError() { error = false; } public boolean getError() { return this.error; } } Serializer (util) package com.crud.gsjavafx.utils;
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud Serializer (util) package com.crud.gsjavafx.utils; import com.crud.gsjavafx.models.AnimalList; import com.crud.gsjavafx.models.RescueAnimal; import javafx.collections.ObservableList; import java.io.*; import java.util.ArrayList; /** Serialize and deserialize ArrayList AnimalList.allAnimals (see: {@link AnimalList}). */ public final class Serializer { private static final String PATH = "data.bin"; /** Serializer is static-only, and not to be instantiated. */ private Serializer() {} public static void serialize(ObservableList<RescueAnimal> observableListAnimals) throws IOException { try(var serializer = new ObjectOutputStream(new FileOutputStream(PATH, false))) { ArrayList<RescueAnimal> convertedList = new ArrayList<>(observableListAnimals); serializer.writeObject(convertedList); } } public static ArrayList<RescueAnimal> deserialize() throws IOException, ClassNotFoundException { try(ObjectInputStream objectIn = new ObjectInputStream(new FileInputStream(PATH))) { ArrayList<RescueAnimal> deserializedArrayList = new ArrayList<>(); for (RescueAnimal animal : (ArrayList<RescueAnimal>) objectIn.readObject()) { RescueAnimal deserializedAnimal = new RescueAnimal( animal.getSerializableName(), animal.getSerializableSpecies(), animal.getGender(), animal.getAge(), animal.getWeight(), animal.getAcquisitionDate(), animal.getSerializableLocation(), animal.getTrainingStatus(), animal.getReserved() ); deserializedArrayList.add(deserializedAnimal); } return deserializedArrayList; } } } AnimalList (model helper so to speak) package com.crud.gsjavafx.models; import com.crud.gsjavafx.utils.Serializer; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.io.IOException;
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud /** * A global list of RescueAnimal objects; stores all animals in an ArrayList for serialization. */ public final class AnimalList { public static ObservableList<RescueAnimal> allAnimals = FXCollections.observableArrayList(); /** AnimalList is static-only, and not to be instantiated. */ private AnimalList() {} /** * Populate public static field, allAnimals, on program start. * * @return the deserialized ArrayList composed of RescueAnimal(s). */ public static void initializeList() { try { allAnimals.addAll(Serializer.deserialize()); } catch(Exception e) { } } /** Add new animal to the list, allAnimals. */ public static void setAllAnimals(RescueAnimal animal) { allAnimals.add(animal); } /** Serialize the list, allAnimals. */ public static void saveAnimalList() { try { Serializer.serialize(allAnimals); } catch(IOException e) { } } } RescueAnimal (main model - for brevity, I didn't include getters and setters, but if I should please let me know) package com.crud.gsjavafx.models; import javafx.beans.property.SimpleStringProperty; import java.io.Serial; import java.io.Serializable; /** * */ public class RescueAnimal implements Serializable { @Serial private static final long serialVersionUID = 1L; transient private SimpleStringProperty animalName; transient private SimpleStringProperty animalSpecies; transient private SimpleStringProperty location; private String serializableName; private String serializableSpecies; private String gender; private int age; private int weight; private String acquisitionDate; private String serializableLocation; private int trainingStatus; private boolean reserved;
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
java, beginner, mvc, javafx, crud public RescueAnimal(String name, String species, String gender, int age, int weight, String acquisitionDate, String location, int trainingStatus, boolean reserved) { // SimpleStringProperty. this.animalName = new SimpleStringProperty(name); this.animalSpecies = new SimpleStringProperty(species); this.location = new SimpleStringProperty(location); // String substitutes for SimpleStringProperty for serialization purposes. this.serializableName = getName(); this.serializableSpecies = getAnimalType(); this.serializableLocation = getLocation(); // Standard String fields not used in TableView. this.gender = gender; this.age = age; this.weight = weight; this.acquisitionDate = acquisitionDate; this.trainingStatus = trainingStatus; this.reserved = reserved; } Answer: I skimmed through your code and could not find anything from skimming. Regarding serialization, if you must use Serializable, you should avoid using the JavaFX properties. If you don't have to use Serializable, keep the properties and use something like JSON instead. Have a look at @Jame_D's answer here.
{ "domain": "codereview.stackexchange", "id": 43811, "lm_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, beginner, mvc, javafx, crud", "url": null }
python, programming-challenge, hangman Title: Hangman Game: Revealing guessed letters Question: I solved this problem: the Edabit Hangman Game challenge. Create a function that, given a phrase and a number of letters guessed, returns a string with hyphens - for every letter of the phrase not guessed, and each letter guessed in place. Notes The letters are always given in lowercase, but they should be returned in the same case as in the original phrase. All characters other than letters should always be returned. I saw people solved this in a one line but is it my solution good? I want to take everything and solving into smaller pieces and how to improve the solution any please explain why is it better to use that solution. Does the built in functions used as a cheating? def hangman(phrase, lst): alphanumerical_characters = ['1','2','3','4','5','6','7','8','9',".","!","?",","] #characters which are alphanumerical #if requires from A-Z and numbers 1-9 and other symbols result = '' new_list = [] #creating new_list because i want to take the uppercase letters and lowercase letters new_list = lst.copy() #we create copy of that to get the lowercase elements for element in phrase: if element.isupper(): element = element.lower() if element in lst: element = element.upper() new_list.append(element) #this for loop requires if element is uppercase , make lowercase and then check if its in lst for element in phrase: if element.isspace(): result += " " elif element not in new_list: if element in alphanumerical_characters: result += element else: result += '-' else: result += element #in second for loop we check if there's space between characters , element not in new_list, element in list return result
{ "domain": "codereview.stackexchange", "id": 43812, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, hangman", "url": null }
python, programming-challenge, hangman Answer: Any non-trivial function ought to have a docstring describing its purpose and any constraints on its arguments. That's also a good place for the unit tests, if we use the doctest module. alphanumerical_characters is a misleading name for that variable - it seems to be intended as a list of non-alphabetic characters. It's incomplete (e.g. missing ', which is present in many words, including the first one of this sentence). I think it would be better to check whether a character is alphabetic, and hide those, revealing only the ones that don't match any alphabetic letter. We could use element.isalpha() for that: if element.isalpha(): result += '-' else: result += element There's no point assigning [] to new_list, since we immediately replace that with a copy of lst. element is a long name for iterating over characters. Since its scope is small, I'd go for a very short name, such as c. I don't really follow the logic in the if element.isupper() test. It looks like we could eliminate all that by just considering uppercase versions of lst when testing. E.g. guesses = set(lst) | set(lst.upper()) Now guesses contains both the original lowercase letters and their uppercase partners. Some performance notes: Testing in works better if the right-hand argument is a set rather than a list. Because strings are immutable, building them character by character with += is inefficient. Consider creating a list of characters, then converting to a string with ''.join(chars). Applying these suggestions, we get def hangman(phrase, lst): ''' Replace any letters in phrase not present in lst (case-insensitively) with '-'.
{ "domain": "codereview.stackexchange", "id": 43812, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, hangman", "url": null }
python, programming-challenge, hangman >>> hangman('abc', '') '---' >>> hangman('abc', 'ax') 'a--' >>> hangman('ABC', 'cb') '-BC' >>> hangman("? !", '') '? !' >>> hangman("Don't worry!", 'dor') "Do-'- -orr-!" ''' guesses = set(lst) | set(lst.upper()) result = [] for c in phrase: if c.isalpha() and not c in guesses: c = '-' result.append(c) return ''.join(result) if __name__ == '__main__': import doctest doctest.testmod() We can further refine that by using a generator to build result: guesses = set(lst) | set(lst.upper()) return ''.join(c if c in guesses or not c.isalpha() else '-' for c in phrase)
{ "domain": "codereview.stackexchange", "id": 43812, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, hangman", "url": null }
c++, game, sfml Title: A Flappy bird game using C++ and SFML Question: I have written a Flappy Bird using SFML and C++, kindly review my code. I'm hoping for objective criticism. main.cpp #include "Game.h" int main() { Game game1; return 0; } Game.h #pragma once #include <SFML/Graphics.hpp> #include "Definitions.h" #include "ResourceHolder.h" #include "StateMachine.h" struct GameData { sf::RenderWindow window; StateMachine machine; }; typedef std::shared_ptr<GameData> GameDataRef; class Game { private: const float dt = 1.0f / 60.0f; sf::Clock clock; GameDataRef data = std::make_shared<GameData>(); int loadResource(); void run(); public: Game(); }; Game.cpp #include "Game.h" #include "MainMenuState.h" int Game::loadResource() { auto& tH = getGlobalTextureHolder(); auto& fH = getGlobalFontHolder(); return tH.loadFromFile("Resource\\res\\birdAnimation.png", "bird") && tH.loadFromFile("Resource\\res\\background.png", "back") && tH.loadFromFile("Resource\\res\\ground.png", "ground") && tH.loadFromFile("Resource\\res\\UpperPipe.png", "top_pipe") && tH.loadFromFile("Resource\\res\\DownPipe.png", "down_pipe") && tH.loadFromFile("Resource\\res\\StartButton.png", "start_button") && tH.loadFromFile("Resource\\res\\FB_Image.png", "title") && tH.loadFromFile("Resource\\res\\GameOver.png", "gameOver") && tH.loadFromFile("Resource\\res\\board.png", "board") && tH.loadFromFile("Resource\\res\\goldMedal.png", "gold_medal") && tH.loadFromFile("Resource\\res\\silverMedal.png", "silver_medal") && tH.loadFromFile("Resource\\res\\bronzeMedal.png", "bronze_medal") && tH.loadFromFile("Resource\\res\\ironMedal.png", "iron_medal") && fH.loadFromFile("Resource\\FlappyFont.ttf", "numbers"); } void Game::run() { float newTime; float frameTime; float interpolation; float currentTime = this->clock.getElapsedTime().asSeconds();
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml float currentTime = this->clock.getElapsedTime().asSeconds(); float accumulator = 0.0f; while (this->data->window.isOpen()) { this->data->machine.processStateChanges(); newTime = this- >clock.getElapsedTime().asSeconds(); frameTime = newTime - currentTime; if (frameTime > 0.25f) { frameTime = 0.25f; } currentTime = newTime; accumulator += frameTime; while (accumulator >= dt) { this->data->machine.getActiveState()->handleInput(); this->data->machine.getActiveState()->update(dt); accumulator -= dt; } interpolation = accumulator / dt; this->data->machine.getActiveState()->draw(interpolation); } } Game::Game() { srand(time(NULL)); data->window.create(sf::VideoMode(windowWidth, windowHeight), gameTitle); data->machine.addState(StateRef(new MainMenuState(this->data))); if (!this->loadResource()) { std::cout << "Fattal error"; } this->run(); } Background.h #pragma once #include "Game.h" class Background { private: GameDataRef data; sf::Sprite s_back1; sf::Sprite s_back2; public: Background(GameDataRef _data); void generateBack(float x); void drawBack(); }; Background.cpp #include "Background.h" Background::Background(GameDataRef _data) : data(_data) { sf::Texture* back = getGlobalTextureHolder().getResource("back"); sf::Vector2u TextureSize = back->getSize(); float ScaleX = (float)windowWidth / (float)TextureSize.x; float ScaleY = (float)windowHeight / (float)TextureSize.y; s_back1.setTexture(*back); s_back2.setTexture(*back); s_back1.setScale(ScaleX, ScaleY); s_back2.setScale(ScaleX, ScaleY); }
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml void Background::generateBack(float x) { if (x >= s_back1.getPosition().x + 230) { s_back2.setPosition(s_back1.getPosition().x + (float)windowWidth, 0.0f); } if (x >= s_back2.getPosition().x + 230) { s_back1.setPosition(s_back2.getPosition().x + (float)windowWidth, 0.0f); } } void Background::drawBack() { data->window.draw(s_back1); data->window.draw(s_back2); } Bird.h #pragma once #include "Game.h" class Bird { private: GameDataRef data; sf::Sprite s_bird; sf::Clock clock; int currentBirdState; float currentFrame = 0.0f; //Current frame float rotation = 0.0f; //Variable for rotate float time = 0.0f; // Time public: Bird(GameDataRef _data); void updateBird(float dt); void tap(); void animationBird(); //Animation bird float getX(); float getY(); void drawBird(); const sf::Sprite& getSprite(); }; Bird.cpp #include "Bird.h" Bird::Bird(GameDataRef _data) : data(_data) { sf::Texture* bird = getGlobalTextureHolder().getResource("bird"); s_bird.setTexture(*bird); s_bird.setTextureRect(sf::IntRect(0, 0, 34, 24)); s_bird.setPosition((float)windowWidth / 2.0f, (float)windowHeight / 2.0f); s_bird.setOrigin(s_bird.getGlobalBounds().width/2,s_bird.getGlobalBounds().height/2); currentBirdState = bStateStill; } void Bird::updateBird(float dt) { if (bStateStill == currentBirdState) { s_bird.move(moveSpeed, 0); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { s_bird.move(moveSpeed, -flyingSpeed * dt); rotation -= rotationSpeed * dt; if (rotation < -25.0f) { rotation = -25.0f; } s_bird.setRotation(rotation); } else { s_bird.move(moveSpeed, g * dt); rotation += rotationSpeed * dt; if (rotation > 90.0f) { rotation = 90.0f; } s_bird.setRotation(rotation); } }
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml s_bird.setRotation(rotation); } } void Bird::tap() { currentBirdState = bStateFlying; } void Bird::animationBird() //Animation bird { currentFrame += 0.005f * time; if (currentFrame > 3) { currentFrame -= 3; } if (bStateStill == currentBirdState) { s_bird.setTextureRect(sf::IntRect(56 * (int)currentFrame, 0, 34, 24)); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { s_bird.setTextureRect(sf::IntRect(56 * (int)currentFrame, 0, 34, 24)); } else { s_bird.setTextureRect(sf::IntRect(56, 0, 34, 24)); } time = clock.getElapsedTime().asMicroseconds(); clock.restart(); time /= 800.0f; } float Bird::getX() { return s_bird.getPosition().x; } float Bird::getY() { return s_bird.getPosition().y; } void Bird::drawBird() { data->window.draw(s_bird); } const sf::Sprite& Bird::getSprite() { return s_bird; } Camera.h #pragma once #include "Game.h" class Camera { private: GameDataRef data; sf::View view; public: Camera(GameDataRef _data); void getBirdCoordinateForCamera(float x, float y); void setCamera(); }; Camera.cpp #include "Camera.h" Camera::Camera(GameDataRef _data) : data(_data) { view.setCenter(sf::Vector2f(windowWidth, windowHeight)); view.setSize(sf::Vector2f(windowWidth, windowHeight)); } void Camera::getBirdCoordinateForCamera(float x, float y) { float tempX = x; float tempY = y; if (y < 320 || y > 320) { tempY = 320; } view.setCenter(tempX, tempY); } void Camera::setCamera() { data->window.setView(view); } Collision.h #pragma once #include "Game.h" class Collision { public: Collision(); bool checkSpriteCollision(sf::Sprite sprite1, float scale1, sf::Sprite sprite2, float scale2); }; Collision.cpp #include "Collision.h" Collision::Collision() { }
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml Collision.cpp #include "Collision.h" Collision::Collision() { } bool Collision::checkSpriteCollision(sf::Sprite sprite1, float scale1, sf::Sprite sprite2, float scale2) { sprite1.setScale(scale1, scale1); sprite2.setScale(scale2, scale2); sf::Rect<float> rect1 = sprite1.getGlobalBounds(); sf::Rect<float> rect2 = sprite2.getGlobalBounds(); if (rect1.intersects(rect2)) { return true; } else { return false; } } Definitions.h #pragma once #define windowWidth 460 #define windowHeight 640 #define gameTitle "Flappy Bird" #define g 180.0f //Gravity #define flyingSpeed 180.0f //Vertical speed #define rotationSpeed 200.0f //Rotation speed #define moveSpeed 2.0f //Gorizontal speed #define distanceBetweemPipes 50.0f #define DISTANCE 256 #define bStateStill 1 #define bStateFlying 2 GameState.h #pragma once #include <SFML/Audio.hpp> #include "State.h" #include "Game.h" #include "Background.h" #include "Bird.h" #include "Ground.h" #include "Pipes.h" #include "Camera.h" #include "Collision.h" #include "Hud.h" class GameState : public State { private: GameDataRef data; Bird* bird1; Background* back1; Ground* ground1; Pipes* pipes1; Collision collis1; Camera* camera1; Hud *hud1; sf::Clock clock; sf::Sound so_die; sf::Sound so_hit; sf::Sound so_point; sf::Sound so_wing; sf::SoundBuffer die; sf::SoundBuffer hit; sf::SoundBuffer point; sf::SoundBuffer wing; enum GameStates { eReady, ePlaying, eGameOver }; int currentGameState; int score; bool cState; public: GameState(GameDataRef _data); void init(); void handleInput(); void update(float dt); void draw(float dt); }; GameState.cpp #include "GameState.h" #include "GameOverState.h" GameState::GameState(GameDataRef _data) : data(_data) { }
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml GameState::GameState(GameDataRef _data) : data(_data) { } void GameState::init() { bird1 = new Bird(data); back1 = new Background(data); ground1 = new Ground(data); pipes1 = new Pipes(data); camera1 = new Camera(data); hud1 = new Hud(data); currentGameState = eReady; cState = false; score = 0; hud1->updateScore(score); die.loadFromFile("Resource\\sounds\\sfx_die.ogg"); hit.loadFromFile("Resource\\sounds\\sfx_hit.ogg"); point.loadFromFile("Resource\\sounds\\sfx_point.ogg"); wing.loadFromFile("Resource\\sounds\\sfx_wing.ogg"); so_die.setBuffer(die); so_hit.setBuffer(hit); so_point.setBuffer(point); so_wing.setBuffer(wing); } void GameState::handleInput() { sf::Event event; while (this->data->window.pollEvent(event)) { if (sf::Event::Closed == event.type) { this->data->window.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { if (eGameOver != currentGameState) { currentGameState = ePlaying; bird1->tap(); so_wing.play(); } } } } void GameState::update(float dt) { if (eGameOver != currentGameState) { bird1->animationBird(); back1->generateBack(bird1->getX()); ground1->generateGround(bird1->getX()); hud1->move(); camera1->getBirdCoordinateForCamera(bird1->getX(), bird1->getY()); camera1->setCamera(); } bird1->updateBird(dt); if (ePlaying == currentGameState) { pipes1->generatePipes(bird1->getX(), cState); cState = true; if (collis1.checkSpriteCollision(bird1->getSprite(), 0.7f, ground1->getFirstSprite(), 1.0f) || collis1.checkSpriteCollision(bird1->getSprite(), 0.7f, ground1->getSecondSprite(), 1.0f)) { currentGameState = eGameOver; so_hit.play(); }
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml if (collis1.checkSpriteCollision(bird1->getSprite(), 0.625f, pipes1->getFirstTopSprite(), 1.0f) || collis1.checkSpriteCollision(bird1->getSprite(), 0.625f, pipes1->getFirstDownSprite(), 1.0f)) { currentGameState = eGameOver; so_hit.play(); } if (collis1.checkSpriteCollision(bird1->getSprite(), 0.625f, pipes1->getSecondTopSprite(), 1.0f) || collis1.checkSpriteCollision(bird1->getSprite(), 0.625f, pipes1->getSecondDownSprite(), 1.0f)) { currentGameState = eGameOver; so_hit.play(); } if (pipes1->score(bird1->getX())) { score++; hud1->updateScore(score); so_point.play(); } } if (eGameOver == currentGameState) { this->data->machine.addState(StateRef(new GameOverState(data, score)), true); } } void GameState::draw(float dt) { this->data->window.clear(); back1->drawBack(); if (ePlaying == currentGameState) { pipes1->drawPipes(); } ground1->drawGround(); bird1->drawBird(); hud1->draw(); this->data->window.display(); }
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml this->data->window.display(); } GameOverState.h #pragma once #include <fstream> #include "State.h" #include "Game.h" #include "Camera.h" #include "InputManager.h" class GameOverState : public State { private: GameDataRef data; InputManager* iM2; Camera* camera2; sf::Sprite s_back; sf::Sprite s_gameOverTitle; sf::Sprite s_retryButton; sf::Sprite s_board; sf::Sprite s_goldMedal; sf::Sprite s_silverMedal; sf::Sprite s_bronzeMedal; sf::Sprite s_ironMedal; sf::Text t_score; sf::Text t_bestScore; int score; int bestScore; public: GameOverState(GameDataRef _data, int _score); void init(); void handleInput(); void update(float dt); void draw(float dt); }; GameOverState.cpp #include "GameOverState.h" #include "GameState.h" GameOverState::GameOverState(GameDataRef _data, int _score) : data(_data), score(_score) { } void GameOverState::init() { std::fstream read("BestScore.txt", std::ios::in); if (read.is_open()) { while (!read.eof()) { read >> bestScore; } } read.close(); std::fstream write("BestScore.txt", std::ios::out); if (write.is_open()) { if (score > bestScore) { bestScore = score; } write << bestScore; } write.close(); camera2 = new Camera(data); iM2 = new InputManager(data); sf::Texture* back = getGlobalTextureHolder().getResource("back"); sf::Vector2u TextureSize = back->getSize(); float ScaleX = (float)windowWidth / (float)TextureSize.x; float ScaleY = (float)windowHeight / (float)TextureSize.y; s_back.setTexture(*back); s_back.setScale(ScaleX, ScaleY); sf::Texture* gameOverTitle = getGlobalTextureHolder().getResource("gameOver");
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml sf::Texture* gameOverTitle = getGlobalTextureHolder().getResource("gameOver"); s_gameOverTitle.setTexture(*gameOverTitle); sf::Texture* button = getGlobalTextureHolder().getResource("start_button"); s_retryButton.setTexture(*button); camera2->setCamera(); s_back.setPosition(windowWidth / 2, windowHeight / 2); s_gameOverTitle.setPosition(windowWidth / 1.21, windowHeight / 1.51); s_retryButton.setPosition(windowWidth / 1.09, windowHeight / 1.0); sf::Texture* board = getGlobalTextureHolder().getResource("board"); s_board.setTexture(*board); s_board.setPosition(windowWidth / 1.26, windowHeight / 1.29); sf::Texture* gold_medal = getGlobalTextureHolder().getResource("gold_medal"); s_goldMedal.setTexture(*gold_medal); sf::Texture* silver_medal = getGlobalTextureHolder().getResource("silver_medal"); s_silverMedal.setTexture(*silver_medal); sf::Texture* bronze_medal = getGlobalTextureHolder().getResource("bronze_medal"); s_bronzeMedal.setTexture(*bronze_medal); sf::Texture* iron_medal = getGlobalTextureHolder().getResource("iron_medal"); s_ironMedal.setTexture(*iron_medal); sf::Font* text = getGlobalFontHolder().getResource("numbers"); t_score.setFont(*text); t_bestScore.setFont(*text); t_score.setString(std::to_string(score)); t_score.setCharacterSize(20); t_score.setFillColor(sf::Color::White); t_score.setOrigin(sf::Vector2f(t_score.getGlobalBounds().width / 2, t_score.getGlobalBounds().height / 2)); t_bestScore.setString(std::to_string(bestScore)); t_bestScore.setCharacterSize(20); t_bestScore.setFillColor(sf::Color::White); t_bestScore.setOrigin(sf::Vector2f(t_score.getGlobalBounds().width / 2, t_score.getGlobalBounds().height / 2)); t_score.setPosition(550, 534); t_bestScore.setPosition(551, 576);
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml t_score.setPosition(550, 534); t_bestScore.setPosition(551, 576); if (score > 0 && score < 25) { s_ironMedal.setPosition(390, 539); } else if (score >= 25 && score < 50) { s_bronzeMedal.setPosition(390, 539); } else if (score >= 50 && score < 75) { s_silverMedal.setPosition(390, 539); } else if (score >= 75) { s_goldMedal.setPosition(390, 539); } } void GameOverState::handleInput() { sf::Event event; while (this->data->window.pollEvent(event)) { if (sf::Event::Closed == event.type) { this->data->window.close(); } if (iM2->IsSpriteClicked(event, this->s_retryButton, sf::Mouse::Left)) { this->data->machine.addState(StateRef(new GameState(data)), true); } } } void GameOverState::update(float dt) { } void GameOverState::draw(float dt) { this->data->window.clear(); this->data->window.draw(this->s_back); this->data->window.draw(this->s_retryButton); this->data->window.draw(this->s_gameOverTitle); this->data->window.draw(this->s_board); if (score > 0 && score < 25) { this->data->window.draw(this->s_ironMedal); } else if (score >= 25 && score < 50) { this->data->window.draw(this->s_bronzeMedal); } else if (score >= 50 && score < 75) { this->data->window.draw(this->s_silverMedal); } else if (score >= 75) { this->data->window.draw(this->s_goldMedal); } this->data->window.draw(t_score); this->data->window.draw(t_bestScore); this->data->window.display(); } Ground.h #pragma once #include "Game.h" class Ground { private: GameDataRef data; sf::Sprite s_ground; sf::Sprite s_ground2; public: Ground(GameDataRef _data); void generateGround(float x); void drawGround(); const sf::Sprite& getFirstSprite(); const sf::Sprite& getSecondSprite(); };
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml const sf::Sprite& getFirstSprite(); const sf::Sprite& getSecondSprite(); }; Ground.cpp #include "Ground.h" Ground::Ground(GameDataRef _data) : data(_data) { sf::Texture* ground = getGlobalTextureHolder().getResource("ground"); s_ground.setTexture(*ground); s_ground2.setTexture(*ground); s_ground.setScale(1.003f, 1.0f); s_ground2.setScale(1.003f, 1.0f); s_ground.setPosition(0.0f, windowHeight / 1.3f); } void Ground::generateGround(float x) { if (x >= s_ground.getPosition().x + 230) { s_ground2.setPosition(s_ground.getPosition().x + (float)windowWidth, windowHeight / 1.3f); } if (x >= s_ground2.getPosition().x + 230) { s_ground.setPosition(s_ground2.getPosition().x + (float)windowWidth, windowHeight / 1.3f); } } void Ground::drawGround() { data->window.draw(s_ground); data->window.draw(s_ground2); } const sf::Sprite& Ground::getFirstSprite() { return s_ground; } const sf::Sprite& Ground::getSecondSprite() { return s_ground2; } Hud.h #pragma once #include "Game.h" #include <string> class Hud { private: GameDataRef data; sf::Text scoreText; public: Hud(GameDataRef _data); void move(); void updateScore(int score); void draw(); }; Hud.cpp #include "Hud.h" Hud::Hud(GameDataRef _data) : data(_data) { sf::Font* text = getGlobalFontHolder().getResource("numbers"); scoreText.setFont(*text); scoreText.setString("0"); scoreText.setCharacterSize(64); scoreText.setFillColor(sf::Color::White); scoreText.setOrigin(sf::Vector2f(scoreText.getGlobalBounds().width / 2, scoreText.getGlobalBounds().height / 2)); scoreText.setPosition(sf::Vector2f(windowWidth / 2, windowHeight / 7)); } void Hud::move() { scoreText.move(moveSpeed, 0.0f); } void Hud::updateScore(int score) { scoreText.setString(std::to_string(score)); } void Hud::draw() { data->window.draw(scoreText); } InputManager.h #pragma once
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml void Hud::draw() { data->window.draw(scoreText); } InputManager.h #pragma once #include "Game.h" #include <SFML/Graphics.hpp> class InputManager { private: GameDataRef data; public: InputManager(GameDataRef _data); bool IsSpriteClicked(sf::Event event, sf::Sprite object, sf::Mouse::Button button); sf::Vector2i GetMousePosition(); }; InputManager.cpp #include "InputManager.h" InputManager::InputManager(GameDataRef _data) : data(_data) { } bool InputManager::IsSpriteClicked(sf::Event event, sf::Sprite object, sf::Mouse::Button button) { if (event.type == sf::Event::MouseButtonReleased) { // on click auto pos = data->window.mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y)); if (event.mouseButton.button == sf::Mouse::Left) { // on left click if (object.getGlobalBounds().contains(pos)) { return true; } } } return false; } sf::Vector2i InputManager::GetMousePosition() { return sf::Mouse::getPosition(data->window); } MainMenuState.h #pragma once #include "Game.h" #include "InputManager.h" class MainMenuState : public State { private: GameDataRef data; InputManager *iM1; sf::Sprite s_title; sf::Sprite s_background; sf::Sprite s_button; public: MainMenuState(GameDataRef _data); void init(); void handleInput(); void update(float dt); void draw(float dt); }; MainMenuState.cpp #include "MainMenuState.h" #include "GameState.h" MainMenuState::MainMenuState(GameDataRef _data) : data(_data) { } void MainMenuState::init() { iM1 = new InputManager(data); sf::Texture* back = getGlobalTextureHolder().getResource("back"); sf::Vector2u TextureSize = back->getSize(); float ScaleX = (float)windowWidth / (float)TextureSize.x; float ScaleY = (float)windowHeight / (float)TextureSize.y;
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml s_background.setTexture(*back); s_background.setScale(ScaleX, ScaleY); sf::Texture* title = getGlobalTextureHolder().getResource("title"); s_title.setTexture(*title); sf::Texture* button = getGlobalTextureHolder().getResource("start_button"); s_button.setTexture(*button); s_title.setPosition(windowWidth / 3.15, windowHeight / 6); s_button.setPosition(windowWidth / 2.46, windowHeight / 2); } void MainMenuState::handleInput() { sf::Event event; while (this->data->window.pollEvent(event)) { if (sf::Event::Closed == event.type) { this->data->window.close(); } if (iM1->IsSpriteClicked(event, this->s_button, sf::Mouse::Left)) { this->data->machine.addState(StateRef(new GameState(data)), true); } } } void MainMenuState::update(float dt) { } void MainMenuState::draw(float dt) { this->data->window.clear(); this->data->window.draw(this->s_background); this->data->window.draw(this->s_title); this->data->window.draw(this->s_button); this->data->window.display(); } Pipes.h #pragma once #include "Game.h" #include <random> class Pipes { private: GameDataRef data; sf::Sprite s_top1; sf::Sprite s_down1; sf::Sprite s_top2; sf::Sprite s_down2; int sizeGroundTexture; float originPipe = 0.0f; float randY = 0.0f; public: Pipes(GameDataRef _data); void randomizeY(); void generatePipes(float x, bool state); void drawPipes(); bool score(float x); const sf::Sprite& getFirstTopSprite(); const sf::Sprite& getFirstDownSprite(); const sf::Sprite& getSecondTopSprite(); const sf::Sprite& getSecondDownSprite(); }; Pipes.cpp #include "Pipes.h" Pipes::Pipes(GameDataRef _data) : data(_data) { sf::Texture* top_pipe = getGlobalTextureHolder().getResource("top_pipe"); sf::Texture* down_pipe = getGlobalTextureHolder().getResource("down_pipe");
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }
c++, game, sfml sf::Texture* down_pipe = getGlobalTextureHolder().getResource("down_pipe"); s_top1.setTexture(*top_pipe); s_top2.setTexture(*top_pipe); originPipe = top_pipe->getSize().x / 2.0f; s_down1.setTexture(*down_pipe); s_down2.setTexture(*down_pipe); sf::Texture* gTexture = getGlobalTextureHolder().getResource("ground"); sizeGroundTexture = gTexture->getSize().y; } void Pipes::randomizeY() { std::mt19937 gen; gen.seed(time(0)); std::uniform_int_distribution<> uid(1, sizeGroundTexture); randY = uid(gen); } void Pipes::generatePipes(float x, bool state) { if (state == false) { randomizeY(); s_top1.setPosition(DISTANCE + x, 0.0f - distanceBetweemPipes - randY); s_down1.setPosition(DISTANCE + x, (float)windowHeight - s_top1.getGlobalBounds().height + distanceBetweemPipes - randY); randomizeY(); s_top2.setPosition(s_top1.getPosition().x + DISTANCE, 0.0f - distanceBetweemPipes - randY); s_down2.setPosition(s_down1.getPosition().x + DISTANCE, (float)windowHeight - s_top2.getGlobalBounds().height + distanceBetweemPipes - randY); } else if (x == s_top2.getPosition().x + 24) { randomizeY(); s_top1.setPosition(s_top2.getPosition().x + DISTANCE, 0.0f - distanceBetweemPipes - randY); s_down1.setPosition(s_down2.getPosition().x + DISTANCE, (float)windowHeight - s_top1.getGlobalBounds().height + distanceBetweemPipes - randY); } else if (x == s_top1.getPosition().x + 24) { randomizeY(); s_top2.setPosition(s_top1.getPosition().x + DISTANCE, 0.0f - distanceBetweemPipes - randY); s_down2.setPosition(s_down1.getPosition().x + DISTANCE, (float)windowHeight - s_top2.getGlobalBounds().height + distanceBetweemPipes - randY); } }
{ "domain": "codereview.stackexchange", "id": 43813, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, sfml", "url": null }