text
stringlengths
1
2.12k
source
dict
performance, linux, assembly, x86, bigint Title: Multiply two huge base-10 numbers in assembly Question: This post is a second part of my original post, Add two huge base-10 numbers, which deals with adding two huge base-10 numbers. However, in this case, I'm multiplying two non-negative whole numbers. In both cases, the input and output are represented as null-terminated ASCII strings, with digits in big-endian order. I use my own custom strlen function which only modifies rcx. I've tried to incorporate most of the feedback I've received and managed to shorten the code from 170 to 130 lines. Is there anything else I can do which will make it run faster? Here's the code: extern add_whole extern strlen section .text global _multiply_whole _multiply_whole: ; Input: ; - char *a -> rdi ; - char *b -> rsi ; - char *res -> rdx (allocate strlen(a) + strlen(b) + 1 (for null terminator) bytes) ; - char *buf1 -> rcx (temporary buffer for program to use) ; - char *buf2 -> r8 (both buf1 and buf2 have the same length as res)
{ "domain": "codereview.stackexchange", "id": 43997, "lm_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, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint ; Registers used: ; - rax ; - rbx ; - r9 ; - r10 ; - r11 ; - r12 ; - r13 ; - r14 ; - r15 push rbx ; Push used callee-saved registers. push r12 push r13 push r14 push r15 mov r9, rdi ; Move char* a to r9. mov r10, rcx ; Save rcx since strlen() doesn't preserve it. call strlen ; rax = strlen(a) mov rbx, rax ; Save rax in order to prevent it from being overwritten. mov rdi, rsi ; strlen's first argument is now b. call strlen ; Call strlen with b. dec rax xchg rax, rbx ; rbx = strlen(b) - 1 mov rdi, r9 ; Restore rdi. mov rcx, r10 ; Restore rcx. xor r10d, r10d ; r10b is the carry. mov byte [rdx], '0' ; Set the default value of the result string to '0'. xor r14d, r14d ; The number of leading zeroes to add. .loop_1: lea r13, [rax+1] ; r13 = strlen(a) + 1 add rcx, rax ; rcx = &a[strlen(a)] mov r9, rax ; r9 = strlen(a) mov r15d, 10 ; The number we're dividing by. push rax ; Save rax since we use it for mul and div later. .loop_2: movzx r11d, byte [rsi+rbx] ; r11b is a byte of char *b sub r11b, '0' movzx eax, byte [rdi+r9-1] ; al is a byte of char *a sub al, '0' mul r11b mov r11b, al ; r11b is the multiplication of char *a and char *b. add r11b, r10b ; Add carry. push rdx mov al, r11b div r15b mov r10b, al ; carry = r11b / 10 mov al, ah mov byte [rcx], al add byte [rcx], '0' ; Add the remainder to the result string. pop rdx dec rcx dec r9 jnz .loop_2 ; Loop r9 times. mov byte [rcx], r10b ; Add the final carry (might be 0)
{ "domain": "codereview.stackexchange", "id": 43997, "lm_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, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint mov byte [rcx], r10b ; Add the final carry (might be 0) add byte [rcx], '0' ; to the string. xor r10b, r10b ; Reset carry. xor r11d, r11d ; r11 = 0 test r14, r14 jle .after_loop_3 ; if r14 <= 0 then skip loop_3 .loop_3: ; Adds r14 trailing zeroes to buf1, r14 is the amount of times loop_1 has run. mov byte [rcx+r13], '0' ; buf1[r13] = '0' inc r13 ; r13++ inc r11 ; r11++ cmp r11, r14 js .loop_3 ; Loop r14 times. .after_loop_3: mov byte [rcx+r13], 0 ; Zero-terminate the string to pass it to add_whole(). push rcx ; Save used caller-saved registers. push rdi push rsi push rdx mov rdi, rdx ; param1 = rdx (char *res) mov rsi, rcx ; param2 = rcx (char *buf1) mov rdx, r8 ; param3 = r8 (char *buf2) mov r15, r8 ; Saving the r8 register. call add_whole ; buf2 = add_whole(res, buf1) (this doesn't actually return anything) mov r8, r15 ; Restoring the r8 register. pop rdx pop rsi xor r11d, r11d mov rdi, r8 call strlen ; r9 = strlen(buf2) (length of the addition result) mov r9, rax pop rdi pop rcx pop rax .loop_4: mov r15b, byte [r8+r11] mov byte [rdx+r11], r15b inc r11 cmp r11, r9 js .loop_4 mov byte [rdx+r9], 0 xor r11d, r11d .loop_5: mov byte [rcx+r11], 0 mov byte [r8+r11], 0 inc r11 cmp r11, r13 js .loop_5 inc r14 mov r15, rbx dec rbx test r15, r15 jg .loop_1 mov rdi, rdx call strlen mov byte [rdx+rax], 0 pop r15 pop r14 pop r13 pop r12 pop rbx ret
{ "domain": "codereview.stackexchange", "id": 43997, "lm_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, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint This is basically the pen-and-paper multiplication algorithm implemented in assembly. I've used movzx in some cases and even avoided pushing and popping registers (instead, I've used two movs as suggested by https://stackoverflow.com/questions/73996728/is-moving-into-another-register-faster-or-slower-than-push-and-pop.) Currently, this code can calculate 1000! 27 times per second. I used this code for that benchmark. #include "multiply.h" #include <chrono> #include <iostream> std::string factorial(int x) { std::string answer = "1"; for (auto i = 2; i <= x; i++) { std::string toMultiply = std::to_string(i); char *partAns = (char *)calloc(answer.length() + toMultiply.length() + 1, 1); multiply(answer.c_str(), toMultiply.c_str(), partAns); answer = partAns; free(partAns); } return answer; } int main() { double time = 0; int x = 0; while (time < 1) { auto start = std::chrono::high_resolution_clock::now(); std::string s = factorial(1000); auto end = std::chrono::high_resolution_clock::now(); time += std::chrono::duration_cast<std::chrono::microseconds>(end - start) .count() * 1e-6; x++; } std::cout << "1000!'s per second: " << x << '\n'; }
{ "domain": "codereview.stackexchange", "id": 43997, "lm_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, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint std::cout << "1000!'s per second: " << x << '\n'; } multiply.h: /// @brief Multiplies the first rational argument with the second rational /// argument and stores the result in the third argument. /// @param a The first non-negative rational number as a decimal. /// @param b The first non-negative rational number as a decimal. /// @param res Where a * b will be stored. void multiply(const char *a, const char *b, char *res) { extern size_t strlen(const char *str); size_t a_length = strlen(a); size_t b_length = strlen(b); char *a_copy = (char *)calloc(a_length + 1, 1); char *b_copy = (char *)calloc(b_length + 1, 1); size_t ptr = 0; int displacement = 0; unsigned char flag = 0; for (size_t i = 0; i < a_length; i++) { if (flag == 1) displacement++; if (a[i] == '.') flag = 1; else { a_copy[ptr] = a[i]; ptr++; } } ptr = 0; flag = 0; for (size_t i = 0; i < b_length; i++) { if (flag == 1) displacement++; if (b[i] == '.') flag = 1; else { b_copy[ptr] = b[i]; ptr++; } } size_t bufsize = strlen(a) + strlen(b) + 1; char *buf1 = (char *)calloc(bufsize, 1); char *buf2 = (char *)calloc(bufsize, 1); _multiply_whole(a_copy, b_copy, res, buf1, buf2); size_t reslength = strlen(res); for (size_t i = 0; i < displacement; i++) res[reslength - i] = res[reslength - i - 1]; if (displacement) res[reslength - displacement] = '.'; free(buf1); free(buf2); free(a_copy); free(b_copy); } Any way to improve this? Answer: Unfortunate compare/branch pair A cmp/js pair cannot macro-fuse on various Intel processors. Since it's meant to be a less-than comparison, usually it would be done with cmp/jl or cmp/jb (depending on signedness) both of which can macro-fuse. Also, cmp/js in general can go wrong in case of overflow. That case doesn't look very relevant here in this code, I just mention it so you can avoid it when it does matter.
{ "domain": "codereview.stackexchange", "id": 43997, "lm_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, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint avoided pushing and popping registers Not entirely, but I'll leave that up to you. div and 8-bit registers Note that the dividend for div r15b is ax, not al. ah is zero at the time of the division, but seemingly by accident, and in such a way that it creates a situation where the high-byte register and the low-byte register may have gotten renamed separately and need to be "unified" with an implicit extra µop. That would only happen on microarchitectures that rename those registers separately. On others, writing to byte registers may have an implicit dependency on the corresponding 64-bit register, to "merge" the new value into it. movzx has been used in some cases, but there are still other operations that risk triggering the curse of partial register writes. The curse of partial register writes also applies to xor r10b, r10b for example, which (unlike xor r10d, r10d) is not a special zeroing idiom (so it is a real xor instruction, with associated execution cost, and not a dependency-breaker). Unless there is some overriding reason not to, you should zero the corresponding 32-bit register. Using xor r11d, r11d to set r11 to zero is good, keep doing that. By the way the div can be avoided, which is probably still a good idea, despite significant improvements to the performance of integer division in recent x86 processors. There are various ways to approach this. For example for a number in range 0..91 held in eax, division by 10 may be implemented like this: imul edx, eax, 0CDh ; approximately 1/10 * 2^11 shr edx, 11 which works for that entire range of numbers and actually more, the first time it goes wrong is when eax = 0x0405. Then the remainder can be determined by subtracting 10 times the quotient from the dividend, imul ecx, edx, -10 add eax, ecx ; this add may be merged with the conversion to ASCII into a 3-part lea
{ "domain": "codereview.stackexchange", "id": 43997, "lm_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, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint Or two leas could be used to implement a multiplication by 10, but then there would be a sub which cannot be merged with the conversion to ASCII. I used some relatively arbitrary registers for these examples, I do not mean to imply that these snippets can be plugged into the code as-is. Please take them as descriptions of techniques rather than as concrete suggestions. mov byte [rcx], al add byte [rcx], '0' A read-modify-write operation is relatively "heavy" in various ways. Not super heavy, but heavy enough to think about avoiding it. It could be avoided by using lea to do a non-destructive addition, or even by adding '0' to eax (note that I'm choosing eax instead of al on purpose, to avoid the wrath of partial register writes), storing al, and then subtracting '0' again. That add and sub would be part of a loop-carried dependency chain, but that does not look significant to me compared to the rest of the loop body.
{ "domain": "codereview.stackexchange", "id": 43997, "lm_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, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint Sweeping changes One of the biggest things you could do for performance, is multiplying several digits at once. The basic multiplication algorithm does a quadratic number of multiplications after all. Switching from base 10 to base 109 (so that each limb fits in 32 bits, and each product fits in 64 bits) would not reduce multiplications by a factor of 9, but rather a factor of 81[1]. I chose a power of ten for the base, since that most easily converts to and from the base ten input and output. Even with that, it is not so simple to do efficiently, or even to do it at all. The temporary results into which the additions take place, should remain in base 109 for as long as possible, since converting that to base ten is (while simpler than general base conversions, since each limb would map nicely to 9 output digits) actually not cheap. You could take this one step further and take advantage of 64bit-to-128bit multiplication to do it all in base 1018 for another 4x reduction in multiplications, but the resulting 128bit partial products are more complicated to deal with. I don't think you should do it. There are various more complex algorithms for big-integer multiplication that are worth using when numbers have about the size that you're already dealing with (over a thousand decimal digits), but they apply only when both inputs are sufficiently big, which is not the case when calculating a factorial. note 1: but that factor is lower when calculating a factorial, since one of the multiplicands is always small in that case.
{ "domain": "codereview.stackexchange", "id": 43997, "lm_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, linux, assembly, x86, bigint", "url": null }
c++, random, hashcode Title: Laughably tiny random engine Question: I devised a tiny pseudo-random engine and I wondered if it would be considered decent or even good. It is based on a SHA256 implementation and uses a single 32-bytes state variable. On seeding, the seed is hashed and that's the initial state of the engine. Then, for each new pseudo-random number, the state is hashed, its first byte is popped and the first byte of the hash is pushed at the end of the state (...as in "shifting left"). The requested pseudo-random number is extracted directly from the state hashed state (e.g. a 64-bits integer can be served from the first 4 bytes of the state variable hashed state). All this is based on the assumption that SHA256 produces "uniform" distribution (i.e. for an infinite number of distinct inputs, the occurence of 1 or 0 for every bit of the hash is very close to 50%). Here is my C++ implementation (please ignore the util:: namespace; the SHA256 implementation I use can be found here): random_engine.h #pragma once #include <SHA256/SHA256.h> #include <array> namespace util { class random_engine_t { private: std::array<uint8_t, 32> m_state; public: random_engine_t(const uint8_t* seed, size_t slen); random_engine_t(const char* seed); random_engine_t(const time_t seed); template<typename T> T next() { static_assert(sizeof(T) <= 32); SHA256 sha; sha.update(m_state.data(), m_state.size()); uint8_t* digest = sha.digest(); T t = *reinterpret_cast<T*>(digest); //update seed { //shuffle back for (size_t s = 1; s < m_state.size(); s++) { m_state[s - 1] = m_state[s]; } //set last byte from digest m_state[m_state.size() - 1] = digest[0]; } delete[] digest; return t; } }; } random_engine.cpp
{ "domain": "codereview.stackexchange", "id": 43998, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, random, hashcode", "url": null }
c++, random, hashcode random_engine.cpp #include <util/random_engine_t.h> namespace util { random_engine_t::random_engine_t(const uint8_t* seed, size_t slen) { SHA256 sha; sha.update(seed, slen); uint8_t* digest = sha.digest();//initial state { std::copy(digest, digest + 32, m_state.data()); } delete[] digest; } random_engine_t::random_engine_t(const char* seed) : random_engine_t(reinterpret_cast<const uint8_t*>(seed), strlen(seed)) {} random_engine_t::random_engine_t(const time_t seed) : random_engine_t(reinterpret_cast<const uint8_t*>(&seed), sizeof(time_t)) {} } The next() function is templated but is meant only for integer types. Is there any obvious flaw with this design that I'm not seeing ?
{ "domain": "codereview.stackexchange", "id": 43998, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, random, hashcode", "url": null }
c++, random, hashcode Answer: Possibility of short cycles SHA256 is a cryptographically secure hash function, which indeed means the output is very uncorrelated to the input. However, given exactly the same input, it will always give the same output. That implies that if, after a while, the state will return to an earlier value, you will have entered a cycle. If this cycle is short, then the quality of your random number generator has also dropped significantly. Note that the probability that you enter a cycle is 100%, the only question is how long it will take given the initial seed, and how long the cycle will be. One way prevent short cycles from happening is to ensure the state is not updated based on the hash function itself. If you would just treat the state as a 256 bit counter, and increment the counter by 1 each time next() is called, you are guaranteed to have the longest possible cycle (\$2^{256}\$). See also this Cryptography question. Unsafe use of reinterpret_cast<>() You should not use reinterpret_cast<>() to create a T from m_state. Consider that T might have different alignment restrictions than m_state, for example T might be a 64-bit integer or floating point number. Instead, create a default-constructed T and std::copy() the memory from m_state into t. Also note that all of this is only legal if T is a trivial type, so you might want to add a static_assert() or restrict the template parameter to verify that. Make more use of STL algorithms You are already using std::copy() in the constructor, you can also use it to shift the state by one byte.
{ "domain": "codereview.stackexchange", "id": 43998, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, random, hashcode", "url": null }
javascript, array Title: JavaScript BitArray Implementation Question: I am working on a project in which an array can easily grow beyond 50M in length. It's an array holding only boolean (0/1) values. Using Uint8Array is just fine and it's very performant compared normal arrays. Still I just wanted to try implementing a BitArray by extending DataView object. BitArray enormously reduces the memory footprint compared to normal Arrays (1/32) and Uint8Array (1/8). So that's a certain gain but as for speed, despite I did everything to my knowledge BitArray is still slightly slower compared to both unless the size hits the 33,554,433 limit (> 2²⁵). As I have read from this document, at this point the normal Array reaches to ~268MB memory limit and it's internal structure gets switched to NumberDictionary[16] yielding a dramatic slow down in v8. Note that when the length is 33,554,433 the BitArray uses only 4MB of memory. One other point to note is, for my application i need the total number of 1s in the BitArray (population count) which is the popcount property in below code. Thanks to the blazingly fast Hamming Weight algorithm BitArray is like 80 times faster compared to counting the existing items in array though I am not testing it here. Any ideas to boost the BitArray up a little are most welcome. class BitArray extends DataView{ constructor(n,ab){ var abs = n >> 3; // ArrayBuffer Size super(ab instanceof ArrayBuffer ? ab : n & 31 ? new ArrayBuffer(abs + 4 - (abs & 3)) : new ArrayBuffer(abs)); } get length(){ return this.buffer.byteLength*8; }
{ "domain": "codereview.stackexchange", "id": 43999, "lm_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, array", "url": null }
javascript, array get length(){ return this.buffer.byteLength*8; } get popcount(){ var m1 = 0x55555555, m2 = 0x33333333, m4 = 0x0f0f0f0f, h01 = 0x01010101, pc = 0, x; for (var i = 0, len = this.buffer.byteLength >> 2; i < len; i++){ x = this.getUint32(i << 2); x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits pc += (x * h01) >> 56; } return pc; } // n >> 3 is Math.floor(n/8) // n & 7 is n % 8 at(n){ return this.getUint8(n >> 3) & (1 << (n & 7)) ? 1 : 0; } set(n){ this.setUint8(n >> 3, this.getUint8(n >> 3) | (1 << (n & 7))); } reset(n){ this.setUint8(n >> 3, this.getUint8(n >> 3) & ~(1 << (n & 7))); } slice(a = 0, b = this.length){ return new BitArray(b-a,this.buffer.slice(a >> 3, b >> 3)); } toggle(n){ this.setUint8(n >> 3, this.getUint8(n >> 3) ^ (1 << (n & 7))); } toString(){ return new Uint8Array(this.buffer).reduce((p,c) => p + Array.prototype.reduce.call(c.toString(2).padStart(8,"0"),(f,s) => s+f), "") .slice(0,this.length); } } // Test code starts from here var len = 1e6, // array length tst = 10, // test count arr = Array(len), bar = new BitArray(len), uia = new Uint8Array(len), r1,r2,r3,t = 0; console.log(`There are ${bar.popcount} 1s in the BitArray`); for (var i = 0; i < len; i++){ (Math.random() > 0.5) && ( t++ , bar.set(i) ); } console.log(`${t} .set() ops are made and now there are ${bar.popcount} 1s in the BitArray`);
{ "domain": "codereview.stackexchange", "id": 43999, "lm_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, array", "url": null }
javascript, array console.log(`${t} .set() ops are made and now there are ${bar.popcount} 1s in the BitArray`); console.time("Array"); for (var k = 0; k < tst; k++){ for (var i = 0; i < len; i++) arr[i] = Math.random() > 0.5 ? 1 : 0; for (var i = 0; i < len; i++) t = arr[1]; r1 = arr.slice(); } console.timeEnd("Array"); console.time("BitArray"); for (var k = 0; k < tst; k++){ for (var i = 0; i < len; i++) Math.random() > 0.5 ? bar.set(i) : bar.reset(i) for (var i = 0; i < len; i++) t = bar.at(i); r2 = bar.slice(); } console.timeEnd("BitArray"); console.time("Uint8Array"); for (var k = 0; k < tst; k++){ for (var i = 0; i < len; i++) uia[i] = Math.random() > 0.5 ? 1 : 0; for (var i = 0; i < len; i++) t = uia[i]; r3 = uia.slice(); } console.timeEnd("Uint8Array"); Answer: abs + 4 - (abs & 3)
{ "domain": "codereview.stackexchange", "id": 43999, "lm_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, array", "url": null }
javascript, array Answer: abs + 4 - (abs & 3) Could be simplified: (abs + 3) & -4 They are not equivalent expressions, but they are equivalent when abs is not a multiple of 4. Actually the simpler one is more convenient in this case: with this expression, you can skip the ternary, because it won't improperly round up multiples of 4 so that's no longer a special case. popcount trickery You're using a good trick already, but there is still a possibility for more. One interesting property of the trick you used is that when it has done a couple of steps, it starts to waste some of its potential, by which I mean for example that the third step, (x + (x >> 4)) & m4, adds adjacent nibbles, but the values in those nibbles range from 0 to 4 (inclusive), not the range 0 to 15. If the loop was unrolled a factor of two, then instead of having two whole copies of the popcount trick, only the first half needs to be duplicated: then the intermediate results could be added (producing nibbles with values in the range 0 to 8, inclusive), and the second half of the trick (the third and fourth steps) needs only to be performed once. There are more tricks, for example given 3 uint32s (a, b, c), we only need 2 32-bit popcounts to count all the bits: b0 = a ^ b ^ c b1 = (a & (b | c)) | (b & c) count = popcount(b0) + 2 * popcount(b1) The bit-manipulation steps are effectively a bit-level 3-input addition, with the 2-bit result spread across two variables: at each position, b0 holds bit 0 of the sum at that position, b1 holds bit 1 of the sum. This can be generalized to combining 7 inputs into 3, 15 into 4, etc. Even better versions of this idea can be found in Faster Population Counts Using AVX2 Instructions (of course you won't be using AVX2 in JavaScript, but some of the same techniques can be applied to reduce the number of actual popcounts).
{ "domain": "codereview.stackexchange", "id": 43999, "lm_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, array", "url": null }
javascript, html, dom Title: Wrting A Movie app , must be a better way Question: I am trying to get the value from the from and and pass it to the API and output the result to the DOM. The code works fine but I am 1000% sure there is a better way to write THIS. Thanks for the help and I am new so trying to learn. JS CODE const textInput = document.querySelector(`#search__box`); const btn = document.querySelector(`#btn`); const ShowName = document.querySelector(`.show__name`); const btn_rest = document.querySelector(`.btn__reset`); let btn__test = ""; const btnClickHandler = (e) => { e.preventDefault(); axios.get(`https://api.tvmaze.com/search/shows?q=${userData}`).then((res) => { const looparr = res.data; try { for (show of looparr) { const createDiv = document.createElement(`div`); const createA = document.createElement(`p`); const createIMG = document.createElement(`img`); const createH3 = document.createElement(`h3`); const createH4 = document.createElement(`h4`); createDiv.classList.add(`yes`); createIMG.classList.add(`img-style`); createH3.innerHTML = show.show.summary; createIMG.src = show.show.image.medium; createH4.innerText = `Release Year ${show.show.premiered}`; ShowName.append(createDiv); createDiv.append(createA); createDiv.append(createIMG); createDiv.append(createH3); createDiv.append(createH4); createDiv.style.borderBottom = `1px solid black`; createA.classList.add(`test`); createA.innerText = show.show.name; btn__test = document.querySelectorAll(`.yes`); } } catch { (e) => {}; } }); };
{ "domain": "codereview.stackexchange", "id": 44000, "lm_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, html, dom", "url": null }
javascript, html, dom const btnResetHanddler = (e) => { e.preventDefault(); for (div of btn__test) { ShowName.removeChild(div); } textInput.value = ""; }; const inputHanddler = (e) => { const test = e.target.value; return (userData = test); }; btn.addEventListener(`click`, btnClickHandler); textInput.addEventListener(`change`, inputHanddler); btn_rest.addEventListener(`click`, btnResetHanddler); html{ font-size: 62.5%; position: relative; } .search__wrapper{ font-size: 3rem; display: flex; justify-content: center; } #search__box{ width: 30rem; height: 3rem; border-radius: 2rem; border: none; background-color: rgb(213, 207, 207); } .show__name{ display: flex; font-size: 2rem; flex-direction: column; } .show__name p { margin: 1.2rem; font-size: 3rem; text-align: center; } .test{ font-size: 40rem; color: black; } .img-style{ transition: all 2s; width: 400px; } .img-style:hover{ transform: scale(1.1); margin-top: 1.5rem;} .yes { display: flex; flex-direction: column; align-items: center; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TV APP</title> <link rel="stylesheet" href="style.css"> </head> <body> <section class="search__wrapper"> <form action="#"> <label for="search__box">search</label> <input type="search" name="search__box" id="search__box"> <button type="submit" id="btn">Submit</button> <button class="btn__reset">Reset</button> </form> <ul class="list"> </ul> </section> <section class="show__name"> </section> <script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script> <script src="app.js"></script> </body> </html>
{ "domain": "codereview.stackexchange", "id": 44000, "lm_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, html, dom", "url": null }
javascript, html, dom </html> Answer: Some improvements I can suggest: Use a linter for your CSS to ensure the formatting remains constant, it allows others to more easily assist you. For example, this portion would be automatically fixed on save: .img-style:hover{ transform: scale(1.1); margin-top: 1.5rem;} Use a variable assignment when in JavaScript loops, otherwise you are creating a global variable which can have unintended consequences. So this: for (show of looparr) { Would turn into this: for (const show of looparr) { Since you do not need to change the value of the variable during your iterations. Don't place btn__test = document.querySelectorAll(".yes"); inside your upper loop, that will be called multiple times unnecessarily. Instead, place that segment within the btnResetHanddler function, where it is actually used.
{ "domain": "codereview.stackexchange", "id": 44000, "lm_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, html, dom", "url": null }
c, tower-of-hanoi Title: Tower of Hanoi (without recursion) Question: I came across an interesting method of solution for the Tower of Hanoi puzzle and wrote a short version of it as a programming exercise. The program produces the correct results but I have two questions. First is there simpler way to write the alternating step of determining the only valid move which does not involve the smallest disk. Second when I try to make the two primary routines (move smallest disk and make alternating move) into functions the handling of variables becomes unwieldy. /* tower.c Tower of Hanoi -- mechanical solution Place one of the three rods upright at each corner of a triangle. Alternate between moving the smallest disk and making the only valid move which does not involve the smallest disk. The smallest disk always moves in the same direction: counter-clockwise if there are an odd number of disks in the puzzle; clockwise if there are an even number of disks in the puzzle. from "The Icosian Game and the Tower of Hanoi" in THE SCIENTIFIC AMERICAN BOOK OF MATHEMATICAL PUZZLES & DIVERSIONS by Martin Gardner, (Simon and Schuster, 1959), pp. 55 - 62 */ #include <stdio.h> #include <stdbool.h> int destinationCount (int array[], int numberOfElements) { int count = 0, i; for ( i = 1; i <= numberOfElements; ++i ) if ( array[i] == 3 ) ++count; return count; }
{ "domain": "codereview.stackexchange", "id": 44001, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, tower-of-hanoi", "url": null }
c, tower-of-hanoi return count; } int main (void) { int numberOfDisks, i, smallestDir, moveCount = 0; bool everyOtherMove = false; int rodFrom, rodTo, disk; int topDisk[4]; int temp; printf ("\nTower of Hanoi puzzle\n"); printf ("\nnumber of disks? "); scanf ("%i", &numberOfDisks); int rod[numberOfDisks + 1]; // all disks start on rod 1 for ( i = 1; i <= numberOfDisks; ++i ) rod[i] = 1; // set direction to move smallest disk if ( (numberOfDisks & 1) == 0 ) smallestDir = 1; else smallestDir = -1; printf("\nsolution\n\n"); do { ++moveCount; if ( ! everyOtherMove ) { // move smallest disk rodFrom = rod[1]; rodTo = rodFrom + smallestDir; if ( rodTo > 3 ) rodTo = 1; if ( rodTo < 1 ) rodTo = 3; disk = 1; } else { // make only valid move not involving the smallest disk // find disk at the top of each rod for ( i = 1; i <= 3; ++i ) topDisk[i] = numberOfDisks + 1; for ( i = numberOfDisks; i >= 1; --i ) topDisk[rod[i]] = i; // find which disk to move switch ( rod[1] ) { case 1: rodFrom = 2; rodTo = 3; break; case 2: rodFrom = 1; rodTo = 3; break; case 3: rodFrom = 1; rodTo = 2; break; default: printf ("error"); break; }
{ "domain": "codereview.stackexchange", "id": 44001, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, tower-of-hanoi", "url": null }
c, tower-of-hanoi if ( topDisk[rodFrom] > topDisk[rodTo] ) { // swap values temp = rodFrom; rodFrom = rodTo; rodTo = temp; } disk = topDisk[rodFrom]; } printf ("%i: disk %i rod %c to rod %c\n", moveCount, disk, rodFrom + 64, rodTo + 64); // move disk rod[disk] = rodTo; // toggle everyOtherMove everyOtherMove = ! everyOtherMove; } while ( destinationCount (rod, numberOfDisks) != numberOfDisks ); return 0; } Answer: Remove the everyOtherMove flag variable You use it only once to control the logic of your program: if ( ! everyOtherMove ) { and this usage may be substitued with a evenness check of the moveCount variable that you would have anyway. Do not declare vars so much before using them At line 36 temp is declared as an int, at line 113 temp is used for the first time. How can the reader remember the type of temp 77 lines later? Declare it just before using it. Loop variables should be declared inside the loop statement as C99 allows it. Use ternary when it clearly simplifies if ( (numberOfDisks & 1) == 0 ) smallestDir = 1; else smallestDir = -1; Becomes int smallestDir = (numberOfDisks & 1) == 0 ? 1 : -1 Much shorter and without the smallestDir = repetition. Using % instead of bitwise operations to check evenness would be a further improvement. Reduce main (both code and vertical whitespace) I introduce this helper function: int wrap_around(int min, int max, int value) { return value < min ? max : (value > max ? min : value); }
{ "domain": "codereview.stackexchange", "id": 44001, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, tower-of-hanoi", "url": null }
c, tower-of-hanoi (Please note that it could also be written with if conditionals, I wrote it like this just because of my familiarity with ternary). The first if branch now is: if (moveCount % 2 == 0) { // move smallest disk rodFrom = rod[1]; rodTo = wrap_around(1, 3, rodFrom + smallestDir); disk = 1; } while before it was: if ( ! everyOtherMove ) { // move smallest disk rodFrom = rod[1]; rodTo = rodFrom + smallestDir; if ( rodTo > 3 ) rodTo = 1; if ( rodTo < 1 ) rodTo = 3; disk = 1; } The same concept is expressed in much less space, and this is a good attribute in my view because: Some logic is modularized in other functions, the reader gets a more abstract overview. If all code is compacted this way an overall view of the program becomes possible helping understanding. Compacting the else clause else { // make only valid move not involving the smallest disk // find disk at the top of each rod for ( i = 1; i <= 3; ++i ) topDisk[i] = numberOfDisks + 1; for ( i = numberOfDisks; i >= 1; --i ) topDisk[rod[i]] = i; // find which disk to move switch ( rod[1] ) { case 1: rodFrom = 2; rodTo = 3; break; case 2: rodFrom = 1; rodTo = 3; break; case 3: rodFrom = 1; rodTo = 2; break; default: printf ("error"); break; } if ( topDisk[rodFrom] > topDisk[rodTo] ) { // swap values temp = rodFrom; rodFrom = rodTo; rodTo = temp; } disk = topDisk[rodFrom]; }
{ "domain": "codereview.stackexchange", "id": 44001, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, tower-of-hanoi", "url": null }
c, tower-of-hanoi disk = topDisk[rodFrom]; } I do not fully understand the uppermost two for loops but both the switch and the body of the if ( topDisk[rodFrom] > topDisk[rodTo] ) statement are performing very clear, specific tasks, so: else { // make only valid move not involving the smallest disk // find disk at the top of each rod for ( i = 1; i <= 3; ++i ) topDisk[i] = numberOfDisks + 1; for ( i = numberOfDisks; i >= 1; --i ) topDisk[rod[i]] = i; // find which disk to move find_start_and_destination(rod[1], *rodFrom, *rodTo); if ( topDisk[rodFrom] > topDisk[rodTo] ) { SWAP(rodFrom, rodTo); } disk = topDisk[rodFrom]; } I just removed the unnecessary blanklines (blanklines should separate logically separated blocks of code, not each line / statement), and used a function to incorporate the switch and a macro to swap variables. The function must use pointers because two values may not be returned from a function in C, but I think the modularization is still an advantage.
{ "domain": "codereview.stackexchange", "id": 44001, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, tower-of-hanoi", "url": null }
interview-questions, react.js, jsx, redux Title: Proper way of using redux and props Question: I made a weather app in react and redux for an interview. The response was that I didn't use redux properly, and that it has unnecessary props. I'm not sure what they meant. The app is on github https://github.com/s-e1/weather-app There are 2 pages in the App, Home contains SearchBar and HomeMain, HomeMain contains an array of ForecastCard. Favorites contains an array of CityCard. reducer.js const initialState = { cityName: "Tel Aviv", cityKey: 215854, searchResults: [], weatherResults: {} }; const reducer = (state = initialState, action) => { switch (action.type) { case 'SET NAME': return { ...state, cityName: action.payload }; case 'SET KEY': return { ...state, cityKey: action.payload }; case 'SET SEARCH': return { ...state, searchResults: action.payload }; case 'SET WEATHER': return { ...state, weatherResults: action.payload }; default: return state; } } export default reducer; utils.js - for sending requests to the server import axios from "axios"; const server = "https://weather-app-serv.herokuapp.com/" || "http://localhost:8000/"; export const getSearchRequest = async (cityName) => { if (!cityName) return []; let reply = await axios.get(server + "search?name=" + cityName); return reply.data; } export const getWeatherRequest = async (key) => { const url = `${server}weather?key=${key}`; let reply = await axios.get(url); return reply.data; } export const getFavoritesRequest = async (key) => { const url = `${server}favorites?key=${key}`; let reply = await axios.get(url); return reply.data; } app.js import { useEffect } from "react"; import { Switch, Route } from "react-router-dom"; import { useDispatch, useSelector } from 'react-redux';
{ "domain": "codereview.stackexchange", "id": 44002, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "interview-questions, react.js, jsx, redux", "url": null }
interview-questions, react.js, jsx, redux import Navbar from "./components/Navbar"; import Home from "./components/Home"; import Favorites from "./components/Favorites"; import { getSearchRequest, getWeatherRequest } from "./utils"; import "./App.css"; function App() { const dispatch = useDispatch(); const cityName = useSelector(state => state.cityName); const cityKey = useSelector(state => state.cityKey); useEffect(() => { weatherCB(cityName, cityKey); }, []) const searchCB = (name) => { getSearchRequest(name) .then(data => { dispatch({ type: "SET SEARCH", payload: data }); }) } const weatherCB = (name, key) => { dispatch({ type: "SET NAME", payload: name }); dispatch({ type: "SET KEY", payload: key }); getWeatherRequest(key) .then(data => { dispatch({ type: "SET WEATHER", payload: data }); }) } return ( <div className="appContainer"> <Navbar /> <Switch> <Route exact path="/"><Home searchCB={searchCB} weatherCB={weatherCB} /></Route> <Route path="/favorites"><Favorites weatherCB={weatherCB} /></Route> </Switch> <footer> <p>Data provided by <a href="https://developer.accuweather.com/">Accuweather</a></p> </footer> </div> ); } export default App; Home.js - contains SearchBar and HomeMain import SearchBar from "./SearchBar"; import HomeMain from "./HomeMain"; import ErrorBoundary from "../ErrorBoundary"; function Home({ searchCB, weatherCB }) { return ( <div> <ErrorBoundary> <SearchBar searchCB={searchCB} weatherCB={weatherCB} /> </ErrorBoundary> <ErrorBoundary> <HomeMain /> </ErrorBoundary> </div> ); } export default Home;
{ "domain": "codereview.stackexchange", "id": 44002, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "interview-questions, react.js, jsx, redux", "url": null }
interview-questions, react.js, jsx, redux </div> ); } export default Home; SearchBar.js - a child of Home component import { useState } from "react"; import { useSelector } from 'react-redux'; import "./SearchBar.css"; function SearchBar({ searchCB, weatherCB }) { const searchResults = useSelector(state => state.searchResults); const [text, setText] = useState(""); const search = (e) => { setText(e.target.value); searchCB(e.target.value); } const sendWeather = (name, key) => { weatherCB(name, key); setText(""); searchCB(""); } return ( <div> <div className="searchBar">Search: <input onChange={search} value={text} /> </div> {searchResults.length ? <ul className="searchResults"> {searchResults.map((e, i) => { return <li className="searchItem" key={i} onClick={() => sendWeather(e.cityName, e.key)}> {e.cityName}, {e.countryName} </li> })} </ul> : null} </div> ); } export default SearchBar; HomeMain.js - a child of Home component import { useEffect, useState } from "react"; import { useSelector } from 'react-redux'; import ForecastCard from "./ForecastCard"; import "./HomeMain.css"; function HomeMain() { const cityName = useSelector(state => state.cityName); const cityKey = useSelector(state => state.cityKey); const weatherResults = useSelector(state => state.weatherResults); const [currentWeather, setCurrentWeather] = useState({}); const [forecast, setForecast] = useState([]); const [imgUrl, setImgUrl] = useState(""); const [isFavorite, setIsFavorite] = useState(false); const daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const today = new Date().getDay(); const iconSite = "https://developer.accuweather.com/sites/default/files/";
{ "domain": "codereview.stackexchange", "id": 44002, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "interview-questions, react.js, jsx, redux", "url": null }
interview-questions, react.js, jsx, redux useEffect(() => { if (weatherResults.currentWeather || weatherResults.forecast) { setCurrentWeather(weatherResults.currentWeather); setForecast(weatherResults.forecast); const url = iconSite + weatherResults.currentWeather.icon.padStart(2, '0') + "-s.png" setImgUrl(url); setIsFavorite(checkIfFavorite()); } }, [weatherResults.currentWeather, weatherResults.forecast]) const checkIfFavorite = () => { if (!localStorage.weatherApp) return false; const arr = JSON.parse(localStorage["weatherApp"]); const found = arr.some(e => e.cityName === cityName); return found; } const addFavorite = () => { setIsFavorite(true); let arr; if (!localStorage.weatherApp) { arr = []; } else { arr = JSON.parse(localStorage["weatherApp"]); const found = arr.some(e => e.cityName === cityName); if (found) return; } arr.push({ cityKey, cityName }); localStorage["weatherApp"] = JSON.stringify(arr); } const removeFavorite = () => { setIsFavorite(false); const arr = JSON.parse(localStorage["weatherApp"]); const filteredArr = arr.filter(e => e.cityName !== cityName); localStorage["weatherApp"] = JSON.stringify(filteredArr); } return ( <div className="homeMain"> {currentWeather.text ? <div > {isFavorite ? <button onClick={removeFavorite}>Remove From Favorites</button> : <button onClick={addFavorite}>Add To Favorites</button> }
{ "domain": "codereview.stackexchange", "id": 44002, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "interview-questions, react.js, jsx, redux", "url": null }
interview-questions, react.js, jsx, redux <div className="currentWeather"> <h4>{cityName}</h4> <img src={imgUrl} alt="icon" /> <div>{currentWeather.temperature + '\u00B0'}c</div> <div>{currentWeather.text}</div> </div> </div> : null} {forecast.length ? <div className="forecast"> {forecast.map((e, i) => { return <ForecastCard key={i} high={e.high} low={e.low} day={daysOfWeek[(today + i) % 7]}> </ForecastCard> })} </div> : null} </div> ); } export default HomeMain; ForecastCard.js - a child of HomeMain import "./ForecastCard.css"; function ForecastCard({ day, high, low }) { return ( <div className="forecastCard"> <strong>{day}</strong> <div>H: {high + '\u00B0'}c </div> <div>L: {low + '\u00B0'}c</div> </div> ); } export default ForecastCard; The 2nd page in the app for the Favorite cities weather, a child of App. import { useEffect, useState } from "react"; import ErrorBoundary from "../ErrorBoundary"; import CityCard from "./CityCard"; import "./Favorites.css"; function Favorites({ weatherCB }) { const [cityArray, setCityArray] = useState([]); useEffect(() => { if (!localStorage.weatherApp) return; setCityArray(JSON.parse(localStorage["weatherApp"])); }, []) return ( <div> <ErrorBoundary> <div className="favorites"> {cityArray.length ? cityArray.map((e, i) => { return <CityCard key={i} data={e} weatherCB={weatherCB} /> }) : null} </div> </ErrorBoundary> </div> ); } export default Favorites;
{ "domain": "codereview.stackexchange", "id": 44002, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "interview-questions, react.js, jsx, redux", "url": null }
interview-questions, react.js, jsx, redux export default Favorites; CityCard.js is a child of Favorites. import { useEffect, useState } from "react"; import { useHistory } from "react-router"; import { getFavoritesRequest } from "../utils"; import "./CityCard.css"; function CityCard({ data, weatherCB }) { const [resData, setResData] = useState({}); let history = useHistory(); useEffect(() => { getFavoritesRequest(data.cityKey) .then(res => setResData(res)); }, [data]) const goToDetails = () => { history.push("/"); weatherCB(data.cityName, data.cityKey); } return ( <div onClick={goToDetails} className="cityCard"> {resData.text ? <div> <h1>{data.cityName}</h1> <div>{resData.temperature + '\u00B0'}c</div> <div>{resData.text}</div> </div> : null} </div> ); } export default CityCard; Any suggestions about improving the code are welcome. Answer: Redux has a really great style guide which outlines all of the best practices. I can use that to show which rules you are breaking to give you more specific feedback. The good news is that you are not breaking any of the rules in the "essential" category. You've got the basics down, but you need refinement on the best practices. The response was that I didn't use redux properly, and that it has unnecessary props. I'm not sure what they meant. Let's start with the issue of "unnecessary props". You are passing down the searchCB and weatherCB props through multiple components: from App to Home to SearchBar. You shouldn't need to do this sort of "prop drilling" with redux because the redux store is global. SearchBar can connect to redux directly, and make changes which will affect App and other components. Connect More Components to Read Data from the Store
{ "domain": "codereview.stackexchange", "id": 44002, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "interview-questions, react.js, jsx, redux", "url": null }
interview-questions, react.js, jsx, redux Connect More Components to Read Data from the Store Let's look at the function itself, because there are a few rules to consider here: const weatherCB = (name, key) => { dispatch({ type: "SET NAME", payload: name }); dispatch({ type: "SET KEY", payload: key }); getWeatherRequest(key) .then(data => { dispatch({ type: "SET WEATHER", payload: data }); }) } Avoid Dispatching Many Actions Sequentially Model Actions as Events, Not Setters Use Thunks for Async Logic Move Complex Logic Outside Components What we want is a single action which can be dispatched from any component anywhere in the app when the user selects a city. The action which happened is that a city was selected. You'll want to pass the city name and key in the payload. There's a rule specifically for this next one, but... const [currentWeather, setCurrentWeather] = useState({}); const [forecast, setForecast] = useState([]); const [imgUrl, setImgUrl] = useState(""); /*... */ useEffect(() => { if (weatherResults.currentWeather || weatherResults.forecast) { setCurrentWeather(weatherResults.currentWeather); setForecast(weatherResults.forecast); const url = iconSite + weatherResults.currentWeather.icon.padStart(2, '0') + "-s.png" setImgUrl(url); setIsFavorite(checkIfFavorite()); } }, [weatherResults.currentWeather, weatherResults.forecast]) In your HomeMain component you are copying state that already exists in redux into the local state of your component. You don't want to do this. Just use the redux state directly, and make use of selector functions if you want to derive values from it. I'm rewriting your reducer.js file using thunks, and that will allow us to do some cleanup in the components. import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; import { getSearchRequest, getWeatherRequest } from "./utils";
{ "domain": "codereview.stackexchange", "id": 44002, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "interview-questions, react.js, jsx, redux", "url": null }
interview-questions, react.js, jsx, redux const initialState = { city: { name: "Tel Aviv", key: 215854 }, searchResults: [], weatherResults: {} }; export const fetchSearchResults = createAsyncThunk( "weather/fetchSearchResults", getSearchRequest ); export const fetchWeather = createAsyncThunk( "weather/fetchWeather", getWeatherRequest ); const weatherSlice = createSlice({ name: "weather", initialState, reducers: { selectCity: (state, action) => { state.city = action.payload; } }, extraReducers: (builder) => builder .addCase(fetchSearchResults.fulfilled, (state, action) => { state.searchResults = action.payload; }) .addCase(fetchWeather.fulfilled, (state, action) => { state.weatherResults = action.payload; }) }); export default weatherSlice.reducer; export const { selectCity } = weatherSlice.actions; This requires a little change in index.js to enable thunk middleware and other redux-toolkit features. import { configureStore } from "@reduxjs/toolkit"; const store = configureStore({ reducer }); Home and SearchBar should not take any props. SearchBar involves two actions: selecting a city and submitting a search request. const dispatch = useDispatch(); const search = (e) => { setText(e.target.value); dispatch(fetchSearchResults(e.target.value)); }; const sendWeather = (name, key) => { dispatch(selectCity({ name, key })); setText(""); }; App does not need any redux logic at all! All of the subcomponents can handle that themselves. So you can delete a lot here. HomeMain can be responsible for initiating the weather fetching for the currently selected city. We also want to get rid of all of the redundant state. const cityName = useSelector((state) => state.cityName); const cityKey = useSelector((state) => state.cityKey); const weatherResults = useSelector((state) => state.weatherResults); const { currentWeather, forecast } = weatherResults; const dispatch = useDispatch();
{ "domain": "codereview.stackexchange", "id": 44002, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "interview-questions, react.js, jsx, redux", "url": null }
interview-questions, react.js, jsx, redux const { currentWeather, forecast } = weatherResults; const dispatch = useDispatch(); useEffect(() => { dispatch(fetchWeather(cityKey)); }, [dispatch, cityKey]); Complete Revised Code
{ "domain": "codereview.stackexchange", "id": 44002, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "interview-questions, react.js, jsx, redux", "url": null }
python, performance, algorithm, physics, markov-chain Title: Calculating the energy of the harmonic oscillator using a Monte Carlo method Question: The problem The partition function for the quantum harmonic oscillator can be written in the path integral formulation as $$Z\propto\int Dx(\tau)\exp\left(-\frac{S_E}{\hbar}\right)=\int Dx(\tau)\exp\left(-\frac{\int_0^{\beta \hbar}d\tau\left(\frac{1}{2}m\dot x^2(\tau)+\frac{1}{2}m\omega^2 x^2(\tau)\right)}{\hbar}\right) $$ To attack this problem numerically, we can make this quantity discrete by choosing a sequence of N points x1,...,xN on the path x(τ) with distance a between each other; rescaling these variables we can write $$\frac{S_E^{discrete}}{\hbar}=\sum_{j=1}^N\left(\frac{1}{2\eta}(y_{j+1}-y_j)^2+\frac{\eta}{2}y_j^2\right) $$ where η=aω. The continuum is then recovered in the limit of small η. In this discrete form, the internal energy of the system transforms as follows: $$\frac{U^{cont}}{\hbar\omega}=\partial_\beta\log Z=\hbar\omega\left(\frac{1}{2}+\frac{1}{e^{N\eta}-1}\right) \ \Rightarrow \ \frac{U^{discrete}}{\hbar\omega}=\frac{1}{2\eta}-\frac{1}{2\eta^2}\langle \Delta y^2\rangle+\frac{1}{2}\langle y^2\rangle$$ where the averages are first taken over a single path, and then over all paths generated in the Monte Carlo simulation according to the distribution function $$p(y_1,...,y_N)=e^{-S_E^{discrete}/\hbar}.$$ My goal is to compute the internal energy and compare it to the theoretical value for various values of N, in function of the inverse temperature Nη. The algorithm In order to sample paths that follow this distribution, we can employ a MCMC method based on the Metropolis algorithm: Initialize the discrete path in a cold configuration (all zeros) or hot configuration (random numbers) For each Monte Carlo sweep, loop on all j=1,...,N and propose to modify y_j with a uniformly sampled y_p in the interval [y_j-δ,y_j+δ] for some parameter δ.
{ "domain": "codereview.stackexchange", "id": 44003, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, algorithm, physics, markov-chain", "url": null }
python, performance, algorithm, physics, markov-chain The update is accepted with probability $$r=e^{-\Delta S_{E}^{discrete}},$$ where the difference in the action (between the original and the modified path) can be easily computed as \begin{align*} \Delta S_{E}^{discrete}&=(y^p)^2\left(\frac{\eta}{2}+\frac{1}{\eta}\right)-\frac{y^p}{\eta}(y_{j_0+1}+y_{j_0-1})-y_{j_0}^2\left(\frac{\eta}{2}+\frac{1}{\eta}\right)\\&-\frac{1}{2}y_{j_0}(y_{j_0+1}+y_{j_0-1}). \end{align*} The code As kindly reviewed by a user of this forum, I report here the code that I wrote of a MCMC simulation of the quantum harmonic oscillator in the path integral formulation: import numpy as np import matplotlib.pyplot as plt from numpy.random import default_rng, Generator import time as tm def metropolis_ho( path: np.ndarray, rand: Generator, eta: float, delta: float, ntimes: int, equilibrium_start: int = 10_000, ) -> tuple[ np.ndarray, # observables 1 np.ndarray, # observables 2 ]: """Monte Carlo Simulation""" n = len(path) # Initialize arrays of observables obs1 = np.empty(ntimes) obs2 = np.empty(ntimes) # Useful constants c1 = 1/eta c2 = c1 + eta/2 # Iterate loop on all sites for i in range(ntimes): for j in range(n): for _ in range(3): # Set y as j-th point on path y = path[j] # Propose modification y_p = rand.uniform(y - delta, y + delta) # Calculate accept probability force = path[(j + 1) % n] + path[j - 1] p_ratio = c1*force*(y_p - y) + c2*(y*y - y_p*y_p) # Accept-reject if rand.random() < np.exp(p_ratio): path[j] = y_p # Average of y^2 on the path obs1[i] = np.dot(path, path)/n # Average of Delta y^2 on the path diff = path - np.roll(path, -1) obs2[i] = np.dot(diff, diff)/n
{ "domain": "codereview.stackexchange", "id": 44003, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, algorithm, physics, markov-chain", "url": null }
python, performance, algorithm, physics, markov-chain # Get rid of non-equilibrium states and decorrelate n_term = equilibrium_start obs1 = obs1[n_term:] obs2 = obs2[n_term:] return obs1, obs2 def U(obs1,obs2,eta): """Computes internal energy""" c1=1/(2*eta) c2=1/(2*eta**2) av1=np.average(obs1) av2=np.average(obs2) return c1-c2*av2+av1/2 def exact_U(n,eta): """"Theoretical expectation for internal energy""" return 0.5+1./(np.exp(n*eta)-1) begin=tm.time() #Initialize arrays to plot U(n) n_array=np.asarray([5,10,15,20,25,30,40,50]) U_array=[] for n in n_array: #Initialize path hot = True rand: Generator = default_rng(seed=0) if hot: start = rand.uniform(low=-1, high=1, size=n) else: start = np.zeros(n) #Run MCMC obs1, obs2 = metropolis_ho( path=start, rand=rand, eta=0.01, delta=1, ntimes=80000, equilibrium_start=1000, ) #Compute energy U_array.append(U(obs1,obs2,eta=0.01)) plt.plot(np.dot(n_array,0.01),U_array,linestyle='None',marker='s',color='k') #Set arrays for plotting exact U n_array=np.arange(0.01,300,0.1) exact_U_array=[] for n in n_array: #Compute theoretical value exact_U_array.append(exact_U(n,eta)) plt.plot(np.dot(eta,n_array),exact_U_array,'b') plt.ylim(0,12) plt.xlim(0,3) plt.show() end=tm.time() print(f"Total runtime: {end-begin}.") Results Even without error bars, it is pretty evident that my results are just not that accurate. Can the code be improved or fixed in order to obtain a closer fit? Answer: You will probably get feedback more specific to the physics problem you are solving at physics.stackexchange.com [Thanks to Reinderien in the comments for clarification.] As for the code itself, there are some issues that may make debugging harder: Bad naming - names should explain what they are actually naming # Useful constants c1 = 1/eta c2 = c1 + eta/2
{ "domain": "codereview.stackexchange", "id": 44003, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, algorithm, physics, markov-chain", "url": null }
python, performance, algorithm, physics, markov-chain # Useful constants c1 = 1/eta c2 = c1 + eta/2 I can't tell what c1 means by looking at its name. def U(obs1,obs2,eta): """Computes internal energy""" Should be named get_internal_energy(). Comments should explain why, not what # Set y as j-th point on path y = path[j] I can see what it does by reading the code. The question is why do we need this line? def U(obs1,obs2,eta): """Computes internal energy""" You write in the docstring what should be in the name of the method. Inconsistent spacing Your spacing is all over the place, though this issue is minor and can be fixed easily. Reformat the file (e.g. Ctrl+Alt+L in PyCharm) with whatever linter you're using, it inreases readability at zero cost.
{ "domain": "codereview.stackexchange", "id": 44003, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, algorithm, physics, markov-chain", "url": null }
c++, design-patterns Title: Is this the correct way of implementing a builder pattern in C++? Question: Coming from a Javascript background, and just now getting into c++. Want to know if im doing the builder pattern correctly in C++, and also what could improve on ? PongObject.cpp using namespace std; class PongObject{ private: int objectHeight; int objectWidth; int offset; int objectScreenHeight; Color objectColor; public: void setPongObjectWidth(int width){ this->objectWidth = width; } void setPongObjectHeight(int height){ this->objectHeight = height; } void setPongObjectOffset(int offset){ this->offset = offset; } void setPongObjectScreenHeight(int screenHeight){ this->objectScreenHeight = screenHeight; } void setPongObjectColor(Color color){ this->objectColor = color; } void build(){ DrawRectangle(offset, objectScreenHeight, objectWidth, objectHeight, objectColor); } }; PongObjectBuilder.cpp class PongBuilder: PongObject{ public: PongBuilder& setWidth(int width){ this->setPongObjectWidth(width); return *this; } PongBuilder& setHeight(int height){ this->setPongObjectHeight(height); return *this; } PongBuilder& setOffset(int offset){ this->setPongObjectOffset(offset); return *this; } PongBuilder& setScreenHeight(int screenHeight){ this->setPongObjectScreenHeight(screenHeight); return *this; } PongBuilder& setPongColor(Color color){ this->setPongObjectColor(color); return *this; } PongBuilder& buildObject(){ this->build(); return *this; } };
{ "domain": "codereview.stackexchange", "id": 44004, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns", "url": null }
c++, design-patterns }; main.cpp int main(void){ GameWindow window(1000, 1000); SetTargetFPS(60); window.setWindow(); PongBuilder* pongObj1 = new PongBuilder(); PongBuilder* pongObj2 = new PongBuilder(); int pong1Y = GetScreenHeight() / 2 - 50; int pong2Y = GetScreenHeight() / 2 - 50; const int someOffset = GetScreenWidth() - 100 - 50; while(!WindowShouldClose()){ ClearBackground(BLACK); BeginDrawing(); pongObj1->setWidth(100).setHeight(100).setOffset(50).setScreenHeight(pong1Y).setPongColor(RAYWHITE).buildObject(); if(IsKeyDown(KEY_A)){ pong1Y -= 500 * GetFrameTime(); } if(IsKeyDown(KEY_S)){ pong1Y += 500 * GetFrameTime(); } if(IsKeyDown(KEY_D)){ pong2Y-= 500 * GetFrameTime(); } if(IsKeyDown(KEY_F)){ pong2Y += 500 * GetFrameTime(); } pongObj2->setWidth(100).setHeight(100).setOffset(someOffset).setScreenHeight(pong2Y).setPongColor(BLUE).buildObject(); EndDrawing(); } delete pongObj1; delete pongObj2; return 0; } Answer: Looks like you got the idea wrong: Builder is a creational design pattern that lets you construct complex objects step by step. Builder is not supposed to be a subclass of the object you are building. It's a utility class whose only purpose is to create objects, don't use it to alter them after creation or for unrelated tasks such as drawing. This misuse leads to performance problems: you're setting width, height, offset and color every frame even though they never change. You can find a good c++ example with explanation here. Unrelated comments regarding your code:
{ "domain": "codereview.stackexchange", "id": 44004, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns", "url": null }
c++, design-patterns Don't use using namespace std;, it's like a wildcard import, will lead to name collisions. Your private block of PongObject is indented too much, make sure to reformat your code to make it more readable. No need to create your objects on the heap when you can do it on the stack. Just remove new keywords from object creation lines and you won't need to del them afterwards.
{ "domain": "codereview.stackexchange", "id": 44004, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns", "url": null }
c++, template-meta-programming, variant-type, visitor-pattern Title: C++: Visit Any Type Holding Other Types (`std::any`, `std::variant`, etc.) Question: Intro I want to visit the value held by a class, which could be of multiple types. This class is very similar to a std::any, so I will be using this in this question. I wanted to create a reusable solution that accesses the value efficiently (without recursion, or unnecessary calls), that worked similarly to how std::visit works for std::variant. Function This is what I have come up with: namespace detail { struct retriever { template <typename Type, typename Return, typename Visitor, typename Value> static Return get(Visitor&& visitor, Value&& value) { decltype(auto) innerValue = compatibility_layer<std::decay_t<Value>>::template get<Type>(std::forward<Value>(value)); return std::invoke(std::forward<Visitor>(visitor), std::move(innerValue)); } }; } template <typename... Alternatives, typename Visitor, typename Value> constexpr std::common_type_t<std::invoke_result_t<Visitor, Alternatives>...> visit(Visitor&& visitor, Value&& value) { using Return = std::common_type_t<std::invoke_result_t<Visitor, Alternatives>...>; constexpr std::array<bool(*)(const std::decay_t<Value>&), sizeof...(Alternatives)> compatibilityResult = { &compatibility_layer<std::decay_t<Value>>::template holds_alternative<Alternatives>... }; if (auto compatibleType = std::find_if(std::begin(compatibilityResult), std::end(compatibilityResult), [&] <typename F> (F&& f) { return std::invoke(std::forward<F>(f), value); }); compatibleType != std::end(compatibilityResult)) { constexpr std::array<Return(*)(Visitor&&, Value&&), sizeof...(Alternatives)> retrievers = { &detail::retriever::get<Alternatives, Return, Visitor, Value>... };
{ "domain": "codereview.stackexchange", "id": 44005, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, variant-type, visitor-pattern", "url": null }
c++, template-meta-programming, variant-type, visitor-pattern std::size_t index = std::distance(std::begin(compatibilityResult), compatibleType); return retrievers[index](std::forward<Visitor>(visitor), std::forward<Value>(value)); } else { throw std::invalid_argument("Value does not hold any of the alternatives."); } } The inputs to the function are a visitor and the value to be visited. Also, as template arguments, you have to provide which types should be tested for compatibility (the types to visit). The function uses a compatibility_layer class (which needs to be specialized for the type you want to support visiting (e.g., std::any), to: Determine whether the value holds a specific type Retrieve a certain type from the value For std::any, the implementation would be like this: template <> struct compatibility_layer<std::any> { template <typename T> constexpr static bool holds_alternative(const std::any& value) { return value.type() == typeid(T); } template <typename T> constexpr static decltype(auto) get(const std::any& value) { return std::any_cast<T>(value); } }; We don't invoke holds_alternative for all the types provided in the template argument Alternatives, but only until we find a true value. We do this by iterating over a std::array (populated at compile-time) holding pointers to the respective static methods holds_alternative. Similarly, we call get at most once, only for that type that is compatible. To map the compatible type to the get method to call, we create another std::array (also populated at compile-time) that holds pointers to the get methods. Then, we access the correct get method based on the index of the compatible type from the previous array. Example In this example, I visit a std::any and a std::variant (just as a test - I know std::visit should be used for variants). namespace { template <typename T> void doVisit(T&& value) {
{ "domain": "codereview.stackexchange", "id": 44005, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, variant-type, visitor-pattern", "url": null }
c++, template-meta-programming, variant-type, visitor-pattern template <typename T> void doVisit(T&& value) { auto visitor = [](auto &&v) { std::cout << "Made it! " << v << std::endl; }; vac::visit<bool, int, double, std::string>(std::move(visitor), std::forward<T>(value)); } } int main() { std::cout << "I am running" << std::endl; // Any example. std::any anyValue = std::string{"Any!"}; ::doVisit(std::move(anyValue)); // Variant example. std::variant<bool, int, double, std::string> variantValue = true; ::doVisit(std::move(variantValue)); } The compatibility_layer for the variant is similar: template <typename... Ts> struct compatibility_layer<std::variant<Ts...>> { template <typename T> constexpr static bool holds_alternative(const std::variant<Ts...>& value) { return std::holds_alternative<T>(value); } template <typename T> constexpr static decltype(auto) get(const std::variant<Ts...>& value) { return std::get<T>(value); } }; Feedback The function does what I need, but I am not sure whether it's any better than a recursive function like: template <typename FirstAlternative typename... OtherAlternatives, typename Visitor, typename Value> constexpr std::invoke_result_t<Visitor, FirstAlternative> visit(Visitor&& visitor, Value&& value) { if (compatibility_layer<std::decay_t<Value>>::template holds_alternative<FirstAlternative>(value)) { return detail::retriever::get<Alternatives, Return, Visitor, Value>(std::forward<Visitor>(visitor), std::forward<Value>(value)); } else { if constexpr (sizeof...(OtherAlternatives) == 0) { throw std::invalid_argument("Value does not hold any of the alternatives."); } else { return visit<OtherAlternatives...>(std::forward<Visitor>(visitor), std::forward<Value>(value)); } } } I wanted to avoid recursing, mainly to simplify debugging (as our std::any can hold 20 different types).
{ "domain": "codereview.stackexchange", "id": 44005, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, variant-type, visitor-pattern", "url": null }
c++, template-meta-programming, variant-type, visitor-pattern Answer: I could not find any issues with this code, except a slightly alternative way to implement it: Avoiding arrays I wanted to avoid recursing, mainly to simplify debugging (as our std::any can hold 20 different types). Although recursion might actually result in the cleanest code here, I can see the point. However, creating arrays of function pointers is also not very nice in my opinion. The usual way you replace recursive templates since C++17 is by using fold expressions. We can do that here as well. Consider: template <typename... Alternatives, typename Visitor, typename Value> constexpr auto visit(Visitor &&visitor, Value &&value) { using Return = std::common_type_t<std::invoke_result_t<Visitor, Alternatives>...>; Return (*retriever)(Visitor &&, Value &&) = {}; ([&]{ if (compatibility_layer<std::decay_t<Value>>::template holds_alternative<Alternatives>(value)) { retriever = &detail::retriever::get<Alternatives, Visitor, Value>; } }(), ...); if (retriever) { return retriever(std::forward<Visitor>(visitor), std::forward<Value>(value)); } else { throw std::invalid_argument("Value does not hold any of the alternatives."); } } This could be improved by letting the lambda return a boolean, so you can short-circuit using ||. It is very unfortunate that std::optional<void> is not valid, otherwise I think having a std::optional<Return> result variable would make this code even cleaner. Visiting multiple variables at the same time If you look at the documentation of std::visit(), you'll notice that it can take multiple variables as arguments. Consider that you might have a visitor that takes two or more arguments, like in: std::variant<int, float> foo = 42; std::any bar = 3.1415; auto sum = visit<int, float, double>( [](auto a, auto b) -> double {return a + b;}, foo, bar); This is doable, but would of course complicate your code even more.
{ "domain": "codereview.stackexchange", "id": 44005, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, variant-type, visitor-pattern", "url": null }
python, python-3.x Title: Python script that generates random csv Question: I have a Python script that given some configuration, generates a random CSV file that can be used for testing purposes. I want to know if it adheres to the best Python and coding practices. It works for cases where I need upwards of 10K+ rows fast enough for my requirements, so I am not too worried about performance although inputs on performance are also appreciated. Input: Schema: as a dict, information about each column name, data type and some other constraints (like fixed length/in a range/ from a given list) Number of rows Name of the output CSV file Script: import random as rnd import csv from abc import ABC, abstractmethod # csv creator, creates a csv files with a given config roundPrecision = 3 class BoundType(ABC): def __init__(self, dtype, params): self.dType = dtype self.params = params @abstractmethod def generate(self): pass class FixedLength(BoundType): # params is length def generate(self): length = self.params.get("len", 1) if self.dType == "int": return rnd.randint(10 ** (length - 1), 10 ** length - 1) elif self.dType == "float": return FixedLength("int", self.params).generate() + round(rnd.random(), roundPrecision) elif self.dType == "string": alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") word = [rnd.choice(alphabet) for _ in range(length)] return ''.join(word) else: return None class FixedRange(BoundType): # params is range def generate(self): lo, hi = (self.params.get("lohi")) if self.dType == "int": return rnd.randint(lo, hi) elif self.dType == "float": return round(rnd.uniform(lo, hi), roundPrecision) else: return None
{ "domain": "codereview.stackexchange", "id": 44006, "lm_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 class FromPossibleValues(BoundType): # params is a list def generate(self): possibleval = self.params.get("set", set()) return rnd.choice(possibleval) def createcsv(rows, filename, schema): with open(f'./output/{filename}.csv', 'w', encoding='UTF8', newline='') as f: writer = csv.writer(f) writer.writerow(schema.keys()) for _ in range(rows): writer.writerow([x.generate() for x in schema.values()]) Test: from csvGen.csvGenerator import FixedLength, FixedRange, FromPossibleValues, createcsv schema = { "col1": FixedLength("int", {"len": 5}), "col2": FixedLength("float", {"len": 5}), "col3": FixedLength("string", {"len": 5}), "col4": FixedRange("int", {"lohi": (10, 15)}), "col5": FixedRange("float", {"lohi": (5.5, 6.7)}), "col6": FromPossibleValues("int", {"set": [1, 2, 3, 4, 5]}), "col7": FromPossibleValues("int", {"set": [1.1, 2.2, 3.3]}), "col8": FromPossibleValues("int", {"set": ["A", "AB"]}) } rows = 10 fileName = "eightVals" createcsv(rows, fileName, schema) This is what the output looks like for the given test : col1 col2 col3 col4 col5 col6 col7 col8 51685 71830.471 PAXBK 12 6.192 1 2.2 AB 60384 42341.991 RHNUK 11 6.037 1 1.1 AB 73505 30997.171 DVOGT 10 6.69 5 2.2 A 60528 85072.731 FWWXW 10 5.761 1 2.2 A 23048 65401.245 EVPUX 13 6.474 4 1.1 AB 74748 66969.774 PEULP 15 6.546 3 2.2 AB 88763 34749.184 VOAUO 10 6.402 4 2.2 AB 77351 44566.163 JOBQF 13 5.683 1 2.2 AB 50820 73002.154 EACZT 15 5.711 1 1.1 AB 53037 89225.572 YTLBI 13 6.328 1 2.2 AB Answer: This seems overbuilt, and would also be more tersely expressed with Numpy/Pandas. Additionally, your manual loops - whereas you're satisfied with current performance - will be faster in vectorised form. This program can be as simple as import numpy as np import pandas as pd from string import ascii_uppercase from numpy.random import default_rng
{ "domain": "codereview.stackexchange", "id": 44006, "lm_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 round_precision = 3 nrows = 10 rand = default_rng() array_3 = rand.choice(tuple(ascii_uppercase), size=(nrows, 5)) df = pd.DataFrame({ 'col1': rand.integers(low=1e4, high=1e5, size=nrows), 'col2': rand.uniform(low=1e4, high=1e5, size=nrows).round(decimals=round_precision), 'col3': pd.DataFrame(array_3).agg(''.join, axis=1), 'col4': rand.integers(low=10, high=16, size=nrows), 'col5': rand.uniform(low=5.5, high=6.7, size=nrows).round(decimals=round_precision), 'col6': rand.integers(low=1, high=6, size=nrows), 'col7': rand.choice(np.linspace(start=1.1, stop=3.3, num=3), size=nrows), 'col8': rand.choice(('A', 'AB'), size=nrows), }) df.to_csv('eightVals.csv', index=None) with output col1,col2,col3,col4,col5,col6,col7,col8 90510,54337.357,TITJJ,12,6.254,2,2.2,A 82827,10498.364,MLZFY,11,5.881,5,2.2,A 81292,95873.98,UOHVL,14,5.931,2,1.1,AB 44278,69859.781,RGQVO,11,6.492,2,2.2,AB 26424,18106.356,XPCYV,15,6.176,5,2.2,AB 12324,52143.779,VUEWA,15,5.959,2,3.3,A 38774,34881.201,URXXL,15,6.545,2,2.2,AB 25801,31699.204,XEWGS,14,6.427,3,3.3,A 59555,98153.322,WYGBV,11,6.062,1,2.2,A 44449,86569.519,MDNXN,15,6.229,1,3.3,A If this needs to be reusable (and I'm not entirely convinced that it is, given what you've shown), you can adapt the above to utility functions. I don't know that classes are necessary.
{ "domain": "codereview.stackexchange", "id": 44006, "lm_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, unit-testing, file-system, integration-testing Title: Clean up directories and files when a unit test fails Question: While running unit tests (most of them integration tests) with Python I create some directories. They need to be deleted after the test or when the test fails. The execution of the cleanup code need to be guaranteed. A fake or virtual filesystem (e.g. pyfakefs) or isn't a solution my situation because my unit tests call external tools (e.g. rsync) via subprocess.Popen. Also separated ramfs based filesystems not an option. I prefer vanilla unittest instead of pytest. The directories need to have a specific name. Random names are a problem. My current solution is a class that holds a pathlib.Path instance as a member and deletes it from the filesystem in its __del__() method. #!/usr/bin/env python3 import unittest import pathlib import shutil import time class SelfDestructingPath: def __init__(self, path): print('init') self._path = pathlib.Path(path) self._path.mkdir() def __del__(self): shutil.rmtree(self._path) print('del') @property def path(self): return self._path class MyTest(unittest.TestCase): def test_foobar(self): print('test start') sdp = SelfDestructingPath('auto_delete') self.assertTrue(sdp.path.exists()) time.sleep(5) self.assertTrue(False) print('test end') if __name__ == '__main__': unittest.main()
{ "domain": "codereview.stackexchange", "id": 44007, "lm_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, unit-testing, file-system, integration-testing", "url": null }
python, unit-testing, file-system, integration-testing print('test end') if __name__ == '__main__': unittest.main() The question here is if there is a more elegant solution. I know about context managers. But in my case I don't see an advantage to them. My solution does save me one indention because I don't have to create a with block. In my application I use that feature heavily. Another alternative would be to derive from pathlib.Path: class SelfDestructingPath(pathlib.Path). But I read somewhere that it is often not a good choice to derive from Python's own packages when you don't know what you are doing. Any suggestions to improve this or to make it more pythonic? Answer: It appears that you have reinvented Python's tempfile.TemporaryDirectory class. Yours is slightly different, as it doesn't respect the user's $TMPDIR (or equivalent). The implementation seems reasonable (except for its chattiness - I'd remove those print() calls). I recommend you use Python's TemporaryDirectory; it can be used as a context manager, can be cleaned manually, or can wait until garbage collection gets around to deleting it, so you have much more flexibility than with this class.
{ "domain": "codereview.stackexchange", "id": 44007, "lm_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, unit-testing, file-system, integration-testing", "url": null }
rust, vectors Title: Collect gaps in a number sequence in Rust using Vec::windows Question: I have the following code which collects gaps in a number sequence into a separate vec. There will never be a case, iterating over a Vec<i32> where .windows(2) will yield a window with None values. So I want to simplify things by transforming each window into a Gap with first and last i32 values wherever the gap between 2 numbers is > 1. So a transform -> filter -> result kind of pipeline. My version works, but seems imperative and long-winded. I keep thinking I should be able to use .from_fn(), .filter() and .collect() to generate the gap vector without a for loop. How would I go about this? #[derive(Debug)] struct Gap { first: i32, last: i32, } fn main() { let original_numbers = vec![1, 3, 4, 7, 8, 10, 11, 13, 6, 19, 20, 21]; let mut seq = original_numbers.clone(); seq.sort(); let windows = seq.windows(2); let mut gaps: Vec<Gap> = Vec::new(); for gap_window in windows { let g = Gap { first: if let Some(num) = gap_window.first() { *num + 1 } else { 0 }, last: if let Some(num) = gap_window.last() { *num - 1 } else { 0 }, }; if g.last - g.first >= 0 { gaps.push(g) } } for gap in gaps { println!("{:?}", gap) }; } Output: Gap { first: 2, last: 2 } Gap { first: 5, last: 5 } Gap { first: 9, last: 9 } Gap { first: 12, last: 12 } Gap { first: 14, last: 18 } Answer: My version works, but seems imperative and long-winded. I keep thinking I should be able to use .from_fn(), .filter() and .collect() to generate the gap vector without a for loop. How would I go about this? Use filter_map. It combines filter and map, and what you are doing is essentially mapping windows into gaps and filtering out invalid gaps. first: if let Some(num) = gap_window.first() { *num + 1 } else { 0 },
{ "domain": "codereview.stackexchange", "id": 44008, "lm_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, vectors", "url": null }
rust, vectors Rust has nice functions for dealing with Option. In this case you can do: first: gap_window.first().map(|num| *num + 1).unwrap_or(0) But why are defaulting to zero here? Silently defaulting to garbage values when an unexpected outcome occours is the worst possible strategy. It is way way better to panic: first: *gap_window.first().unwrap() + 1 Or even better: first: gap_window[0] + 1
{ "domain": "codereview.stackexchange", "id": 44008, "lm_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, vectors", "url": null }
c++, beginner, datetime, homework Title: Algorithm that prints day, when submitted date Question: I would love to know your opinion about this algorithm that we wrote in class. I was thinking about how I can optimize it (in terms of size of code/complexity) without using library functions (besides <iostream> for reading and writing). Assignment (translated): Gregorian calendar rule about leap years was introduced on (Friday) 15 of October in 1582. Write a program that when given a date in format “dd.MM.yyyy", will display the name of that day. You need to define and use enum type Weekday {Monday, Tuesday, …, Sunday}. Here is my code: #include <iostream> bool isLeapYear(int year){ if(year % 4 == 0 && year % 100 != 0){ return true; } else if (year % 400 == 0){ return true; } else { return false; } } enum Weeknday {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; int main() { // Get date int day,mounth,year; scanf("%d.%d.%d",&day,&mounth,&year); // Count days int days = 0; for(int i = 1582; i <= year; i++){ if(i != year) { if(isLeapYear(i)){ days += 366; } else { days += 365; } } else { for(int j = 1; j <= mounth; j++){ if(j != mounth){ if(j == 1 || j == 3 || j == 5 || j == 7 || j == 8 || j == 10 || j == 12){ days += 31; } else if (j == 4 || j == 6 || j == 9 || j == 11){ days += 30; } else if (j == 2){ if(isLeapYear(i)){ days += 29; } else { days += 28; } } } else { days += day; } } } }
{ "domain": "codereview.stackexchange", "id": 44009, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, datetime, homework", "url": null }
c++, beginner, datetime, homework int a = (days-3)%7; Weeknday enum_day; switch(a) { case 1: enum_day = Monday; std::cout << "Monday"; break; case 2: enum_day = Tuesday; std::cout << "Tuesday"; break; case 3: enum_day = Wednesday; std::cout << "Wednesday"; break; case 4: enum_day = Thursday; std::cout << "Thursday"; break; case 5: enum_day = Friday; std::cout << "Friday"; break; case 6: enum_day = Saturday; std::cout << "Saturday"; break; case 7: enum_day = Sunday; std::cout << "Sunday"; break; } std::cout << enum_day; } Answer: Almost everything, including input and output, is in the main() function. That makes it hard to create automatic tests for the code. I recommend creating a function that can be tested without any I/O: int weekday(int year, int month, int day) Then main() can do the reading of input and writing of output. We need to include <cstdio> to define std::scanf. The fact that you could build this on your platform without that include (and using plain scanf()) doesn't mean that it will build elsewhere, as that's due to optional choices made by your compiler that are not mandated by standard C++. When we use std::scanf(), we absolutely must check how many values it converted, otherwise we'll be working with unitialised variables. Here's a suggestion: // Get date int day, month, year; if (std::scanf("%d.%d.%d", &day, &mounth, &year) != 3) { std::cerr << "Input must be in 'day.month.year' format.\n"; return EXIT_FAILURE; } (We need to include <cstdlib> to define EXIT_FAILURE).
{ "domain": "codereview.stackexchange", "id": 44009, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, datetime, homework", "url": null }
c++, beginner, datetime, homework (We need to include <cstdlib> to define EXIT_FAILURE). In the switch to print the day name, we have case 7 which can never be reached. I think that was intended to be case 0. We could use an array of day names instead of the switch. If we define Weekday enum to begin with Sunday (which would then be equal to zero, we can convert our remainder of days directly to Weekday (int and enum types are convertible). If we're not allowed to change the order, we could change the arithmetic to reduce the value by 1. Always produce complete lines of output. Each line should end with '\n'. Spelling: it doesn't matter in a small program, but in larger programs (especially when working as part of a team) spelling errors can make searching for code difficult. Always try to use correct spellings for words such as "month" and "weekday". The algorithm can be improved. It's possible to work out how many days to add for a range of years without looping over each one individually (and note that we only care about the number of days modulo 7, so we only need to count 1 or 2 days for each year). Sticking with the iterative algorithm for now, let's examine it for problems. If we enter a year less than 1582, we'll give a meaningless result - it would be better to test for that and give an error message. (It's a quite likely user error to enter just the last two digits of the year, for example). The loop we have has a test for whether it's the last iteration. Instead of doing that, use a loop with one less iteration, and move the last-iteration code after the loop. That looks like this: for(int i = 1582; i < year; i++){ if(isLeapYear(i)){ days += 366; } else { days += 365; } }
{ "domain": "codereview.stackexchange", "id": 44009, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, datetime, homework", "url": null }
c++, beginner, datetime, homework for(int j = 1; j < mounth; j++) { if(j == 1 || j == 3 || j == 5 || j == 7 || j == 8 || j == 10 || j == 12){ days += 31; } else if (j == 4 || j == 6 || j == 9 || j == 11){ days += 30; } else if (j == 2){ if(isLeapYear(year)){ days += 29; } else { days += 28; } } } days += day; Doesn't that seem more reasonable? The big if in the "month" loop might be clearer as a switch - or perhaps a lookup in an array. Be sure to check that 0≤month≤12 first - more error reporting! There's a subtle bug here: int a = (days-3)%7; The first couple of days in 1582 will result in a negative value there. That shows the value of testing "edge cases" - we really should have tried the very first day that must work. We can ensure a positive value by writing (days+4) % 7 instead. Or ever initialise days with value 4 (or better, with Thursday, corresponding to 1581-12-31) instead of 0, so we don't need this adjustment at the end.
{ "domain": "codereview.stackexchange", "id": 44009, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, datetime, homework", "url": null }
javascript, object-oriented, design-patterns, simulation Title: I made a webpage that simulates sharks eating fish in the torrid world of Wa-tor Question: I've been self-studying HTML/CSS/JS. I read about Wa-tor. It's a population dynamics simulation which simulates fish and sharks breeding and predating. This seemed cool so I decided to implement it. I don't know much about javascript, my background is mostly in python and R. Here's my implementation. Just hit Play. And here's the source code. Wa-tor var intervalId; var isPaused; function randomChoice(arr) { return arr[Math.floor(Math.random() * arr.length)]; } function tick(sea) { sea.tick(); sea.draw(); } function play() { var sea = new Sea(seaCanvas.width, seaCanvas.height); sea.generate(); sea.draw(); clearInterval(intervalId); intervalId = setInterval(tick, 1, sea); } Sea class Sea { constructor(width, height) { this.width = width; this.height = height; this.numFish = 0; this.numSharks = 0; this.chronon = 0; this.ctx = document.getElementById('seaCanvas').getContext('2d', { willReadFrequently: true }); this.array = new Array(); for (let j = 0; j < this.height; j++) { var row = new Array(); for (let i = 0; i < this.width; i++) { row.push(null); } this.array.push(row) } } getNorthCellCoords(x, y) { if (y !== 0) { return { x: x, y: y - 1 }; } else { return { x: x, y: this.height - 1 }; } } getWestCellCoords(x, y) { if (x !== 0) { return { x: x - 1, y: y }; } else { return { x: this.width - 1, y: y }; } }
{ "domain": "codereview.stackexchange", "id": 44010, "lm_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, object-oriented, design-patterns, simulation", "url": null }
javascript, object-oriented, design-patterns, simulation getSouthCellCoords(x, y) { if (y !== this.height - 1) { return { x: x, y: y + 1 }; } else { return { x: x, y: 0 }; } } getEastCellCoords(x, y) { if (x !== this.width - 1) { return { x: x + 1, y: y }; } else { return { x: 0, y: y } } } getCell(x, y) { return this.array[y][x]; } getAdjacentCoords(x, y) { var coords = new Array(); coords.push(this.getNorthCellCoords(x, y)); coords.push(this.getWestCellCoords(x,y)); coords.push(this.getSouthCellCoords(x,y)); coords.push(this.getEastCellCoords(x,y)); return coords; } getEmptyAdjacentCoords(x, y) { var coords = this.getAdjacentCoords(x, y); var empty = new Array(); for (let i = 0; i < coords.length; i++) { let testX = coords[i].x; let testY = coords[i].y; if (this.array[testY][testX] == null) { empty.push(coords[i]); } } return empty; } getAdjacentFishCoords(x, y) { var coords = this.getAdjacentCoords(x, y); var fish = new Array(); for (let i = 0; i < coords.length; i++) { let testX = coords[i].x; let testY = coords[i].y; if (this.array[testY][testX] != null) { if (this.array[testY][testX].species === 'fish') { fish.push(coords[i]); } } } return fish; }
{ "domain": "codereview.stackexchange", "id": 44010, "lm_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, object-oriented, design-patterns, simulation", "url": null }
javascript, object-oriented, design-patterns, simulation move(origin, destination) { this.array[origin.y][origin.x].x = destination.x; this.array[origin.y][origin.x].y = destination.y; this.array[destination.y][destination.x] = this.array[origin.y][origin.x]; this.array[origin.y][origin.x] = null; } addFish(origin, chronon) { this.numFish++; this.array[origin.y][origin.x] = new Fish(this, origin.x, origin.y, chronon); } addShark(origin, chronon) { this.numSharks++; this.array[origin.y][origin.x] = new Shark(this, origin.x, origin.y, chronon); } kill(coord) { if (this.array[coord.y][coord.x].species === 'fish') { this.numFish--; } else if (this.array[coord.y][coord.x].species === 'shark') { this.numSharks--; } this.array[coord.y][coord.x] = null; } generate() { let fishPct = document.getElementById('fishPct').value / 100; let sharkPct = document.getElementById('sharkPct').value / 100; for (let x = 0; x < this.width; x++) { for (let y = 0; y < this.height; y++) { let r = Math.random(); if (r < fishPct) { this.array[y][x] = new Fish(this, x, y, 0); this.numFish++; } else if (r < fishPct + sharkPct) { this.array[y][x] = new Shark(this, x, y, 0); this.numSharks++; } else { this.array[y][x] = null; } } } }
{ "domain": "codereview.stackexchange", "id": 44010, "lm_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, object-oriented, design-patterns, simulation", "url": null }
javascript, object-oriented, design-patterns, simulation draw() { const imageData = this.ctx.getImageData(0, 0, this.ctx.canvas.width, this.ctx.canvas.height); const data = imageData.data; for (let x = 0; x < this.width; x++) { for (let y = 0; y < this.height; y++) { let i = 4 * (y * this.width + x); if (this.array[y][x] == null) { // white water data[i] = 255; data[i + 1] = 255; data[i + 2] = 255; data[i + 3] = 255; } else if (this.array[y][x].species === 'fish') { // yellow fish data[i] = 255; data[i + 1] = 255; data[i + 2] = 0; data[i + 3] = 255; } else if (this.array[y][x].species === 'shark') { // red sharks data[i] = 255; data[i + 1] = 0; data[i + 2] = 0; data[i + 3] = 255; } } } this.ctx.putImageData(imageData, 0, 0); document.getElementById('chrononText').innerHTML = this.chronon; document.getElementById('fishText').innerHTML = this.numFish; document.getElementById('sharksText').innerHTML = this.numSharks; } tick() { this.chronon++; for (let x = 0; x < this.width; x++) { for (let y = 0; y < this.height; y++) { if (this.array[y][x] == null) { // do nothing } else { this.array[y][x].tick(this.chronon); } } } } } Animal class Animal { constructor(sea, x, y, chronon) { this.sea = sea; this.x = x; this.y = y; this.chronon = chronon; this.species = null; this.hasMoved = false; this.turnsToBreed = 0; this.turnsToStarve = 0; } }
{ "domain": "codereview.stackexchange", "id": 44010, "lm_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, object-oriented, design-patterns, simulation", "url": null }
javascript, object-oriented, design-patterns, simulation Fish class Fish extends Animal { constructor(sea, x, y, chronon) { super(sea, x, y, chronon); this.turnsToBreed = document.getElementById('fishBreedTurns').value; this.species = 'fish'; } tick(chronon) { if (chronon === this.chronon) { // already moved } else { // yet to move var empty = this.sea.getEmptyAdjacentCoords(this.x, this.y); if (empty.length === 0) { // no empty adjacent cells } else { // there is at least one empty adjacent cell available var origin = {x: this.x, y: this.y}; var destination = randomChoice(empty); if (this.turnsToBreed <= 0) { this.turnsToBreed = document.getElementById('fishBreedTurns').value; this.sea.move(origin, destination); this.sea.addFish(origin, this.chronon + 1); } else { this.sea.move(origin, destination); } } this.chronon++; this.turnsToBreed--; } } } Shark class Shark extends Animal { constructor(sea, x, y, chronon) { super(sea, x, y, chronon); this.turnsToBreed = document.getElementById('sharkBreedTurns').value; this.turnsToStarve = document.getElementById('sharkStarveTurns').value; this.species = 'shark'; }
{ "domain": "codereview.stackexchange", "id": 44010, "lm_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, object-oriented, design-patterns, simulation", "url": null }
javascript, object-oriented, design-patterns, simulation tick(chronon) { if (chronon === this.chronon) { // already moved } else { // yet to move var fish = this.sea.getAdjacentFishCoords(this.x, this.y); if (fish.length === 0) { // no adjacent fish var empty = this.sea.getEmptyAdjacentCoords(this.x, this.y); if (empty.length === 0) { // no empty adjacent cells } else { // there is at least one empty adjacent cell available var origin = {x: this.x, y: this.y}; var destination = randomChoice(empty); if (this.turnsToBreed <= 0) { this.turnsToBreed = document.getElementById('sharkBreedTurns').value; this.sea.move(origin, destination); this.sea.addShark(origin, this.chronon + 1); } else { this.sea.move(origin, destination); } } } else { // devourin' time! var origin = {x: this.x, y: this.y}; var destination = randomChoice(fish); this.turnsToStarve = document.getElementById('sharkStarveTurns').value; if (this.turnsToBreed <= 0) { this.turnsToBreed = document.getElementById('sharkBreedTurns').value + 1; this.sea.kill(destination); this.sea.move(origin, destination); this.sea.addShark(origin, this.chronon + 1); } else { this.sea.kill(destination); this.sea.move(origin, destination); } } this.chronon++; this.turnsToBreed--; this.turnsToStarve--; if (this.turnsToStarve === 0) { this.sea.kill({x: this.x, y: this.y}); } }
{ "domain": "codereview.stackexchange", "id": 44010, "lm_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, object-oriented, design-patterns, simulation", "url": null }
javascript, object-oriented, design-patterns, simulation this.sea.kill({x: this.x, y: this.y}); } } } }
{ "domain": "codereview.stackexchange", "id": 44010, "lm_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, object-oriented, design-patterns, simulation", "url": null }
javascript, object-oriented, design-patterns, simulation I had a lot of questions pop up while I was writing this. Some of them: Did I take the right approach by using the Canvas? I considered SVG but read that Canvas is better for many entities, especially if I did one-to-one pixels. Would the next step be GL for this kind of thing? Did I use JS's "class" system properly? I don't think I took full advantage of Fish and Shark inheriting from Animal. Did I organize my files properly? I feel like three .js files may be overkill. What does my code smell like? Did I miss out on any helpful design patterns? I don't have much experience doing this, so some guidance would be enormously helpful. Thank you. Answer: Pretty good! To answer your questions: Definitely, for pixel-sized entities, bitmap is imho perfect choice :) You could definitely design your code more polymorphic. tick method could be already in your Animal class and possibly taking care of some of the common stuff like checking for correct chronon value automatically. Imagine one method in animal, that does this check and if this check passes, it calls another method and that method actually does the job (and is implemented in your subclasses Shark and Fish). There could be more methods in Animal probably depending on your design. It seems weird to call sea.move(fish) (should sea move the fish? shouldn't fish move on it's own?). It's always good to split into more smaller pieces :) Although it's good practice to merge all your .js files into one big when in browser. webpack is one of common tools for that. Hah, smells fine! Take a look at "game loop", polymorphism, "Law of demeter". Some things to modify:
{ "domain": "codereview.stackexchange", "id": 44010, "lm_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, object-oriented, design-patterns, simulation", "url": null }
javascript, object-oriented, design-patterns, simulation Some things to modify: Is the check of chronon chronon === this.chronon really necessary? Does that really happen? I would expect the calling code makes sure it is always called only once per frame. This just increases nesting and doesn't look too good. In case you need this in your code, I would use negative condition with return to reduce nesting: if (chronon !== this.chronon) return I don't like referencing settings from your classes through html divs. Is it because you want the settings to be dynamic and it's possible to modify them while the game is running? Even so, I would prefer a wrapper that has access to those settings so that UI is not so tightly bound to your logic. Very often you have branching and then there's a lot of shared code in both pathways. That is unnecessary duplication, that you could leave outside. For example this: if (this.turnsToBreed <= 0) { this.turnsToBreed = document.getElementById('sharkBreedTurns').value + 1; this.sea.kill(destination); this.sea.move(origin, destination); this.sea.addShark(origin, this.chronon + 1); } else { this.sea.kill(destination); this.sea.move(origin, destination); } Can turn into this: this.sea.kill(destination); this.sea.move(origin, destination); if (this.turnsToBreed <= 0) { this.turnsToBreed = document.getElementById('sharkBreedTurns').value + 1; this.sea.addShark(origin, this.chronon + 1); } You never really check for correct calls. For example the code allows adding fish to a location where already is one. It removes the old fish, but increments the count. There may be hidden some small bugs in your code, because you don't really check for invalid states. Your tick methods are too big, extract them into smaller ones with more specific purpose - moving, breeding, devouring, etc.
{ "domain": "codereview.stackexchange", "id": 44010, "lm_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, object-oriented, design-patterns, simulation", "url": null }
c#, performance, algorithm, array Title: Calculate sum of largest sequence of decreasing odd ints Question: I wrote a method that finds the maximum sum of consecutive decreasing sequence of odd integers. For example: if sequence is 13 9 7 12 13 15 13, then sum is 29 (13 + 9 + 7). I don't think it's as good as it could be, because the same code is repeated multiple times. static int SumOfLargestSequence(int[] array) { int sumMax = 0; int sum = 0; for (int i = 0; i < array.Length; i++) { if (i == 0) { if (array[i] % 2 == 1) { sum += array[i]; if (sumMax < sum) { sumMax = sum; } } } else { if (array[i] % 2 == 0) { sum = 0; } else { if (sum != 0) { if (array[i - 1] > array[i]) { sum += array[i]; if (sumMax < sum) { sumMax = sum; } } } else { sum += array[i]; if (sumMax < sum) { sumMax = sum; } } } } } return sumMax; }
{ "domain": "codereview.stackexchange", "id": 44011, "lm_label": 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, algorithm, array", "url": null }
c#, performance, algorithm, array return sumMax; } Answer: I think the biggest problem with your code is that there are too many (unnecessary) branches inside the loop, which ruins the legibility of your code. First let me share with you my refactored version: static int SumOfLargestSequence(int[] array) { int sum = array[0] % 2 == 1 ? array[0] : 0; int sumMax = sum; for (int idx = 1; idx < array.Length; idx++) { if (array[idx] % 2 == 0) { sum = 0; continue; } if (sum == 0 || array[idx - 1] > array[idx]) { sum += array[idx]; sumMax = sumMax < sum ? sum : sumMax; } } return sumMax; } Now let's see the refactoring work step-by-step. The first element if (i == 0) { if (array[i] % 2 == 1) { sum += array[i]; if (sumMax < sum) { sumMax = sum; } } } Performing this branching in every iteration is pointless. Rather start the loop from 1 (for (int idx = 1; idx < array.Length; idx++)). And assign the initial values at variable declarations. int sum = array[0] % 2 == 1 ? array[0] : 0; int sumMax = sum; The even case if (array[i] % 2 == 0) { sum = 0; } else { ... } If number is even then reset the sum and move on. With the continue statement you don't need the else block. if (array[idx] % 2 == 0) { sum = 0; continue; } ... The descending order and the after reset cases if (sum != 0) { if (array[i - 1] > array[i]) { sum += array[i]; if (sumMax < sum) { sumMax = sum; } } } else { sum += array[i]; if (sumMax < sum) { sumMax = sum; } } You want to execute the exact same steps under two different circumstances. Combine your conditions to have a single branch. Also use ternary conditional operator to calculate the value of sumMax.
{ "domain": "codereview.stackexchange", "id": 44011, "lm_label": 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, algorithm, array", "url": null }
c#, performance, algorithm, array if (sum == 0 || array[idx - 1] > array[idx]) { sum += array[idx]; sumMax = sumMax < sum ? sum : sumMax; } As it was mentioned by others your requirements are a bit vague so try to spend some time to better understand the problem space and have requirements for suboptimal conditions as well.
{ "domain": "codereview.stackexchange", "id": 44011, "lm_label": 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, algorithm, array", "url": null }
c#, .net, async-await, extension-methods, task-parallel-library Title: Extension methods to modify an async Task's type from Task> to Task> Question: I've written a lot of (await SomeTask).AsList(); in my project, and it's kind of annoying to keep wrapping it. To fix this I've written a little extension method on Task<IEnumerable<T>> to be able to do this for me. The code is like this: /// <summary> /// Awaits the Task and returns the result as Task as List<T>. /// </summary> /// <typeparam name="T">The type of the list.</typeparam> /// <param name="task">The task to await.</param> /// <returns>A task which returns as List which can be awaited.</returns> public static async Task<List<T>> AsListAsync<T>(this Task<IEnumerable<T>> task) { var result = await task; return result.AsList(); } public static List<T> AsList<T>(this IEnumerable<T> enumerable) { if (enumerable is List<T> list) { return list; } return new List<T>(enumerable); } This enables me to write this: _someProperty = await SomeMethod().AsListAsync(); instead of: _someProperty = (await SomeMethod()).AsList(); However I am not sure if this will introduce any unintended behavior or deadlocking. Can someone point out flaws in this code (if any)? Answer: Just two points to mention you should add documentation to the second method as well, because it is a public method and you have documented the first method as well. you should add a null check for the method parameters because one can call this methods directly as well, passing null.
{ "domain": "codereview.stackexchange", "id": 44012, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await, extension-methods, task-parallel-library", "url": null }
javascript Title: Sort events by order-process stage, and modify the "entry" field Question: I have a map with the following data let res = new Map(); res.set('2022-10-31', 'nav'); res.set('2022-10-27', 'entry'); res.set('2022-10-27/duplicate/sending', 'sending'); res.set('2022-10-27/duplicate/cancellation', 'cancellation'); res.set('2022-10-27/duplicate/paymentToManager', 'paymentToManager'); And I need to sort it in this specific order given below and also I need to change the key value nav paymentToManager cancellation sending entry so after sorting the values should be like this let output = new Map(); output.set('2022-10-31', 'nav'); output.set('2022-10-27', 'paymentToManager'); output.set('2022-10-27/duplicate/cancellation', 'cancellation'); output.set('2022-10-27/duplicate/sending', 'sending'); output.set('2022-10-27/duplicate/entry', 'entry'); // <-- key & value changed So I coded in this way let order = new Map(); order.set('nav', 0); order.set('paymentToManager', 1); order.set('cancellation', 2); order.set('sending', 3) order.set('entry', 4) let res = new Map(); res.set('2022-10-31', 'nav'); res.set('2022-10-27', 'entry'); res.set('2022-10-27/duplicate/cancellation', 'cancellation'); res.set('2022-10-27/duplicate/sending', 'sending'); res.set('2022-10-27/duplicate/paymentToManager', 'paymentToManager'); let datesColorMap = new Map(); let pg = [...res.entries()] pg.map(x => { x[0] = x[0].indexOf('/')=== -1 ? x[0] : x[0].substring(0, x[0].indexOf('/')) return x; }) pg.sort((a,b) => { if(order.get(a[1]) < order.get(b[1])) return -1; else if(order.get(a[1]) > order.get(b[1])) return 1; else return 0; }) pg.map(x => { checkDuplicateAndSetMap(datesColorMap, x[0], x[1]); }) function checkDuplicateAndSetMap(datesColorMap, key, value) { if (datesColorMap.has(key) && datesColorMap.get(key) !== value) { key = key + `/duplicate/${value}`; } datesColorMap.set(key, value); } let final = [...datesColorMap.entries()];
{ "domain": "codereview.stackexchange", "id": 44013, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript let final = [...datesColorMap.entries()]; console.log(final) This gives the expected result. Just wondering whether it can be improved? Answer: Avoid relying on map ordering Yes, Maps are technically ordered, but it's generally an antipattern to rely on it. Key-value pair structures are designed for lookups, not iteration. The fact that you have to convert it to an array and back shows the awkwardness of trying to use the structure as an ordered collection. If you find you're needing to iterate the map more often than you're using it for lookups, or you're calling .entries(), .values() or .keys() excessively, consider using an array instead. Be wary of premature optimization. If your data is small, then making order a Map might be slower and more code to deal with than an Array#indexOf, which is plenty fast on an array of less than 10 elements. Furthermore, if you find you're needing to split and join the keys often, consider a different structure that has these pieces of information separate. For example: { "2022-10-31": ["nav"], "2022-10-27": ["entry", "cancellation", "sending", "paymentToManager"] } or even: { nav: "2022-10-31", entry: "2022-10-27", cancellation: "2022-10-27", sending: "2022-10-27", paymentToManager: "2022-10-27", }
{ "domain": "codereview.stackexchange", "id": 44013, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript But it's difficult to make a recommendation without use case context. Nonetheless, if the consumer of the final data structure is joining strings to build keys, something has gone wrong. Don't abuse Array#map for side effects This is a common mistake. Array#map's intent is to transform an array immutably, returning a new array. Array#map's callback contract is that it doesn't modify any state and simply computes a new value for that slot in the array. Your first map callback does return the value, but since the result of the mapping is discarded (incurring pointless allocation and garbage collection), that doesn't do anything. The mutation does the work. If you want to transform the structure in-place, use forEach. The idiomatic way to manipulate arrays in JS use functional-style chained transformations (filter/map/reduce) rather than imperative reassignments and mutations on separate lines. Sometimes, there's a loss of clarity in the compactness and it's useful to break things out a bit, but if the chained transformations are immutable, it's easier to verify correctness. Unless there's good reason to, make sure each map/reduce/filter call does one transformation/filtering/accumulation operation and pick the appropriate method. If you're building a Map from an array while checking that map for duplicates as you go, reduction seems more appropriate than mapping. Other issues
{ "domain": "codereview.stackexchange", "id": 44013, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript Always use const instead of let, unless you really have to reassign the variable, which doesn't apply here. Put logic into functions with clear responsibilities instead of letting it loose in the global scope. The one function that was added feels arbitrary. Why was that made into a function but nothing else? Ideally, functions have a single responsibilty (no "and" in the name or hidden behavior) and don't mutate state. But your function name is clear and all of its dependencies are parameters which is good. Maybe the function could compute the key and return it for the caller to mutate the map? I like to keep my "raw"/hardcoded data as close to JSON primitives as possible (this is usually how the data looks when deserialized). So instead of lots of verbose Map.put() calls for the raw data, I'd keep it as an array of pairs and plug it into the Map constructor. key = key + `/duplicate/${value}`; should be key += `/duplicate/${value}`;. The .sort callback is too complex. pg.sort((a, b) => order.get(a[1]) - order.get(b[1])); is all you need. Use clear variable names: what does pg mean? If you follow the chaining suggestion above, there are fewer variables to have to name. Less application state leads to a lighter cognitive load when reading the code. Use destructuring when it adds clarity, often true for pairs/tuples. ([path, status]) (or whatever these mean), ([key, value]) or even ([k, v]) are much clearer than (x) and x[0] and x[1]. Style: Use an autoformatter. Use consistent spacing. Always use brackets around blocks. Use space after if and for. Add a space after each comma in a single-line argument list. Suggested rewrite This could be sped up a bit by moving the key split into .reduce, at the cost of overburdening the reduce somewhat.
{ "domain": "codereview.stackexchange", "id": 44013, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript const createDateColoring = (input, ordering) => [...input.entries()] .map(([k, v]) => [k.split("/")[0], v]) .sort((a, b) => ordering.get(a[1]) - ordering.get(b[1])) .reduce((a, [k, v]) => { const newK = a.has(k) && a.get(k) !== v ? `${k}/duplicate/${v}` : k; a.set(newK, v); return a; }, new Map()); const input = new Map([ ["2022-10-31", "nav"], ["2022-10-27", "entry"], ["2022-10-27/duplicate/cancellation", "cancellation"], ["2022-10-27/duplicate/sending", "sending"], ["2022-10-27/duplicate/paymentToManager", "paymentToManager"], ]); const states = [ "nav", "paymentToManager", "cancellation", "sending", "entry", ]; const ordering = new Map(states.map((e, i) => [e, i])); console.log([...createDateColoring(input, ordering)]);
{ "domain": "codereview.stackexchange", "id": 44013, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
php, parsing, datetime, laravel Title: PHP Laravel Check if given date is a week or a regular day Question: I have a problem. In my project the user can copy a menu for a specific day or for a specific week. The value that will be sent to the back-end will be something like: 2022-10-07 or 2022-W43 Depending on the selection of the user. But now in the back-end I need to query those items using the given date, but I am not allowed to use the week input (2022-W43), because that is not a valid date. What is a clean way to write the query, because this is my code right now: public function scopeGetMenuItemsOnGivenDate(Builder $query, string $date): Builder { $start = Carbon::parse($date); $end = Carbon::parse($date); $extraCondition = $start->dayOfWeek; // Check if string is meant for a week if (str_contains($date, 'W')) { $date = Carbon::parse($date); $startDateCopy = $date->copy(); $start = $startDateCopy->startOfWeek(); $endDateCopy = $date->copy(); $end = $endDateCopy->endOfWeek(); $extraCondition = ''; } return $query ->whereDate('recurring_start', '<=', $end) ->whereDate('recurring_end', '>=', $start) ->where('recurring_days', 'like', '%' . $extraCondition . '%') ->OrwhereNull('recurring_end'); } First I set the default values to be a given date, but then I check the string if it contains a W, so I know a week has been provided or a regular day. This is not a nice way to check, I prefer if I could use a Carbon date, and check if the recurring_start and recurring_end is inside the given Carbon date. Can someone help me make this code clean and efficient, because I don't feel proud of this code :(
{ "domain": "codereview.stackexchange", "id": 44014, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, parsing, datetime, laravel", "url": null }
php, parsing, datetime, laravel Answer: Your function is trying to do two things at the same time, which is not aligned with the Single responsibility principle: it tries to make a query based on YYYY-MM-DD format or YYYY-WWW format. To make it simpler, we could extract each of those into two functions. Each of the function would get a date in a specific format (YYYY-MM-DD or YYYY-WWW) and return a structure with start date and end date for your database query. The structure can be a DTO (Object), array or even JSON string, up to you. This will bring the following benefits: smaller function, with one single responsibility each we can implement unit tests for your two new functions, which would make your code robust and reliable
{ "domain": "codereview.stackexchange", "id": 44014, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, parsing, datetime, laravel", "url": null }
beginner, rust, statistics Title: Calculating median value from a list of numbers Question: I am learning Rust and I would like to get some feedback around my solution to calculate the median value from a list of integers. I believe the logic is correct as my tests pass, but I'm concerned the right types and if I coded "the Rust way". use std::f32; fn main() { let mut v = Vec::new(); v.push(5); v.push(6); v.push(7); v.push(8); v.push(9); println!("{:?}", get_median(v)); // 7 v = Vec::new(); v.push(5); v.push(6); v.push(7); v.push(8); v.push(9); v.push(10); println!("{:?}", get_median(v)); // 7.5 v = Vec::new(); v.push(6); v.push(5); v.push(10); v.push(7); v.push(9); v.push(8); println!("{:?}", get_median(v)); // 7.5 v = Vec::new(); v.push(-2); v.push(-9); v.push(-4); v.push(-1); v.push(0); v.push(6); println!("{:?}", get_median(v)); // -1.5 } fn get_median(numbers: Vec<i32>) -> f32 { let mut v = numbers; v.sort(); let length = v.len() as f32; if length%2.0 == 1.0 { let index = length as usize / 2; v[index] as f32 } else { let index = length as usize / 2; let lower_mid: usize = index - 1; let higher_mid: usize = index; (v[lower_mid] + v[higher_mid]) as f32 / 2.0 } } Answer: Some basics You don't need to bring f32 into scope, it's in there by default. Use rustfmt on your code. Use a linter like clippy.
{ "domain": "codereview.stackexchange", "id": 44015, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, statistics", "url": null }
beginner, rust, statistics Use initializer functions You don't need to push your elements on a Vec one by one. Use Vec::from(). Or, even better, use the vec! macro. Use a cargo project Develop your project as a cargo crate. It will make the organization of tests and possible dependencies much easier. Use unit tests Use cargo's test suite to assert that your code is working. Useless conversions You convert Vec::len() from usize to f32 just to convert it back to usize again. Write generic code You can generalize your code by using generics and appropriate traits, so that it accepts other numeric iterables. Remember edge cases As pointed out by @G.Sliepen, you might also want to consider the case, where the vector is empty. Suggested: Cargo.toml: [package] name = "median" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dev-dependencies] once_cell = "*" src/lib.rs: use std::ops::Add; pub fn median<T>(items: &[T]) -> f64 where T: Add<Output = T> + Copy + Into<f64> + Ord, { let mut items: Vec<T> = items.to_vec(); if items.is_empty() { return 0.0; } items.sort(); let len = items.len(); if len % 2 == 0 { (items[len / 2] + items[len / 2 - 1]).into() / 2.0 } else { items[len / 2].into() } } tests/test.rs: use median::median; use once_cell::sync::Lazy; static MEDIANS: Lazy<[(f64, Vec<i32>); 5]> = Lazy::new(|| { [ (7.0, vec![5, 6, 7, 8, 9]), (7.5, vec![5, 6, 7, 8, 9, 10]), (7.5, vec![6, 5, 10, 7, 9, 8]), (-1.5, vec![-2, -9, -4, -1, 0, 6]), (0.0, vec![]), ] }); #[test] fn test_median() { for (nominal, numbers) in MEDIANS.iter() { assert_eq!(*nominal, median(numbers)); } }
{ "domain": "codereview.stackexchange", "id": 44015, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, statistics", "url": null }
python, performance, opencv Title: Polarimetric imaging script in python
{ "domain": "codereview.stackexchange", "id": 44016, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, opencv", "url": null }
python, performance, opencv Question: I made this script that takes 3 images taken with a polarising filter 45° apart as inputs and outputs an RGB preview and an image which encodes the polarization parameters as HSV. However it's way too slow, taking 155.8125 seconds to process it. What can I do to improve it? import cv2 import numpy as np import matplotlib.pyplot as plt from PIL import Image from IPython.display import Image import glob import math from pystackreg import StackReg def isolateblue(image): r,g,b=cv2.split(image) return b def rgb_preview(imagelist): return cv2.merge((imagelist[2],imagelist[1],imagelist[0])).astype('uint8') def hsv_processing(imagelist): i0 =imagelist[0]/1 i45 =imagelist[1]/1 i90 =imagelist[1]/1 stokesI = i0 + i90 stokesQ = i0 - i90 stokesU = (np.ones(stokesI.shape)*(2.0 * i45))- stokesI polint = np.sqrt(stokesQ*stokesQ+stokesU*stokesU) poldolp = polint/(stokesI+((np.ones(stokesI.shape)+0.001))) polaop = 0.5 * np.arctan(stokesU, stokesQ) h=(polaop+(np.ones(polaop.shape)*(np.pi/2.0)))/np.pi s=poldolp*200 s[s<0]=0 s[s>255]=255 v=polint hsvpolar=cv2.merge((h,s,v)) rgbimg = cv2.cvtColor(hsvpolar.astype('uint8'),cv2.COLOR_HSV2RGB)*2 rgbimg[rgbimg<0]=0 rgbimg[rgbimg>255]=255 return rgbimg if __name__ == '__main__': imagefiles=glob.glob(r"#whatever your filepath is") imagefiles.sort() images=[] for filename in imagefiles: img=cv2.imread(filename) img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) img=np.int16(img) images.append(img) polchannels=[] for image in images: polchannels.append(isolateblue(image)) num_images=len(polchannels) sr=StackReg(StackReg.AFFINE) polchannels=sr.register_transform_stack(np.stack((polchannels[0],polchannels[1],polchannels[2])), reference='first') cv2.imwrite("rgb preview.jpg",rgb_preview(polchannels)) cv2.imwrite("polarimetric image.jpg",hsv_processing(polchannels)) print("done")
{ "domain": "codereview.stackexchange", "id": 44016, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, opencv", "url": null }
python, performance, opencv Associated files (Google Drive): (high resolution) inputs outputs Answer: You need to care about correctness before performance, and (though it's difficult to say for sure because your numerical methods are undocumented), it's highly unlikely that the output is correct. But, from the top: You need blank lines in your source. No, seriously. Listen to a PEP8 linter. isolateblue does not need cv2 and can use a Numpy slice directly. Further to that, though: images should not be a list, and instead should be a single Numpy pre-allocated array that receives only the blue channels of each image loaded. int16 is not necessary here. StackReg is slow. But (unlike your previous test images), these images are well aligned enough that you might get away with not aligning them at all. If you need to preserve this step, the approach I already showed you in the previous question of using OpenCV's own homography algorithm is about four times as fast as StackReg, and drops one external dependency. Don't cast arrays to float by using /1. Use .astype(). i90 =imagelist[1] should certainly pull from the third channel [2] and not the second [1]. Stop calling np.ones when you should just broadcast. It was a habit in your previous question, it's a habit here, and you need to break it. You've managed to introduce a numerical error because of it: when you write np.ones(stokesI.shape)+0.001, that add should have been a multiply; but really the entire ones() call should go away. Don't s[s>255]=255; use np.clip(). cv2.merge is really just a np.stack(). Don't post-multiply cvtColor by 2. If you need brighter colours, multiply the value channel. Your hue calculation is probably incorrect. After you divide out pi, you need to multiply by 180, since OpenCV's HSV colour space has H ranging from 0 through 180. Suggested from typing import Iterable import cv2 import glob import numpy as np BLUE_CHANNEL = 0
{ "domain": "codereview.stackexchange", "id": 44016, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, opencv", "url": null }
python, performance, opencv import cv2 import glob import numpy as np BLUE_CHANNEL = 0 def warp_align(images: np.ndarray) -> None: print('SIFT detect and compute...') sift = cv2.SIFT_create() keys: list[tuple] = [] descriptors: list[np.ndarray] = [] for image in images: key, descriptor = sift.detectAndCompute(image, mask=None) keys.append(key) descriptors.append(descriptor) FLANN_INDEX_KDTREE = 1 flann = cv2.FlannBasedMatcher( indexParams={'algorithm': FLANN_INDEX_KDTREE, 'trees': 5}, searchParams={'checks': 50}, ) print('knn match...') LOWES_RATIO = 0.7 train_desc, *query_descs = descriptors matches = [ [ m for m, n in flann.knnMatch(query_desc, train_desc, k=2) if m.distance < LOWES_RATIO*n.distance ] for query_desc in query_descs ] def keys_to_points(matched_keys: Iterable[tuple[float, float]]) -> np.ndarray: return np.array(tuple(matched_keys), dtype=np.float32) print('Dewarping with homographies...') train_key, *query_keys = keys for query_key, target_matches, image in zip(query_keys, matches, images[1:]): query_points = keys_to_points(query_key[m.queryIdx].pt for m in target_matches) train_points = keys_to_points(train_key[m.trainIdx].pt for m in target_matches) M, mask = cv2.findHomography(query_points, train_points, method=cv2.RANSAC, ransacReprojThreshold=5) print(M) cv2.warpPerspective(src=image, dst=image, M=M, dsize=image.shape[::-1]) def rgb_preview(image: np.ndarray) -> np.ndarray: """Convert from (rgb), x, y to x, y, (bgr)""" return np.moveaxis(image, 0, -1)[..., ::-1] def hsv_processing(image: np.ndarray) -> np.ndarray: i00, i45, i90 = image i00 = i00.astype(float) stokesI = i00 + i90 stokesQ = i00 - i90 stokesU = 2*i45 - stokesI
{ "domain": "codereview.stackexchange", "id": 44016, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, opencv", "url": null }
python, performance, opencv stokesI = i00 + i90 stokesQ = i00 - i90 stokesU = 2*i45 - stokesI polint = np.sqrt(stokesQ*stokesQ + stokesU*stokesU) # In [0, inf] poldolp = polint/(stokesI + 1e-6) # In [-pi/2, pi/2] polaop = np.arctan(stokesU, stokesQ) h = (polaop/np.pi + 0.5)*180 s = np.clip(100*poldolp, a_min=0, a_max=255) v = np.clip(2*polint, a_min=0, a_max=255) hsvpolar = np.stack((h, s, v), axis=-1).astype('uint8') return cv2.cvtColor(hsvpolar, cv2.COLOR_HSV2RGB) def main() -> None: print('Loading images...') image_filenames = glob.glob('Test*degrees.jpg') image_filenames.sort() pol_channels = None for i, filename in enumerate(image_filenames): img = cv2.imread(filename) # BGR if pol_channels is None: pol_channels = np.empty((3, *img.shape[:2]), dtype=np.uint8) pol_channels[i, ...] = img[..., BLUE_CHANNEL] warp_align(pol_channels) print('Generating preview...') cv2.imwrite("rgb preview.jpg", rgb_preview(pol_channels)) print('Generating polarimetry...') cv2.imwrite("polarimetric image.jpg", hsv_processing(pol_channels)) print('Done.') if __name__ == '__main__': main() Output
{ "domain": "codereview.stackexchange", "id": 44016, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, opencv", "url": null }
javascript Title: Filtering array in JavaScript and outputting to DOM - repetition Question: Sample code below - it works, but feels clunky. clients is provided from a DB as a json_encoded array of objects (in the real app this is several hundred items.) Objective: filter the list based on user input, which can be a partial case-insensitive string of code or name. The user knows in advance what the id or name is - this is to quickly reduce the list to possible matches, to save them from scrolling through hundreds. document.addEventListener("DOMContentLoaded", function (event) { const clients = [{ id: 1, name: "Bob Marley", code: "BM1" }, { id: 2, name: "Elton John", code:"EJ1" }, { id: 3, name: "Beach Boys", code: "BB1" }, { id: 4, name: "Boyzone", code: "BO1" }]; const clientsList = document.getElementById("clientsList"); const search = document.getElementById("search"); // handle empty client array? if (clients.length === 0) { clientsList.innerHTML = '<li>No clients were found.</li>'; } else { // populate the list initially const listArray = clients.map((element) => '<li><a href="/clients/view/' + element.id + '">' + element.name + '</a></li>' ).join(""); clientsList.innerHTML = listArray; search.addEventListener("keyup", function (event) { clientsList.innerHTML = clients.filter((value) => value.name.toLowerCase().includes(event.target.value.toLowerCase()) || value.code.toLowerCase().includes(event.target.value.toLowerCase()) ).map((element) => '<li><a href="/clients/view/' + element.id + '">' + element.name + '</a></li>').join(""); }); } }); <input type="text" id="search" placeholder="Search..."> <ul id="clientsList"></ul> <!-- Sample input / output bo => bob marley, beach boys, boyzone on => elton john, boyzone bm1 => bob marley -->
{ "domain": "codereview.stackexchange", "id": 44017, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript I don't like that there is repetition in generating the li element and url - I thought about creating a function and then using that in the map? const generateListElement = (client_id, name) => `<li><a href="/clients/view/${client_id}">${name}</a></li>`; ...map((element) => generateListElement(element.id, element.name) but that doesn't look much better. good, bad, ugly? Answer: Remove the outer if else if (clients.length === 0) { clientsList.innerHTML = '<li>No clients were found.</li>'; return; } Decouple const clients Make a function. For now clients is hard coded, later rewritten to work with the JSON object. The function call will not change const clients = fetchWhateverThatDataIs(); function fetchWhateverThatDataIs() { return [{ id: 1, name: "Bob Marley", code: "BM1" }, { id: 2, name: "Elton John", code:"EJ1" }, { id: 3, name: "Beach Boys", code: "BB1" }, { id: 4, name: "Boyzone", code: "BO1" }]; } Objects organize functionality then simplify client code A Clients object will encapsulate filter and HtmlList. function Clients (theClients) { this.clients = theClients ? theClients : []; this.isEmpty = function() { return this.clients.length === 0; } this.HtmlList = function () { return this.clients.map((element) => '<li><a href="/clients/view/' + element.id + '">' + element.name + '</a></li>' ).join(""); } //HtmlList // intended as an event handler this.filter = function (event) { this.clients.filter((value) => value.name.toLowerCase().includes(event.target.value.toLowerCase()) || value.code.toLowerCase().includes(event.target.value.toLowerCase()) ).map((element) => '<li><a href="/clients/view/' + element.id + '">' + element.name + '</a></li>').join(""); } //filter } //Clients
{ "domain": "codereview.stackexchange", "id": 44017, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript } //Clients The <li> building is repeated. For now I'm inclined to follow my rule "repeated once, think about refactoring; repeated twice (or more), refactor." In any case make sure this initial refactoring works first. it works, but feels clunky Not any more. document.addEventListener("DOMContentLoaded", function (event) { const clients = new Clients(fetchWhateverThatDataIs()); const clientsList = document.getElementById("clientsList"); const search = document.getElementById("search"); if (clients.isEmpty()) { clientsList.innerHTML = '<li>No clients were found.</li>'; return; } clientsList.innerHTML = clients.HtmlList(); search.addEventListener("keyup", clients.filter); });
{ "domain": "codereview.stackexchange", "id": 44017, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
python Title: Automate the Boring Stuff Chapter 10 - Filling gaps in a sequence Question: The project outline: Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files to close this gap. My solution: import re from pathlib import Path def filename_change(marker, stem, extension, pattern_len): correct_number = str(marker).zfill(pattern_len) new_filename = f"{stem}{correct_number}.{extension}" return Path(new_filename) def check_gaps(basedir, prefix_pattern): sequence = [] marker = 0 pattern_len = len(prefix_pattern) filename_reg = re.compile(r"(.*)(\d{%s})\.(.*)" % pattern_len) for filename in basedir.glob("*"): match = filename_reg.search(str(filename)) if not match: continue sequence.append(filename) sequence.sort() for filename in sequence: match = filename_reg.search(str(filename)) stem = match.group(1) prefix = match.group(2) extension = match.group(3) marker = marker + 1 if int(prefix) != marker: new_filename = filename_change(marker, stem, extension, pattern_len) filename.rename(new_filename) def main(): while True: basedir = Path(input("Please enter a folder to search: ")) if not basedir.is_dir(): print("This path does not exist.") continue prefix_pattern = input("Enter a pattern to find. It must be zero padded (e.g. '001', '01', not '1'): ") check_gaps(basedir, prefix_pattern) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 44018, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python if __name__ == '__main__': main() I assumed that the order of the sequence was important and so opted to rename every file after the gap rather than filling the gaps with files from the end of the list. This seems fine for small sequences but I wondered if there was a more efficient way when dealing with hundreds of files. Answer: Forewords I do believe that you misunderstood the prefix part of the task and that your implementation treats the number or index of the files as the prefix and that you call the prefix stem in your code. It thus result in spam001.txt, spam101.txt and unrelated007.txt being renamed into spam001.txt, spam002.txt and unrelated003.txt. A prefix being something that comes before the information, I do believe that spam, in the example, is the prefix of the files we need to rename. And the prefix will act as a filter on which "series" of files the script needs to deal with. In your implementation, though, you mostly use the user provided information to know how to pad the resulting filename with zeroes. This is an interesting question as the task at hand does not explicit how it should be dealt with but I will talk about it latter. User input As you will learn to automate (boring) stuff, you’ll find out that an interactive script as you did that ask the user about further information it needs to proceed is quite tedious to automate or even test in quick succession. A better and more common approach is to provide options on the command-line and implement a parser within your script. Python provides the argparse module for such tasks. You can easily say that you want to provide a folder to your script and (optionally?) a prefix to filter the files within that folder. Iteration sequence = [] for … in …: … sequence.append(…) Is a code smell, you should be better off writing a list-comprehension: sequence = [filename for filename in basedir.glob('*') if filename_reg.search(str(filename))]
{ "domain": "codereview.stackexchange", "id": 44018, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python You can even use the capabilities of glob to incorporate the prefix in your search and simplify further the extraction of the index by using a simple slice instead of the re module: sequence = [filename for filename in basedir.glob(prefix + '*') if filename.stem[len(prefix):].isnumeric()] This makes sure that you match any spamXXX.txt while excluding both morespamYYY.txt and spammerZZZ.txt. You also use a construct like: marker = 0 for … in …: … marker = marker + 1 … Which is a convoluted way around enumerate. Path manipulations Using pathlib to manipulate filenames is a powerful tool that you don't leverage much. You apply the regex against the whole path instead of only the name or even the stem of the file, which leads to an expression more complex than it needs to be, and more difficult to handle. When renaming the path, you also recreate a whole Path from scratch instead of only changing the relevant part through means of with_name or with_stem. This adds up in terms of complexity for the reader of your code compared to, e.g.: new_name = f'{prefix}{expected_index:03}' filename.rename(filename.with_stem(new_name))
{ "domain": "codereview.stackexchange", "id": 44018, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Also note the :03 format specifier when turning the expected_index (marker in your code) into a string, this feels clearer than str(expected_index).zfill(3). And you can still parametrize it: new_name = f'{prefix}{expected_index:0{padding}}'. Padding Because filenames may or may not have their index padded with leading zeroes, I find it quite tricky to have a "one-size-fits-all" kind of approach. Using .isnumeric on the remaining characters of the filename after the prefix is a first step to detect indexes of any length, but this says nothing about whether or not the resulting filenames should be padded or not. We could compute the len of the digits at the end of the filename and use that as the padding of the resulting filename, but if they aren't padded at all, a filename with a two-digits index (say spam11.txt) being renamed to a one-digit index (spam08.txt) will keep an extra leading zero, which is unexpected. So I guess the best course of action here is to let the user tell whether or not the script need to guess for the padding to apply or just use no padding at all. Proposed improvements """ Check and fill gaps in a directory. Providing a prefix, scan a folder for files numbered after this prefix and remove gaps by re-numbering them if necessary. """ import argparse from pathlib import Path def check_and_fill_gaps(folder: Path, prefix: str = '', ignore_padding: bool = False) -> None: files = sorted( (int(index), path) for path in folder.glob(prefix + '*') if (index := path.stem[len(prefix):]).isnumeric() ) for expected_index, (index, path) in enumerate(files, start=1): if index != expected_index: padding = 0 if ignore_padding else len(path.stem) - len(prefix) path.rename(path.with_stem(f'{prefix}{expected_index:0{padding}}'))
{ "domain": "codereview.stackexchange", "id": 44018, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python def folder(value: str) -> Path: f = Path(value) if not f.is_dir(): raise argparse.ArgumentError(f'{value} is not an existing directory') return f def command_line_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('folder', type=folder, help='folder in which run the scan and replace process') parser.add_argument('-p', '--prefix', default='', help='search for files of the form `prefixXXX.ext` where XXX is any amount of digits') parser.add_argument('-n', '--ignore-padding', action='store_true', help='do not try to 0-pad resulting filenames when renaming') return parser if __name__ == '__main__': args = command_line_parser().parse_args() check_and_fill_gaps(**vars(args)) Note the use of the walrus operator to avoid extracting the index from path.stem twice. Example usage Using the following test folder: $ ls -1 testing morespam42.txt spam103.txt spam10.txt spam11.txt spam19.txt spam1.txt spam21.txt spam23.csv spam2.txt spam3.txt spam6.txt spam7.txt spammer007.xls We can filter with padding guessed: $ python fill_gaps.py -p spam testing; ls -1 testing morespam42.txt spam011.txt spam06.txt spam07.txt spam08.txt spam09.txt spam10.csv spam1.txt spam2.txt spam3.txt spam4.txt spam5.txt spammer007.xls Or without: $ python fill_gaps.py -p spam -n testing; ls -1 testing morespam42.txt spam10.csv spam11.txt spam1.txt spam2.txt spam3.txt spam4.txt spam5.txt spam6.txt spam7.txt spam8.txt spam9.txt spammer007.xls Handling adding a fixed padding to every filename is left as an exercise to the reader.
{ "domain": "codereview.stackexchange", "id": 44018, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
beginner, programming-challenge, rust, roman-numerals Title: Number to Roman in Rust Question: I solved LC12 (Integer to Roman) in Rust. I am a beginner with Rust, so I translated my previous solution from C++ to Rust. I am looking for feedback on how I could improve the following Rust code. The make_digit is nested because I got error saying it's not available in the current scope. I could find the following cases: thousands: just add M for how many thousands are in the number; non-thousand digit: 9: <Digit_1><Digit_10> (c1 and c10 in the code) 4: <Digit_1><Digit_5> 5 --> 8: <Digit_5><Digit_1 * digit % 5> 1 --> 3: <Digit_1 * digit>
{ "domain": "codereview.stackexchange", "id": 44019, "lm_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, programming-challenge, rust, roman-numerals", "url": null }
beginner, programming-challenge, rust, roman-numerals where Digit_1 is the lowest digit in the group (I, X, C) Digit_5: V, L, D Digit_10: X, C, M impl Solution { pub fn int_to_roman(num: i32) -> String { pub fn make_digit(digit: i32, c10: char, c5: char, c1: char) -> String { let mut res = "".to_string(); if (digit == 9){ res.push(c1); res.push(c10); } else if (digit >= 5){ res.push(c5); for ii in 0..(digit - 5) { res.push(c1); } } else if (digit == 4){ res.push(c1); res.push(c5); } else { for ii in 0..digit{ res.push(c1); } } return res; } // make_digit let mut ncopy = num; let thousands: i32 = num / 1000; let mut result: String = "".to_string(); for ii in 0..thousands { result.push('M'); } ncopy %= 1000; let mapping = std::collections::HashMap::from([ (1000, 'M'), (500, 'D'), (100, 'C'), (50, 'L'), (10, 'X'), (5, 'V'), (1, 'I'), ]); let mut modulo = 100; while modulo >= 1 { let digit = ncopy / modulo; // println!("Modulo: {modulo}"); result += &make_digit(digit, mapping[&(modulo * 10)], mapping[&(modulo * 5)], mapping[&modulo]); ncopy %= modulo; modulo /= 10; } return result; } }
{ "domain": "codereview.stackexchange", "id": 44019, "lm_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, programming-challenge, rust, roman-numerals", "url": null }
beginner, programming-challenge, rust, roman-numerals Answer: Right now, you use a combination of two techniques to solve the problem, when either would be simpler and more efficient by itself: a local helper function, and a lookup table. The local helper could be a tail-recursive function with two parameters, an accumulator and a residue. Here’s a simple but verbose implementation, which takes advantage of the fact that local variables in Rust use move semantics. I use .push() as you do, but the Rust String and str& types support the + and += operators, which also re-use the buffer if possible. pub fn int_to_roman(num: i32) -> String { fn helper( mut numerals : String, residue : i32 ) -> String { if residue >= 4000 { String::from("Too Large") } else if residue >= 1000 { numerals.push('M'); helper(numerals, residue - 1000) } else if residue >= 900 { numerals.push('C'); numerals.push('M'); helper(numerals, residue - 900) } else if residue >= 500 { numerals.push('D'); helper(numerals, residue - 500) } else if residue >= 400 { numerals.push('C'); numerals.push('D'); helper(numerals, residue - 400 ) } else if residue >= 100 { numerals.push('C'); helper(numerals, residue - 100 ) } else if residue >= 90 { numerals.push('X'); numerals.push('C'); helper(numerals, residue - 90) } else if residue >= 50 { numerals.push('L'); helper(numerals, residue - 50) } else if residue >= 40 { numerals.push('X'); numerals.push('L'); helper(numerals, residue - 40) } else if residue >= 10 { numerals.push('X'); helper(numerals, residue - 10) } else if residue >= 9 { numerals.push('I'); numerals.push('X'); helper(numerals, residue - 9)
{ "domain": "codereview.stackexchange", "id": 44019, "lm_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, programming-challenge, rust, roman-numerals", "url": null }
beginner, programming-challenge, rust, roman-numerals numerals.push('X'); helper(numerals, residue - 9) } else if residue >= 5 { numerals.push('V'); helper(numerals, residue - 5) } else if residue >= 4 { numerals.push('I'); numerals.push('V'); helper(numerals, residue - 4) } else if residue >= 1 { numerals.push('I'); helper(numerals, residue - 1) } else if residue == 0 { numerals } else { String::from("Too Small") } } return helper( String::from(""), num ) }
{ "domain": "codereview.stackexchange", "id": 44019, "lm_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, programming-challenge, rust, roman-numerals", "url": null }
beginner, programming-challenge, rust, roman-numerals To get an idea of the efficiency of this code, let’s examine the output of one of the else if blocks from Godbolt: else if residue >= 1000 { numerals.push('M'); helper(numerals, residue - 1000) } With -O, this compiles to: cmp edx, 999 jle .LBB7_2 mov rsi, qword ptr [rbx + 16] cmp rsi, qword ptr [rbx + 8] jne .LBB7_22 mov rdi, rbx call alloc::raw_vec::RawVec<T,A>::reserve_for_push mov rsi, qword ptr [rbx + 16] .LBB7_22: mov rax, qword ptr [rbx] mov byte ptr [rax + rsi], 77 add rsi, 1 mov qword ptr [rbx + 16], rsi mov rax, qword ptr [rbx + 16] mov qword ptr [rsp + 16], rax movups xmm0, xmmword ptr [rbx] movaps xmmword ptr [rsp], xmm0 add ebp, -1000 jmp .LBB7_43
{ "domain": "codereview.stackexchange", "id": 44019, "lm_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, programming-challenge, rust, roman-numerals", "url": null }
beginner, programming-challenge, rust, roman-numerals You will notice there is no modular arithmetic, only comparisons and subtractions. The first half of this checks the capacity of the String and enlarges if necessary. As you can see, the part that updates the string and calls helper tail-recursively is reasonably efficient (it misses an opportunity to optimize by updating numerals in place, but an alternative would be to declare numerals within the scope of int_to_roman and passing it between calls to helper by mutable reference), and takes advantage of Rust’s default move semantics for passing mut arguments to a function call. Thus, it uses both copy elision and tail-call elimination. (You could do the same in C++, but you would need to pass std::move(numerals). In Rust, this is the default for a mut parameter.) You could improve on the code above, but I’ll let you decide how. Here are a couple of ideas. If you store pairs like (1000,"M") in a dictionary, you can test each value in the dictionary, from highest to lowest, and append the representation of each value that matches to your numeral. If you remember your place in the dictionary, the code not only becomes more readable, but can avoid double-checking numerals it’s already eliminated. It is, however, possible to do better, with branchless code. You calculate the individual digits and make use of a hash map between values and numerals. You could instead look up each digit in an array, in constant time, and concatenate the results for all digits. pub fn int_to_roman(num: i32) -> String { let raw = num as usize; let thousands = raw % 10000 / 1000; let hundreds = raw % 1000 / 100; let tens = raw % 100 / 10; let ones = raw % 10; static THOUSANDS_ENCODING : [&str; 10] = ["", "M", "MM", "MMM", "?", "?", "?", "?", "?", "?"]; static HUNDREDS_ENCODING : [&str; 10] = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]; static TENS_ENCODING : [&str; 10] = ["", "X", "XX", "XXX", "XL","L", "LX", "LXX", "LXXX", "XC"];
{ "domain": "codereview.stackexchange", "id": 44019, "lm_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, programming-challenge, rust, roman-numerals", "url": null }
beginner, programming-challenge, rust, roman-numerals static ONES_ENCODING : [&str; 10] = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]; return THOUSANDS_ENCODING[thousands].to_string() + HUNDREDS_ENCODING[hundreds] + TENS_ENCODING[tens] + ONES_ENCODING[ones] } (I earlier gave a much worse implementation.) This version uses static, immutable lookup tables of string slices for efficiency: the compiler does not need to do any initialization of these at runtime. The first term of the string concatenation is converted .to_string(), to obtain a temporary String that can be appended to. This is then returned with copy elision. The function needs to do a type cast at the top, because array indices in Rust have type usize, and the language will not accept a signed subscript. This code is approximately equivalent to concatenating values from constexpr std::string_view[] tables in C++. There are faster solutions out there, which for example iterate over the reversed decimal digits of the input rather than doing modular arithmetic.
{ "domain": "codereview.stackexchange", "id": 44019, "lm_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, programming-challenge, rust, roman-numerals", "url": null }
rust, iterator Title: 2021 Day 1 Advent of Code in Rust Question: I'm preparing for the Advent of Code 2022, and in order to shake off the cobwebs, I'm attempting some problems from the previous year in rust. Starting at Day 1, I've been trying to get comfortable with iterator mechanics. The problem description for both parts is:
{ "domain": "codereview.stackexchange", "id": 44020, "lm_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, iterator", "url": null }
rust, iterator Suppose you had the following report: 199 200 208 210 200 207 240 269 260 263 This report indicates that, scanning outward from the submarine, the sonar sweep found depths of 199, 200, 208, 210, and so on. The first order of business is to figure out how quickly the depth increases, just so you know what you're dealing with - you never know if the keys will get carried into deeper water by an ocean current or a fish or something. To do this, count the number of times a depth measurement increases from the previous measurement. (There is no measurement before the first measurement.) In the example above, the changes are as follows: 199 (N/A - no previous measurement) 200 (increased) 208 (increased) 210 (increased) 200 (decreased) 207 (increased) 240 (increased) 269 (increased) 260 (decreased) 263 (increased) In this example, there are 7 measurements that are larger than the previous measurement. How many measurements are larger than the previous measurement? Part 2: Instead, consider sums of a three-measurement sliding window. Again considering the above example: 199 A 200 A B 208 A B C 210 B C D 200 E C D 207 E F D 240 E F G 269 F G H 260 G H 263 H Start by comparing the first and second three-measurement windows. The measurements in the first window are marked A (199, 200, 208); their sum is 199 + 200 + 208 = 607. The second window is marked B (200, 208, 210); its sum is 618. The sum of measurements in the second window is larger than the sum of the first, so this first comparison increased. Your goal now is to count the number of times the sum of measurements in this sliding window increases from the previous sum. So, compare A with B, then compare B with C, then C with D, and so on. Stop when there aren't enough measurements left to create a new three-measurement sum. In the above example, the sum of each three-measurement window is as follows: A: 607 (N/A - no previous sum) B: 618 (increased) C: 618 (no change)
{ "domain": "codereview.stackexchange", "id": 44020, "lm_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, iterator", "url": null }
rust, iterator follows: A: 607 (N/A - no previous sum) B: 618 (increased) C: 618 (no change) D: 617 (decreased) E: 647 (increased) F: 716 (increased) G: 769 (increased) H: 792 (increased) In this example, there are 5 sums that are larger than the previous sum. Consider sums of a three-measurement sliding window. How many sums are larger than the previous sum?
{ "domain": "codereview.stackexchange", "id": 44020, "lm_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, iterator", "url": null }
rust, iterator My solution for both parts: // main.rs use std::fs::File; use std::io::{Result, Read}; fn parse_to_int(body: String) -> Vec<i32> { // Parse the file once and collect into a vec body .split("\n") .map(|x| x.trim().parse::<i32>().unwrap()) .collect() } fn part_one(parsed: &Vec<i32>) -> i32 { // offset iterator to compare if parsed[i] < parsed[i+1] // sum all occurrences where this is true parsed .iter() .zip(parsed.iter().skip(1)) .map(|(a, b)| (b > a) as i32) .sum() } fn part_two(parsed: &Vec<i32>) -> i32 { // Need a sliding window of three elements wide let a = parsed .iter() .zip(parsed.iter().skip(1)) .zip(parsed.iter().skip(2)) .map(|((x, y), z)| x + y + z); // I tried doing let b = a.skip(1); // but the borrow checker wouldn't have it. // This works though let b = parsed .iter() .skip(1) .zip(parsed.iter().skip(2)) .zip(parsed.iter().skip(3)) .map(|((x, y), z)| x + y + z); a.zip(b) .map(|(x, y)| (y > x) as i32) .sum() } pub fn main() -> Result<()> { let mut fh = File::open("data/day1.txt")?; let mut body = String::new(); fh.read_to_string(&mut body)?; body = body.trim().to_string(); let values = parse_to_int(body); let total_1 = part_one(&values); println!("Part 1 solution: {:?}", total_1); let total_2 = part_two(&values); println!("Part 2 solution: {:?}", total_2); Ok(()) } #[cfg(test)] #[test] fn test_int_conversion() { // Make sure my integer converter works let test = String::from("199\n200\n208\n210\n200\n207"); let res = parse_to_int(test); assert_eq!( res, vec![199, 200, 208, 210, 200, 207] ); } #[cfg(test)] #[test] fn test_part_one() { let test = String::from( "199\n200\n208\n210\n200\n207\n240\n269\n260\n263" ); let res = parse_to_int(test);
{ "domain": "codereview.stackexchange", "id": 44020, "lm_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, iterator", "url": null }