text
stringlengths
1
2.12k
source
dict
java, programming-challenge break; case 1: top = 0; break; default: Arrays.fill(candidates[rank], offsets[rank], k, nonTopT); keep(rank+1, offsets[rank]); top = k_; } candidates[t_][k_t+rank] = candidates[rank][top]; } // orderK(candidates[t_], 0); // ?? } /** place top t of up to k values in candidates[t_][0:t] */ private void handleFew(final E[] many) { final int n = many.length; if (n == t) return; if (n < k) { if (1 < t) { // fill up k values to order Arrays.fill(candidates[0], n, k, many[0]); orderK(candidates[0], 0); } System.arraycopy(many, 0, candidates[0], k - n, n); } orderK(candidates[0], 0); for (int p = 0 ; p <= k/2 ; p++) { // t_ might be 0 E tmp = candidates[0][k-p]; candidates[0][k-p] = candidates[t_][p]; candidates[t_][p] = tmp; } }
{ "domain": "codereview.stackexchange", "id": 45340, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, programming-challenge", "url": null }
java, programming-challenge public static void main(String[] args) { TopByOrderK<String> topper = new TopByOrderK<>(3, 5, null); String many[] = { "for", "int", "offset", "n", "k", "order", "apply", "many", // "runnersUp", "top", "candidates", // "offsets", "trickle", "down", "x", "z" }; topper.topByOrderK(many); System.out.println(Arrays.asList(topper.candidates[topper.t_]) .subList(topper.k_t, topper.k)); System.out.println(topper.calls + " calls"); } } Answer: ... non-descendingly. */ I prefer "monotonic ascending", which is easily mentally shortened to just "ascending". Matter of taste. Humans tend to deal better with positive definitions than negative ones. dead stores in ctor t_ = top -1; ... k_ = k - 1; k_t = k - top; I don't get it. We compute these locals, and then never use them? Better to just elide them. int offsets[], t, t_, k, k_, k_t; Oh, wait. They are object attributes, so they aren't dead stores. But, we don't like using the this convention in the ctor, even when not syntactically necessary? Recommend you add this, for emphasis. I don't understand why the name kT isn't being used. It's not obvious to me that any of these are actually needed or helpful. But if we retain them, at least rename to kMinusT, kMinus1, tMinus1. It would be a kindness to the Gentle Reader to declare attributes in similar order to how ctor assigns them. verb vs. noun (or vs. adjective) Consider changing the signature to void keep(int numKept, numValid) { meaningful identifier int down = k_ - keep;
{ "domain": "codereview.stackexchange", "id": 45340, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, programming-challenge", "url": null }
java, programming-challenge meaningful identifier int down = k_ - keep; The meaning of the index down at this point is obscure. Add a // comment, or choose a more informative name. In general, I'm looking for a loop variant in the keep() routine. The promise was to "distribute" values. There's no assert at the end verifying that, and I wouldn't know what to test if I wanted to add such an assertion. Writing backwards if (0 < keep) expressions seems less helpful than letting me mentally pronounce if (keep > 0) as "if keep positive". Eliding { } curly braces on single-statement if's makes reading the code much harder. I am continually feeling like I'm trusting the author not to trick me with misleading indents. Better to just expose the nesting structure by writing the braces. class invariant We need offsets[keep] to be valid, but it's unclear when that was established. It's not a Class Invariant, since ctor didn't touch that array. Similarly for candidates[--keep]. We are only told // keep up to k values of each potential rank ... ... // ... and next free offset which is not enough. The repeated candidates[ci] = Arrays.copyOf(many, k) sheds little light on what the invariant might be. I think it was just used to allocate storage?!? I don't see a plan written down, that we will visit many in a certain order, and prune out losing entries following a certain pattern. int offset = 1; // used in wrap-up I still don't know the meaning of offset, and the code didn't explain it to me. fatal error case 0: // shouldn't happen?! break; Throw a fatal exception here, please. Then we will know it doesn't happen. constant that changes for (int rank = t, top = Integer.MIN_VALUE ; 0 <= --rank ; ) {
{ "domain": "codereview.stackexchange", "id": 45340, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, programming-challenge", "url": null }
java, programming-challenge Up in the ctor you told us that top is a synonym for t, and indeed we might mentally pronounce the latter as "top". But here we're using same identifier in a different scope to represent a different concept. Choose a new name for the new concept. comments lie! This is just wrong. /** place top t of up to k values in candidates[t_][0:t] */ private void handleFew(final E[] many) { final int n = many.length; if (n == t) return; The contract is pretty clear. We evaluate for side effects, and the routine shall place t values into candidates. It didn't. Now, maybe the higher level application doesn't need it to. Which suggests that the spec is wrong. Fix the code to conform to the spec, or fix the spec. It's unclear why {t == 1, t > 1} are distinct special cases. It's unclear why handleFew would need to make more than a single orderK() call, nor where its complexity is coming from. Up at the call site I thought it would be a nice trivial helper that makes an orderK() call and a copy. automated test suite This submission doesn't have one. System.out.println( Arrays.asList( ...' That's a nice print statement, sure. But it's not self evaluating. Crucially, it is a "big" test, we don't see any "small" unit tests of individual component routines. And those routines are on the complex and slightly long side. If I could see them being exercised by unit tests, I might have a greater understanding now of the corner cases they handle, and greater confidence that they compute the right thing. Near as I can tell, the global "found the top T entries!" assessment was done by manually eyeballing the output, rather than by having a component with access to global sort() verify that post-condition. Sometimes I eyeball things correctly. I like the belt-n-suspenders backup of having an automated check.
{ "domain": "codereview.stackexchange", "id": 45340, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, programming-challenge", "url": null }
c++, image, template, classes, variadic Title: Multi-dimensional Image Data Structure with Variadic Template Functions in C++ Question: This is a follow-up question for Three dimensional data structure in C++. I am trying to implement multi-dimensional image data structure with variadic template functions. For example, image.at(4, 3) is to access the element at location x = 4 and y = 3 in two dimensional case. In three dimensional case, image.at(4, 3, 2) is to access the element at location x = 4, y = 3 and z = 2. In this way, both constructing new image and accessing elements are easy. The experimental implementation Image Class Implementation // image.h namespace TinyDIP { template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): image_data(width * height) { size.reserve(2); size.emplace_back(width); size.emplace_back(height); } Image(const std::size_t width, const std::size_t height, const std::size_t depth): image_data(width * height * depth) { size.reserve(3); size.emplace_back(width); size.emplace_back(height); size.emplace_back(depth); } Image(const std::size_t x, const std::size_t y, const std::size_t z, const std::size_t w): image_data(x * y * z * w) { size.reserve(4); size.emplace_back(x); size.emplace_back(y); size.emplace_back(z); size.emplace_back(w); }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic Image(const std::size_t a, const std::size_t b, const std::size_t c, const std::size_t d, const std::size_t e): image_data(a * b * c * d * e) { size.reserve(5); size.emplace_back(a); size.emplace_back(b); size.emplace_back(c); size.emplace_back(d); size.emplace_back(e); } Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight) { size.reserve(2); size.emplace_back(newWidth); size.emplace_back(newHeight); if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = input; } Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight) { size.reserve(2); size.emplace_back(newWidth); size.emplace_back(newHeight); if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); // Reference: https://stackoverflow.com/a/51706522/6667035 } Image(const std::vector<std::vector<ElementT>>& input) { size.reserve(2); size.emplace_back(input[0].size()); size.emplace_back(input.size()); for (auto& rows : input) { image_data.insert(image_data.end(), std::ranges::begin(input), std::ranges::end(input)); // flatten } return; }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename... Args> constexpr ElementT& at(const Args... indexInput) { checkBoundary(indexInput...); constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } if constexpr (n == 2) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); return image_data[y * size[0] + x]; } else if constexpr (n == 3) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); auto z = get_from_variadic_template<3>(indexInput...); return image_data[(z * size[1] + y) * size[0] + x]; } else if constexpr (n == 4) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); auto z = get_from_variadic_template<3>(indexInput...); auto w = get_from_variadic_template<4>(indexInput...); return image_data[((w * size[2] + z) * size[1] + y) * size[0] + x]; } else if constexpr (n == 5) { auto a = get_from_variadic_template<1>(indexInput...); auto b = get_from_variadic_template<2>(indexInput...); auto c = get_from_variadic_template<3>(indexInput...); auto d = get_from_variadic_template<4>(indexInput...); auto e = get_from_variadic_template<5>(indexInput...); return image_data[(((e * size[3] + d) * size[2] + c) * size[1] + b) * size[0] + a]; } }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename... Args> constexpr ElementT const& at(const Args... indexInput) const { checkBoundary(indexInput...); constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } if constexpr (n == 2) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); return image_data[y * size[0] + x]; } else if constexpr (n == 3) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); auto z = get_from_variadic_template<3>(indexInput...); return image_data[(z * size[1] + y) * size[0] + x]; } else if constexpr (n == 4) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); auto z = get_from_variadic_template<3>(indexInput...); auto w = get_from_variadic_template<4>(indexInput...); return image_data[((w * size[2] + z) * size[1] + y) * size[0] + x]; } else if constexpr (n == 5) { auto a = get_from_variadic_template<1>(indexInput...); auto b = get_from_variadic_template<2>(indexInput...); auto c = get_from_variadic_template<3>(indexInput...); auto d = get_from_variadic_template<4>(indexInput...); auto e = get_from_variadic_template<5>(indexInput...); return image_data[(((e * size[3] + d) * size[2] + c) * size[1] + b) * size[0] + a]; } }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic constexpr std::size_t getDimensionality() const noexcept { return size.size(); } constexpr std::size_t getWidth() const noexcept { return size[0]; } constexpr std::size_t getHeight() const noexcept { return size[1]; } constexpr auto getSize() noexcept { return size; } std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data void print(std::string separator = "\t", std::ostream& os = std::cout) const { if(size.size() == 2) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; } else if (size.size() == 3) { for(std::size_t z = 0; z < size[2]; ++z) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y, z) << separator; } os << "\n"; } os << "\n"; } os << "\n"; } }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } void setAllValue(const ElementT input) { std::fill(image_data.begin(), image_data.end(), input); } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; rhs.print(separator, os); return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; } Image<ElementT>& operator-=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic Image<ElementT>& operator*=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::divides<>{}); return *this; } friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default; friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default; friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; } friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; } friend Image<ElementT> operator*(Image<ElementT> input1, ElementT input2) { return multiplies(input1, input2); } friend Image<ElementT> operator*(ElementT input1, Image<ElementT> input2) { return multiplies(input2, input1); } #ifdef USE_BOOST_SERIALIZATION
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic #ifdef USE_BOOST_SERIALIZATION void Save(std::string filename) { const std::string filename_with_extension = filename + ".dat"; // Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c std::ofstream ofs(filename_with_extension, std::ios::binary); boost::archive::binary_oarchive ArchiveOut(ofs); // write class instance to archive ArchiveOut << *this; // archive and stream closed when destructors are called ofs.close(); } #endif private: std::vector<std::size_t> size; std::vector<ElementT> image_data;
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename... Args> void checkBoundary(const Args... indexInput) const { constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } if constexpr (n == 2) { if (get_from_variadic_template<1>(indexInput...) >= size[0]) throw std::out_of_range("Given x out of range!"); if (get_from_variadic_template<2>(indexInput...) >= size[1]) throw std::out_of_range("Given y out of range!"); } if constexpr (n == 3) { if (get_from_variadic_template<1>(indexInput...) >= size[0]) throw std::out_of_range("Given x out of range!"); if (get_from_variadic_template<2>(indexInput...) >= size[1]) throw std::out_of_range("Given y out of range!"); if (get_from_variadic_template<3>(indexInput...) >= size[2]) throw std::out_of_range("Given z out of range!"); } if constexpr (n == 4) { if (get_from_variadic_template<1>(indexInput...) >= size[0]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<2>(indexInput...) >= size[1]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<3>(indexInput...) >= size[2]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<4>(indexInput...) >= size[3]) throw std::out_of_range("Index out of range!"); } if constexpr (n == 5) { if (get_from_variadic_template<1>(indexInput...) >= size[0]) throw std::out_of_range("Index out of range!");
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<2>(indexInput...) >= size[1]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<3>(indexInput...) >= size[2]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<4>(indexInput...) >= size[3]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<5>(indexInput...) >= size[4]) throw std::out_of_range("Index out of range!"); } } };
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename T, typename ElementT> concept is_Image = std::is_same_v<T, Image<ElementT>>; } Full Testing Code The full testing code: // Three dimensional data structure in C++ // Developed by Jimmy Hu #include <algorithm> #include <cassert> // for assert #include <chrono> // for std::chrono::system_clock::now #include <cmath> // for std::exp #include <concepts> #include <execution> // for std::is_execution_policy_v #include <iostream> // for std::cout #include <vector> struct RGB { std::uint8_t channels[3]; }; using GrayScale = std::uint8_t; namespace TinyDIP { // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1}; } template<std::size_t index = 1, typename Arg, typename... Args> constexpr static auto& get_from_variadic_template(const Arg& first, const Args&... inputs) { if constexpr (index > 1) return get_from_variadic_template<index - 1>(inputs...); else return first; } template<typename... Args> constexpr static auto& first_of(Args&... inputs) { return get_from_variadic_template<1>(inputs...); } template<std::size_t, typename, typename...> struct get_from_variadic_template_struct { }; template<typename T1, typename... Ts> struct get_from_variadic_template_struct<1, T1, Ts...> { using type = T1; }; template<std::size_t index, typename T1, typename... Ts> requires ( requires { typename get_from_variadic_template_struct<index - 1, Ts...>::type; }) struct get_from_variadic_template_struct<index, T1, Ts...> { using type = typename get_from_variadic_template_struct<index - 1, Ts...>::type; };
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<std::size_t index, typename... Ts> using get_from_variadic_template_t = typename get_from_variadic_template_struct<index, Ts...>::type; } // image.h namespace TinyDIP { template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): image_data(width * height) { size.reserve(2); size.emplace_back(width); size.emplace_back(height); } Image(const std::size_t width, const std::size_t height, const std::size_t depth): image_data(width * height * depth) { size.reserve(3); size.emplace_back(width); size.emplace_back(height); size.emplace_back(depth); } Image(const std::size_t x, const std::size_t y, const std::size_t z, const std::size_t w): image_data(x * y * z * w) { size.reserve(4); size.emplace_back(x); size.emplace_back(y); size.emplace_back(z); size.emplace_back(w); } Image(const std::size_t a, const std::size_t b, const std::size_t c, const std::size_t d, const std::size_t e): image_data(a * b * c * d * e) { size.reserve(5); size.emplace_back(a); size.emplace_back(b); size.emplace_back(c); size.emplace_back(d); size.emplace_back(e); }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight) { size.reserve(2); size.emplace_back(newWidth); size.emplace_back(newHeight); if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = input; } Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight) { size.reserve(2); size.emplace_back(newWidth); size.emplace_back(newHeight); if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); // Reference: https://stackoverflow.com/a/51706522/6667035 } Image(const std::vector<std::vector<ElementT>>& input) { size.reserve(2); size.emplace_back(input[0].size()); size.emplace_back(input.size()); for (auto& rows : input) { image_data.insert(image_data.end(), std::ranges::begin(input), std::ranges::end(input)); // flatten } return; }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename... Args> constexpr ElementT& at(const Args... indexInput) { checkBoundary(indexInput...); constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } if constexpr (n == 2) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); return image_data[y * size[0] + x]; } else if constexpr (n == 3) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); auto z = get_from_variadic_template<3>(indexInput...); return image_data[(z * size[1] + y) * size[0] + x]; } else if constexpr (n == 4) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); auto z = get_from_variadic_template<3>(indexInput...); auto w = get_from_variadic_template<4>(indexInput...); return image_data[((w * size[2] + z) * size[1] + y) * size[0] + x]; } else if constexpr (n == 5) { auto a = get_from_variadic_template<1>(indexInput...); auto b = get_from_variadic_template<2>(indexInput...); auto c = get_from_variadic_template<3>(indexInput...); auto d = get_from_variadic_template<4>(indexInput...); auto e = get_from_variadic_template<5>(indexInput...); return image_data[(((e * size[3] + d) * size[2] + c) * size[1] + b) * size[0] + a]; } }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename... Args> constexpr ElementT const& at(const Args... indexInput) const { checkBoundary(indexInput...); constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } if constexpr (n == 2) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); return image_data[y * size[0] + x]; } else if constexpr (n == 3) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); auto z = get_from_variadic_template<3>(indexInput...); return image_data[(z * size[1] + y) * size[0] + x]; } else if constexpr (n == 4) { auto x = get_from_variadic_template<1>(indexInput...); auto y = get_from_variadic_template<2>(indexInput...); auto z = get_from_variadic_template<3>(indexInput...); auto w = get_from_variadic_template<4>(indexInput...); return image_data[((w * size[2] + z) * size[1] + y) * size[0] + x]; } else if constexpr (n == 5) { auto a = get_from_variadic_template<1>(indexInput...); auto b = get_from_variadic_template<2>(indexInput...); auto c = get_from_variadic_template<3>(indexInput...); auto d = get_from_variadic_template<4>(indexInput...); auto e = get_from_variadic_template<5>(indexInput...); return image_data[(((e * size[3] + d) * size[2] + c) * size[1] + b) * size[0] + a]; } } constexpr std::size_t getDimensionality() const noexcept {
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic } constexpr std::size_t getDimensionality() const noexcept { return size.size(); }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic constexpr std::size_t getWidth() const noexcept { return size[0]; } constexpr std::size_t getHeight() const noexcept { return size[1]; } constexpr auto getSize() noexcept { return size; } std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data void print(std::string separator = "\t", std::ostream& os = std::cout) const { if(size.size() == 2) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; } else if (size.size() == 3) { for(std::size_t z = 0; z < size[2]; ++z) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y, z) << separator; } os << "\n"; } os << "\n"; } os << "\n"; } }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } void setAllValue(const ElementT input) { std::fill(image_data.begin(), image_data.end(), input); } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; rhs.print(separator, os); return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; } Image<ElementT>& operator-=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic Image<ElementT>& operator*=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::divides<>{}); return *this; } friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default; friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default; friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; } friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; } friend Image<ElementT> operator*(Image<ElementT> input1, ElementT input2) { return multiplies(input1, input2); } friend Image<ElementT> operator*(ElementT input1, Image<ElementT> input2) { return multiplies(input2, input1); } #ifdef USE_BOOST_SERIALIZATION
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic void Save(std::string filename) { const std::string filename_with_extension = filename + ".dat"; // Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c std::ofstream ofs(filename_with_extension, std::ios::binary); boost::archive::binary_oarchive ArchiveOut(ofs); // write class instance to archive ArchiveOut << *this; // archive and stream closed when destructors are called ofs.close(); } #endif private: std::vector<std::size_t> size; std::vector<ElementT> image_data;
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename... Args> void checkBoundary(const Args... indexInput) const { constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } if constexpr (n == 2) { if (get_from_variadic_template<1>(indexInput...) >= size[0]) throw std::out_of_range("Given x out of range!"); if (get_from_variadic_template<2>(indexInput...) >= size[1]) throw std::out_of_range("Given y out of range!"); } if constexpr (n == 3) { if (get_from_variadic_template<1>(indexInput...) >= size[0]) throw std::out_of_range("Given x out of range!"); if (get_from_variadic_template<2>(indexInput...) >= size[1]) throw std::out_of_range("Given y out of range!"); if (get_from_variadic_template<3>(indexInput...) >= size[2]) throw std::out_of_range("Given z out of range!"); } if constexpr (n == 4) { if (get_from_variadic_template<1>(indexInput...) >= size[0]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<2>(indexInput...) >= size[1]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<3>(indexInput...) >= size[2]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<4>(indexInput...) >= size[3]) throw std::out_of_range("Index out of range!"); } if constexpr (n == 5) { if (get_from_variadic_template<1>(indexInput...) >= size[0]) throw std::out_of_range("Index out of range!");
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<2>(indexInput...) >= size[1]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<3>(indexInput...) >= size[2]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<4>(indexInput...) >= size[3]) throw std::out_of_range("Index out of range!"); if (get_from_variadic_template<5>(indexInput...) >= size[4]) throw std::out_of_range("Index out of range!"); } } };
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename T, typename ElementT> concept is_Image = std::is_same_v<T, Image<ElementT>>; } namespace TinyDIP { template<typename ElementT> constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y) { return x.getWidth() == y.getWidth(); } template<typename ElementT> constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { return is_width_same(x, y) && is_width_same(y, z) && is_width_same(x, z); } template<typename ElementT> constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y) { return x.getHeight() == y.getHeight(); } template<typename ElementT> constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { return is_height_same(x, y) && is_height_same(y, z) && is_height_same(x, z); } template<typename ElementT> constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y) { return is_width_same(x, y) && is_height_same(x, y); } template<typename ElementT> constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { return is_size_same(x, y) && is_size_same(y, z) && is_size_same(x, z); } template<typename ElementT> constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y) { assert(is_width_same(x, y)); } template<typename ElementT> constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { assert(is_width_same(x, y, z)); } template<typename ElementT> constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y) { assert(is_height_same(x, y)); }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename ElementT> constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { assert(is_height_same(x, y, z)); } template<typename ElementT> constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y) { assert_width_same(x, y); assert_height_same(x, y); } template<typename ElementT> constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { assert_size_same(x, y); assert_size_same(y, z); assert_size_same(x, z); } template<typename ElementT> constexpr void check_width_same(const Image<ElementT>& x, const Image<ElementT>& y) { if (!is_width_same(x, y)) throw std::runtime_error("Width mismatched!"); } template<typename ElementT> constexpr void check_height_same(const Image<ElementT>& x, const Image<ElementT>& y) { if (!is_height_same(x, y)) throw std::runtime_error("Height mismatched!"); } template<typename ElementT> constexpr void check_size_same(const Image<ElementT>& x, const Image<ElementT>& y) { check_width_same(x, y); check_height_same(x, y); } } template<typename ElementT> void multidimensionalImageTest(const size_t size = 3) { std::cout << "Test with 2D image:\n"; auto image2d = TinyDIP::Image<ElementT>(size, size); image2d.setAllValue(1); image2d.at(1, 1) = 3; image2d.print(); std::cout << "Test with 3D image:\n"; auto image3d = TinyDIP::Image<double>(size, size, size); image3d.setAllValue(0); image3d.at(0, 0, 0) = 4; image3d.print(); return; }
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic int main() { auto start = std::chrono::system_clock::now(); multidimensionalImageTest<double>(); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; } The output of the test code above: Test with 2D image: 1 1 1 1 3 1 1 1 1 Test with 3D image: 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Computation finished at Sat Dec 30 11:10:29 2023 elapsed time: 0.00150394 Godbolt link is here. All suggestions are welcome. The summary information: Which question it is a follow-up to? Three dimensional data structure in C++ What changes has been made in the code since last question? I am trying to create multi-dimensional image data structure with variadic template functions in this post. Why a new review is being asked for? Despite the usage of Image class is easy and the feasible (dimensionality of an Image object can be changed in run-time), there are several if constexpr blocks to deal with various dimension case. Is there any better way to improve the implementation? Answer: Allow 1D images One-dimensional images are not that uncommon in computer graphics. There is no reason why your class couldn't be made to support them. Make the constructors generic Instead of having 4 different constructors that take different numbers of sizes, create a generic constructor: template<std::same_as<std::size_t>... Sizes> Image(Sizes... sizes): image_data((1 * ... * sizes)) { size.reserve(sizeof...(sizes)); (size.push_back(sizes), ...); } Although you can write this even more simply as: template<std::same_as<std::size_t>... Sizes> Image(Sizes... sizes): size{sizes...}, image_data((1 * ... * sizes)) {}
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic Now you can also see that you can make a generic one that takes a vector of elements of arbitrary dimensions as well. And if we want to be really generic, allow any range of elements: template<std::ranges::input_range Range, std::same_as<std::size_t>... Sizes> Image(const Range& input, Sizes... sizes): size{sizes...}, image_data(begin(input), end(input)) { if (image_data.size() != (1 * ... * sizes)) { throw std::runtime_error("Image data input and the given size are mismatched!"); } } Make everything work for more than 5 dimensions I can see why you stopped at 5 dimensions if you still have to manually write the code for each number of dimensions separately. Just spend a little bit of time to figure out how to write this in a generic way, then you'll actually have to do less typing and make the code work for any number of dimensions. Whenever you have to loop over a parameter pack, you can always do this: auto function = [&](auto index) { … }; (function(indexInput), …); Now function() will be called for every element in indexInput in succession. In that lambda you can do anything you want, including incrementing a loop counter. So use that to build up the index you need to read from image_data. This is left as an excercise for the reader. Consider making the number of dimensions a template argument With your current implementation, an object of type Image can have any number of dimensions, but it's not known at compile time. But you have added runtime checks to verify that you pass the right number of arguments to at() for example. Instead of doing this at runtime, it might be better to be able to do the checks at compile time, by making the number of dimensions part of the type: template<std::size_t Rank> class Image { … std::array<std::size_t, Rank> size; };
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic Then you can also use concepts to restrict the number of arguments allowed: template<std::same_as<std::size_t>... Sizes> requires (sizeof...(Sizes) == Rank) Image(Sizes... sizes): size{sizes...}, image_data((1 * ... * sizes)) {} And to avoid having to explicitly specify the number of dimensions when creating an Image<>, you can use a deduction guide: template<typename... Sizes> requires (sizeof...(Sizes) == Rank) Image(Sizes... sizes) -> Image<sizeof...(sizes)>; And of course do the same for the constructor that also takes a range of elements as input.
{ "domain": "codereview.stackexchange", "id": 45341, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++ Title: Checkup for a block of memory, containing a repeated single byte Question: I was looking at this question on SO, because I needed something similar. There are eight answers to it, and I wasn't satisfied with any of them - so I've written my own solution (please see below). It's in C++, so I decided not to add the ninth answer to the C-oriented question. The solution tries to use the multibyte comparison, which is presumably supported by hardware. I used to call the compare function with the unsigned long template parameter. The byte-to-byte comparison might be needed only in the end if and only if the length of the memory block is not divisible by the sizeof(T). template <typename T> inline auto repeatedByte(unsigned char const B) { T res = 0; memset(&res, B, sizeof(T)); return res; } template <typename T> auto compare(const void* const PTR, unsigned char const B, unsigned const N) { if (N > 0) { auto const value = repeatedByte<T>(B); auto const n0 = N / sizeof(T); auto i0 = 0U; auto ptr0 = reinterpret_cast<const T*>(PTR); while (i0 < n0 && *ptr0 == value) {++i0; ++ptr0;} if (i0 >= n0) { if (N % sizeof(T) > 0) { auto i1 = n0 * sizeof(T); auto ptr1 = reinterpret_cast<const unsigned char*>(ptr0); while (i1 < N && *ptr1 == B) {++i1; ++ptr1;} return (i1 >= N); } else { return true; } } else { return false; } } else { return false; } } UPDATE. I've implemented all the @GSliepen suggestions how to improve this code - especially about the data alignment, which looks most critical. All the updates can be found in this Github repository.
{ "domain": "codereview.stackexchange", "id": 45342, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ Answer: This doesn't account for alignment Consider that PTR might not be aligned correctly for a T. You have to account for this first, for example by comparing the first few bytes individually until PTR is suitably aligned. Depending on T and your CPU architecture, misaligned reads might either work fine, work but be much slower, crash your program, or worst of all: give you the wrong results. Remove unnecessary if-statements It's very unlikely anyone will call your function with N set to 0. The if-statement at the start is being evaluated every time the function calls, so wastes a few unnecessary cycles, and it makes the code look more complex. But your loops are already handling the case of N = 0 correctly, so I would just remove that outer if-statement entirely. You might do the same with if (N % sizeof(T) > 0), although there it's of course more likely to avoid the inner loop, but consider that the loop itself would exit immediately after the first check of i0 < N, so there is very little to no performance loss to run it even if N % sizeof(T) == 0. Finally, you can remove some unnecessary indentation by changing the order of the if and else branches, for example you can write: if (i0 < n0) { return false; } // no else … Use static_cast<>() where possible static_cast<>() is the safest way to cast things. Use it where possible. Casting any pointer type to and from void* is possible with static_cast<>(), so there is no need for reinterpret_cast<>().
{ "domain": "codereview.stackexchange", "id": 45342, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
python, programming-challenge, string-processing Title: Advent of Code 2023 - Day 9: Mirage Maintenance Question: Part 1: The task involves analyzing an environmental report from an oasis using the Oasis And Sand Instability Sensor (OASIS). The report consists of multiple histories, each containing a sequence of values over time. The goal is to predict the next value in each history by creating a sequence of differences at each step. This process is repeated until a sequence of zeroes is obtained, and the next values are extrapolated. The sum of these extrapolated values is the solution. For example: 0 3 6 9 12 15 1 3 6 10 15 21 10 13 16 21 30 45 In the above dataset, the first history is 0 3 6 9 12 15. Because the values increase by 3 each step, the first sequence of differences that you generate will be 3 3 3 3 3. Note that this sequence has one fewer value than the input sequence because at each step it considers two numbers from the input. Since these values aren't all zero, repeat the process: the values differ by 0 at each step, so the next sequence is 0 0 0 0. This means you have enough information to extrapolate the history! Visually, these sequences can be arranged like this: 0 3 6 9 12 15 3 3 3 3 3 0 0 0 0 To extrapolate, start by adding a new zero to the end of your list of zeroes; because the zeroes represent differences between the two values above them, this also means there is now a placeholder in every sequence above it: 0 3 6 9 12 15 B 3 3 3 3 3 A 0 0 0 0 0 You can then start filling in placeholders from the bottom up. A needs to be the result of increasing 3 (the value to its left) by 0 (the value below it); this means A must be 3: 0 3 6 9 12 15 B 3 3 3 3 3 3 0 0 0 0 0 Finally, you can fill in B, which needs to be the result of increasing 15 (the value to its left) by 3 (the value below it), or 18: 0 3 6 9 12 15 18 3 3 3 3 3 3 0 0 0 0 0
{ "domain": "codereview.stackexchange", "id": 45343, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing 0 3 6 9 12 15 18 3 3 3 3 3 3 0 0 0 0 0 So, the next value of the first history is 18. #!/usr/bin/env python3 from pathlib import Path from typing import Iterable import typer def find_next_val(line: str) -> int: # N1 N2 N3 N4 ... seqs = [list(map(int, line.split()))] while True: new = [-1 * (seqs[-1][i] - seqs[-1][i + 1]) for i in range(len(seqs[-1]) - 1)] seqs.append(new) if all(val == 0 for val in new): break last = 0 for seq in reversed(seqs[:-1]): seq.append(last := seq[-1] + last) return seqs[0][-1] def total_values(lines: Iterable[str]) -> int: return sum(map(find_next_val, lines)) def main(history_file: Path) -> None: with open(history_file) as f: print(total_values(f)) if __name__ == "__main__": typer.run(main) Part 2: In Part Two, the task extends to extrapolating values backward in time for each history. The process involves adding a zero to the beginning of the sequence of zeroes and filling in new first values for each previous sequence. The goal is to determine the previous values for each history and calculate their sum. In particular, here is what the third example history looks like when extrapolating back in time: 5 10 13 16 21 30 45 5 3 3 5 9 15 -2 0 2 4 6 2 2 2 2 0 0 0 Adding the new values on the left side of each sequence from bottom to top eventually reveals the new left-most history value: 5. Doing this for the remaining example data above results in previous values of -3 for the first history and 0 for the second history. Adding all three new values together produces 2. #!/usr/bin/env python3 from pathlib import Path from typing import Iterable import typer def find_next_val(line: str) -> int: # N1 N2 N3 N4 ... seqs = [list(map(int, line.split()))]
{ "domain": "codereview.stackexchange", "id": 45343, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing def find_next_val(line: str) -> int: # N1 N2 N3 N4 ... seqs = [list(map(int, line.split()))] while True: seqs.append( [-1 * (seqs[-1][i] - seqs[-1][i + 1]) for i in range(len(seqs[-1]) - 1)] ) if all(val == 0 for val in seqs[-1]): break last = 0 for seq in reversed(seqs[:-1]): seq.insert(0, last := seq[0] - last) return seqs[0][0] def total_values(lines: Iterable[str]) -> int: return sum(map(find_next_val, lines)) def main(history_file: Path) -> None: with open(history_file) as f: print(total_values(f)) if __name__ == "__main__": typer.run(main) Review Request: General coding comments, style, etc. What are some possible simplifications? What would you do differently? Answer: The first thing to observe is that the code produces the correct answers to Day 9. Well done! Describe What the Code Does Inside the Code Even if it's a one-line description such as "Solves part 1 of 2023 Advent of Code Day 9" with a link to the problem description as a comment but preferably as a docstring, you should be including a description in your code. Other comments that could help clarify what the code is doing would also be helpful. Efficiency Improvements You have in Part 1's function find_next_val the following: ... def find_next_val(line: str) -> int: ... while True: new = [-1 * (seqs[-1][i] - seqs[-1][i + 1]) for i in range(len(seqs[-1]) - 1)] I would recode the last line as: deltas = [seqs[-1][i + 1] - seqs[-1][i] for i in range(len(seqs[-1]) - 1)] This eliminates the multiplication by -1 and is, I believe, clearer. I would also suggest the name deltas is more descriptive as what is being calculated is the difference (delta) between successive elements. Later in this function you have: ... last = 0 for seq in reversed(seqs[:-1]): seq.append(last := seq[-1] + last) return seqs[0][-1]
{ "domain": "codereview.stackexchange", "id": 45343, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing But there is no need for this calculation to update the seq list. These statements can be simplified to: last = 0 for seq in reversed(seqs[:-1]): last += seq[-1] return last Refactor Your Code to Handle Both Parts The find_next_val implementations for Part 1 and Part 2 are practically identical except for the direction in which we are calculating history (forward or backwards). You could have a single find_next_val function that can handle both parts if you pass it an additional forward boolean argument that specifies the direction in which we are computing history: #!/usr/bin/env python3 from pathlib import Path from typing import Iterable from functools import partial import typer def find_next_val(line: str, forward: bool) -> int: # N1 N2 N3 N4 ... seqs = [list(map(int, line.split()))] while True: deltas = [seqs[-1][i + 1] - seqs[-1][i] for i in range(len(seqs[-1]) - 1)] seqs.append(deltas) if all(val == 0 for val in deltas): break n = 0 for seq in reversed(seqs[:-1]): n = seq[-1] + n if forward else seq[0] - n return n def total_values(lines: Iterable[str], forward: bool) -> int: return sum(map(partial(find_next_val, forward=forward), lines)) def main(history_file: Path) -> None: """Solves Part 1 and Part 2 of Day 9 Adevnt of Code. See: https://adventofcode.com/2023/day/9""" # We could read in the file only once with f.readlines() # to be used for both parts if we are sure that the lines are not modified, which # apppears to be the case: """ with open(history_file) as f: lines = f.readlines() print(total_values(lines, True)) print(total_values(lines, False) """ # But we will stick with processing the file twice: for forward in (True, False): with open(history_file) as f: print(total_values(f, forward)) if __name__ == "__main__": typer.run(main)
{ "domain": "codereview.stackexchange", "id": 45343, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, python-3.x Title: TUI Slot Simulator Question: Wrote a slot machine for a larger casino TUI project I'm creating. Would like some general feedback, along with some specific things: Coloring: Currently I have three loops that are almost identical, only differing in the index where they stop. Is there an easier way to do this? Separation: Did my best to separate specific tasks to their own functions, but I feel there is still some overlap. Flexibility: At the beginning I wrote this to fit any NxN slot interface, but ended up inserting some hardcoded values for a 5x3 machine, like most are. Would like some suggestions on how to tackle this issue, especially for calculating the pre-determined lines. import random from termcolor import colored class Player: def __init__(self, name: str, balance: float) -> None: self.name = name self.balance = balance class Slot:
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 Slot: def __init__(self, options: dict[str, list[float]], dim: tuple[int, int], player: Player) -> None: self.options = options self.w, self.h = dim self.player = player self.result = [[''] * self.w] * self.h self.total_winnings = 0.0 self.rawlines = [ [0, 0, 0, 0, 0], # 1 [1, 1, 1, 1, 1], # 2 [2, 2, 2, 2, 2], # 3 [0, 1, 2, 1, 0], # 4 [2, 1, 0, 1, 2], # 5 [1, 2, 1, 0, 1], # 6 [1, 2, 1, 2, 1], # 7 [0, 1, 0, 1, 2], # 8 [2, 1, 2, 1, 0], # 9 [2, 1, 0, 1, 0], # 10 [0, 1, 2, 1, 2], # 11 [1, 0, 1, 2, 1], # 12 [2, 1, 2, 1, 2], # 13 [1, 0, 1, 0, 1], # 14 [0, 1, 0, 1, 0], # 15 [1, 1, 2, 1, 1], # 16 [0, 0, 1, 0, 0], # 17 [2, 2, 1, 2, 2], # 18 [1, 1, 0, 1, 1], # 19 [0, 0, 2, 0, 0], # 20 [2, 2, 0, 2, 2], # 21 [1, 1, 1, 2, 1], # 22 [0, 0, 0, 1, 2], # 23 [2, 2, 2, 1, 0], # 24 [2, 1, 1, 1, 0] # 25 ] def spin(self, bet: float): self.bet = bet if self.player.balance - bet < 0.0: quit("Insufficient Funds.") for i in range(self.h): self.result[i] = random.choices(list(self.options.keys()), k=self.w) self.__calculate_lines() self.player.balance = self.player.balance + (self.__check_wins() - bet) def __calculate_lines(self) -> None: # https://chiphungry.com/mad-mouse-the-zappening/ self.lines = [[self.result[val][idx] for idx, val in enumerate(line)] for line in self.rawlines]
{ "domain": "codereview.stackexchange", "id": 45344, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x def __check_lines(self) -> float: win = 0.0 for idx, line in enumerate(self.lines): front = line[0] raw_line = self.rawlines[idx] if len(set(line)) == 1: # all win += self.bet * self.options[front][0] for idx, val in enumerate(raw_line): self.result[val][idx] = colored(self.result[val][idx], "green") elif len(set(line[:-1])) == 1: # all but one win += self.bet * self.options[front][1] for idx, val in enumerate(raw_line[:-1]): self.result[val][idx] = colored(self.result[val][idx], "green") elif len(set(line[:-2])) == 1: # all but two win += self.bet * self.options[front][2] for idx, val in enumerate(raw_line[:-2]): self.result[val][idx] = colored(self.result[val][idx], "green") return win def __check_wins(self): self.win = 0.0 self.win += self.__check_lines() self.total_winnings += self.win return self.win def display(self, verbose=False): length = ("|---" * self.w) + "|" z = ''.join(''.join(f"| {a} " for a in r) + '|\n' for r in self.result) print(f"{length}\n{z.strip()}\n{length}") print(f"Balance: ${self.player.balance:0.2f} | Bet: ${self.bet:0.2f} | Win: ${self.win:0.2f}") if verbose: print(f"Total Winnings: ${self.total_winnings:0.2f}") def main(): player = Player("Ben", 50.00) options = { 'A': [3, 0.8, 0.3], 'K': [2.5, 0.6, 0.24], 'Q': [2, 0.5, 0.2], '9': [1.5, 0.4, 0.16], '8': [1.2, 0.3, 0.14], '7': [1, 0.2, 0.1] } slot = Slot(options, (5, 3), player) while True: slot.spin(1.00) slot.display(verbose=True) input() if __name__ == '__main__': main() Answer: Questions
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 if __name__ == '__main__': main() Answer: Questions Currently I have three loops that are almost identical, only differing in the index where they stop. Is there an easier way to do this? Extract the stop-index as a variable, and then issue a single call to colored. Did my best to separate specific tasks to their own functions, but I feel there is still some overlap. This still needs a lot of work. For example, in your __check_lines you're both calculating a winnings sum and reformatting your results matrix. At the beginning I wrote this to fit any NxN slot interface, but ended up inserting some hardcoded values for a 5x3 machine, like most are. Would like some suggestions on how to tackle this issue, especially for calculating the pre-determined lines.
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 Don't accept width and height. Your rawlines (which I call win_database and your reference calls win lines) should imply the dimensions. The good You've written some type hints (you could use more). You've managed to avoid globals. You have a properly-written main function and __main__ guard. You've used a terminal colour library in a seemingly sensible way. Points to work on dim does not benefit from being a tuple; just accept two arguments. Missing a bunch of hints, such as spin() -> None. rawlines should be an immutable tuple of tuples, and should be a class ("static") variable rather than an instance variable. The code is kind of a swamp of inappropriate mutation and state retention. self.result shouldn't be present on Slot at all. Either pass it around in parameters and return values, or (as I'll demonstrate) split out a second Spin class. The simple path to immutability is NamedTuple. Don't quit. Raise a domain-specific exception. Don't for i in range(self.h); loop like a native - the safe choice here is a generator function. Don't double-underscore. That's reserved for name mangling; use a single underscore for private-like members. Reduce self.player.balance = self.player.balance + by using +=. length is not a length; it's some kind of divider string - we can think of a better variable name. ${self.player.balance:0.2f} could instead leverage Python's built-in locale currency formatting support. Since random behaviour is crucial for this application, you should either pass in an instance of Random, or at least pass in an optional random seed for testability. w and h should just be spelled in full. More importantly - accepting those parameters gives the caller the illusion that they can influence the width and height, but they can't! Those are hard-coded in rawlines. It would be a good idea to write a fallback for terminals that don't support colour; something like if termcolor.termcolor._can_do_colour():
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 if termcolor.termcolor._can_do_colour(): yield termcolor.colored(text=f' {symbol} ', color='green') else: yield f'[{symbol}]'
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 Suggested Demonstrating some of the above with less mutation, a little bit more OOP, etc.: this behaves identically to your old code. It took a lot of effort to figure out how the old code worked, and I suspect that there's still a bunch of simplification to the win-condition algorithm that can be done. """ Simulation imitating the slot machine described in https://chiphungry.com/mad-mouse-the-zappening/ """ import dataclasses import functools import locale import random from enum import Enum from typing import Iterator, Iterable, NamedTuple import termcolor class InsufficientFundsError(ValueError): """ Thrown if the user attempts to spin but doesn't have enough balance to submit the bet. """ @dataclasses.dataclass(slots=True) class Player: name: str balance: float def pay(self, bet: float) -> None: new_balance = self.balance - bet if new_balance < 0: raise InsufficientFundsError() self.balance = new_balance def win(self, winnings: float) -> None: self.balance += winnings # A vertical index into the result matrix VIndex = int # A single "card" symbol, like Q Symbol = str # One row in the win condition database IndexRow = tuple[VIndex, ...] # One row in the result matrix SymbolRow = tuple[Symbol, ...] # One win-product row, with a coefficient for each WinClass entry CoefRow = tuple[float, float, float, float] # The matrix of symbols to display to the user ResultMatrix = tuple[SymbolRow, ...] class WinClass(Enum): """ All of the possible alternatives for win condition, in decreasing order of rarity. """ ALL = 0 ALL_BUT_1 = 1 ALL_BUT_2 = 2 NONE = 3 class WinCandidate(NamedTuple): """ One win-candidate row, with symbols from a spin mapped onto the win condition database. These win candidates are not displayed to the user directly. They're used to calculate win class (in turn calculating the addends for winnings money). """
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 symbols: SymbolRow win_class: WinClass @classmethod def map(cls, symbols: Iterable[Symbol]) -> 'WinCandidate': """ From a mapped symbol row, create a WinCandidate instance. """ symbols = tuple(symbols) # Business logic used to determine the win-class for this candidate. # This is somewhat of a performance bottleneck. all_len = len(set(symbols)) if all_len > len(symbols) - 2: win_class = WinClass.NONE # Fast path for very few matches elif all_len == 1: win_class = WinClass.ALL elif len(set(symbols[:-1])) == 1: win_class = WinClass.ALL_BUT_1 elif len(set(symbols[:-2])) == 1: win_class = WinClass.ALL_BUT_2 else: win_class = WinClass.NONE return cls(symbols=symbols, win_class=win_class) @property def front(self) -> Symbol: return self.symbols[0] def __str__(self) -> str: return ''.join(self.symbols) class Spin: """ A single spin of the slot machine. """ # Python class slots, not slot-machine slots __slots__ = 'result', 'bet', 'candidates', 'winnings', 'win_database' def __init__( self, win_coefs_by_symbol: dict[Symbol, CoefRow], win_database: tuple[IndexRow, ...], result: ResultMatrix, bet: float, ) -> None: self.win_database = win_database self.result = result self.bet = bet self.candidates = tuple(self._get_candidates()) self.winnings = sum(self._get_winnings(win_coefs_by_symbol))
{ "domain": "codereview.stackexchange", "id": 45344, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x def _get_winnings( self, win_coefs_by_symbol: dict[Symbol, CoefRow], ) -> Iterator[float]: """ An iterator of winning money. Call sum() on this to get the total winnings for this spin. """ for candidate in self.candidates: coef = win_coefs_by_symbol[candidate.front][candidate.win_class.value] yield self.bet * coef def _get_candidates(self) -> Iterator[WinCandidate]: """ An iterator of win candidate tuples, made by mapping the spin result symbols onto the win condition database. In the demo configuration, the iterator is 25 elements long and yields tuples of 5 symbols each. """ for win_indices in self.win_database: yield WinCandidate.map([ self.result[y][x] for x, y in enumerate(win_indices) ]) @property def width(self) -> int: return len(self.result[0]) def _format_row(self, y: int, result_row: SymbolRow) -> Iterator[str]: for x, symbol in enumerate(result_row): for candidate, win_condition in zip(self.candidates, self.win_database): if y != win_condition[x]: continue win_class = candidate.win_class if win_class != WinClass.NONE: n_excluded = win_class.value if x < len(result_row) - n_excluded: if termcolor.termcolor._can_do_colour(): yield termcolor.colored(text=f' {symbol} ', color='green') else: yield f'[{symbol}]' break else: yield f'{symbol:^3}'
{ "domain": "codereview.stackexchange", "id": 45344, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x def format_lines(self, player: Player) -> Iterator[str]: sep = '|---'*self.width + '|' yield sep for y, result_row in enumerate(self.result): middle = '|'.join(self._format_row(y=y, result_row=result_row)) yield f'|{middle}|' yield sep yield f'Balance: {locale.currency(player.balance)} | {self}' def __str__(self) -> str: return ( f'Bet: {locale.currency(self.bet)}' f' | Win: {locale.currency(self.winnings)}' ) class SlotMachine: # Python class slots, not slot-machine slots __slots__ = ( 'win_coefs_by_symbol', 'win_database', 'width', 'height', 'symbols', 'total_winnings', 'rand', ) def __init__( self, win_coefs_by_symbol: dict[Symbol, CoefRow], win_database: tuple[IndexRow, ...], rand: random.Random | None = None, ) -> None: self.win_coefs_by_symbol = win_coefs_by_symbol self.win_database = win_database self.symbols = tuple(win_coefs_by_symbol.keys()) self.total_winnings = 0. # The only thing that mutates in this class. self.width = len(win_database[0]) self.height = 1 + max( idx for row in win_database for idx in row ) if rand is None: self.rand = random.Random() else: self.rand = rand def _spin_rows(self) -> Iterator[SymbolRow]: """ An iterator of output matrix rows, randomly chosen from the display symbols. """ for _ in range(self.height): yield tuple(self.rand.choices( population=self.symbols, k=self.width, )) def spin(self, player: Player, bet: float) -> Spin: # Will throw if insufficient balance player.pay(bet)
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 spin = Spin( win_coefs_by_symbol=self.win_coefs_by_symbol, win_database=self.win_database, result=tuple(self._spin_rows()), bet=bet, ) self.total_winnings += spin.winnings player.win(spin.winnings) return spin def __str__(self) -> str: return f'Total Winnings: {locale.currency(self.total_winnings)}' def main(balance: float = 50.00, visible: bool = True, pause: bool = False) -> None: # Set to the user's locale, for currency formatting locale.setlocale(category=locale.LC_ALL, locale='') player = Player(name='Ben', balance=balance) win_database = ( (0, 0, 0, 0, 0), (1, 1, 1, 1, 1), (2, 2, 2, 2, 2), (0, 1, 2, 1, 0), (2, 1, 0, 1, 2), (1, 2, 1, 0, 1), (1, 2, 1, 2, 1), (0, 1, 0, 1, 2), (2, 1, 2, 1, 0), (2, 1, 0, 1, 0), (0, 1, 2, 1, 2), (1, 0, 1, 2, 1), (2, 1, 2, 1, 2), (1, 0, 1, 0, 1), (0, 1, 0, 1, 0), (1, 1, 2, 1, 1), (0, 0, 1, 0, 0), (2, 2, 1, 2, 2), (1, 1, 0, 1, 1), (0, 0, 2, 0, 0), (2, 2, 0, 2, 2), (1, 1, 1, 2, 1), (0, 0, 0, 1, 2), (2, 2, 2, 1, 0), (2, 1, 1, 1, 0), ) win_coefs_by_symbol = { 'A': (3.0, 0.8, 0.30, 0), 'K': (2.5, 0.6, 0.24, 0), 'Q': (2.0, 0.5, 0.20, 0), '9': (1.5, 0.4, 0.16, 0), '8': (1.2, 0.3, 0.14, 0), '7': (1.0, 0.2, 0.10, 0), } machine = SlotMachine( win_coefs_by_symbol, win_database, rand=random.Random(0), )
{ "domain": "codereview.stackexchange", "id": 45344, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x while True: try: spin = machine.spin(player=player, bet=1.00) except InsufficientFundsError: if visible: print('Insufficient funds') break output = '\n'.join(spin.format_lines(player=player)) if visible: print(output) print(machine) if pause: input('Press enter to continue.') if visible: print() def profile() -> None: import cProfile cProfile.run('main(balance=10_000, visible=False)', sort='tottime') if __name__ == '__main__': try: main() # profile() except KeyboardInterrupt: pass Output For the purposes of Code Review formatting, this output is shown with the non-colourised fallbacks. |---|---|---|---|---| | 7 | 8 | Q | K | 9 | | Q | 8 | K | Q | 9 | | 7 | 9 | K | 8 | 9 | |---|---|---|---|---| Balance: $49.00 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.00 |---|---|---|---|---| | K | 7 | 7 | 8 | 7 | | K | 8 | 7 | 8 | Q | | A | Q | 9 | 7 | 7 | |---|---|---|---|---| Balance: $48.00 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.00 |---|---|---|---|---| | Q | 7 | K | 8 | 9 | | A | 8 | Q | 8 | 8 | | A | Q | 7 | K | K | |---|---|---|---|---| Balance: $47.00 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.00 |---|---|---|---|---| | 7 | K | 9 | K | 7 | | 8 | Q | A | K | 9 | | 7 | A | 9 | 8 | 9 | |---|---|---|---|---| Balance: $46.00 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.00 |---|---|---|---|---| | 8 | 9 | 7 | 9 | 9 | | Q | 9 | Q | 9 | K | | K | K | 9 | 9 | Q | |---|---|---|---|---| Balance: $45.00 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.00 |---|---|---|---|---| | A | 8 |[7]| 7 | 7 | |[7]|[7]| 9 | Q | 8 | | K | 8 |[7]| 7 | 9 | |---|---|---|---|---| Balance: $44.20 | Bet: $1.00 | Win: $0.20 Total Winnings: $0.20
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 |---|---|---|---|---| | 7 | 9 | Q | 9 | 7 | | 7 | 8 | A | 9 | Q | | 9 | 7 | K | 8 | A | |---|---|---|---|---| Balance: $43.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | K | 8 | K | 8 | A | | A | 8 | A | 9 | 7 | | 9 | 8 | A | 9 | 9 | |---|---|---|---|---| Balance: $42.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | 9 | Q | Q | 7 | A | | A | 7 | K | A | K | | 8 | 7 | A | Q | A | |---|---|---|---|---| Balance: $41.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | K | K | 9 | Q | K | | 9 | A | A | 7 | K | | Q | 8 | 7 | 7 | K | |---|---|---|---|---| Balance: $40.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | 8 | 7 | A | 8 | 7 | | Q | K | 9 | Q | K | | Q | Q | 9 | 9 | K | |---|---|---|---|---| Balance: $39.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | Q | 7 | K | 9 | A | | 8 | Q | A | K | K | | 7 | Q | K | Q | 7 | |---|---|---|---|---| Balance: $38.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | 9 | 9 | 8 | Q | Q | | 9 | A | K | Q | K | | 9 | Q | 7 | 9 | Q | |---|---|---|---|---| Balance: $37.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | Q | 8 | Q | 9 | A | | Q | K | A | 9 | Q | | 9 | 8 | 7 | Q | K | |---|---|---|---|---| Balance: $36.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | Q | 8 | 7 | 8 | K | | 7 | 9 | A | 8 | 7 | | Q | 8 | K | K | 8 | |---|---|---|---|---| Balance: $35.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | A | 8 | 9 | A | A | | 9 | 7 | K | 7 | A | | 7 | Q | A | K | Q | |---|---|---|---|---| Balance: $34.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | 8 | 7 | A | 9 | 9 | | Q | 7 | K | A | A | | 8 | 9 | 7 | 7 | 7 | |---|---|---|---|---| Balance: $33.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 |---|---|---|---|---| | A | 8 | 8 | 9 | 8 | | 7 | 9 | Q | 9 | K | | 9 | A | A | Q | 8 | |---|---|---|---|---| Balance: $32.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | 8 | Q | 9 | A | A | | 7 | K | Q | 9 | K | | Q | K | A | K | 9 | |---|---|---|---|---| Balance: $31.20 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.20 |---|---|---|---|---| | A | Q | K | Q | A | | 7 |[Q]| 7 | 7 | Q | |[Q]| 8 |[Q]| K | 8 | |---|---|---|---|---| Balance: $30.60 | Bet: $1.00 | Win: $0.40 Total Winnings: $0.60 |---|---|---|---|---| | 7 | 7 | 9 | Q | 7 | | 9 |[A]|[A]| 8 | A | |[A]| Q | 9 | Q | Q | |---|---|---|---|---| Balance: $29.90 | Bet: $1.00 | Win: $0.30 Total Winnings: $0.90 |---|---|---|---|---| | 9 | 8 | Q | Q | 7 | | K | 8 | Q | Q | A | | 7 | 8 | 7 | Q | 8 | |---|---|---|---|---| Balance: $28.90 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.90 |---|---|---|---|---| | A | Q | K | A | 7 | | K | A | K | Q | 9 | | A | 7 | 7 | A | Q | |---|---|---|---|---| Balance: $27.90 | Bet: $1.00 | Win: $0.00 Total Winnings: $0.90 |---|---|---|---|---| | 8 | 7 |[Q]| 7 | K | |[Q]|[Q]| 8 | K | 9 | | K | Q | 7 | 7 | 8 | |---|---|---|---|---| Balance: $27.10 | Bet: $1.00 | Win: $0.20 Total Winnings: $1.10 |---|---|---|---|---| | A | A | K | 8 | 7 | | 9 | 8 | 8 | A | A | | 7 | A | K | A | A | |---|---|---|---|---| Balance: $26.10 | Bet: $1.00 | Win: $0.00 Total Winnings: $1.10 |---|---|---|---|---| | 7 | K | A | A | 9 | | 7 | 9 | 7 | 9 | 9 | |[8]|[8]|[8]| 7 | 8 | |---|---|---|---|---| Balance: $25.38 | Bet: $1.00 | Win: $0.28 Total Winnings: $1.38 |---|---|---|---|---| | 7 | K | 9 | 9 | 8 | | Q | 8 | Q | 9 | 7 | | 8 | 9 | A | K | 9 | |---|---|---|---|---| Balance: $24.38 | Bet: $1.00 | Win: $0.00 Total Winnings: $1.38 |---|---|---|---|---| | K | A | 7 | 7 | K | | Q | 8 | A | 9 | A | | K | 8 | A | A | Q | |---|---|---|---|---| Balance: $23.38 | Bet: $1.00 | Win: $0.00 Total Winnings: $1.38
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 |---|---|---|---|---| | Q | 7 | 8 | 8 | A | | 7 | Q | 9 | Q | A | | Q | A | A | 9 | 9 | |---|---|---|---|---| Balance: $22.38 | Bet: $1.00 | Win: $0.00 Total Winnings: $1.38 |---|---|---|---|---| | A | 9 | Q | Q | 8 | | Q | 7 | 9 | Q | 9 | | Q | A | 8 | 9 | 8 | |---|---|---|---|---| Balance: $21.38 | Bet: $1.00 | Win: $0.00 Total Winnings: $1.38 |---|---|---|---|---| | A | 7 |[8]| 7 | 7 | |[8]|[8]| 9 |[8]| K | |[8]| Q |[8]| Q |[8]| |---|---|---|---|---| Balance: $23.98 | Bet: $1.00 | Win: $3.60 Total Winnings: $4.98 |---|---|---|---|---| | A | A | 7 | Q | 7 | | 7 | 9 | 9 | K | A | | 8 | 7 | 8 | 8 | Q | |---|---|---|---|---| Balance: $22.98 | Bet: $1.00 | Win: $0.00 Total Winnings: $4.98 |---|---|---|---|---| | K | A | Q | 9 | 7 | | 7 | Q | A | 8 | 8 | | A | Q | 8 | A | 7 | |---|---|---|---|---| Balance: $21.98 | Bet: $1.00 | Win: $0.00 Total Winnings: $4.98 |---|---|---|---|---| | 7 | 8 | A | A | Q | | A | Q | A | 7 | 8 | | A | 7 | K | K | 8 | |---|---|---|---|---| Balance: $20.98 | Bet: $1.00 | Win: $0.00 Total Winnings: $4.98 |---|---|---|---|---| |[7]| A | A | Q | A | | 9 |[7]| K | A | Q | |[7]| A |[7]| Q | Q | |---|---|---|---|---| Balance: $20.38 | Bet: $1.00 | Win: $0.40 Total Winnings: $5.38 |---|---|---|---|---| | K | 7 | 7 | 9 | K | | 7 | A | 9 | A | 7 | | 7 | 8 | K | K | 8 | |---|---|---|---|---| Balance: $19.38 | Bet: $1.00 | Win: $0.00 Total Winnings: $5.38 |---|---|---|---|---| | K | Q |[A]| A | A | |[A]|[A]| Q | 9 | 8 | |[A]| Q | 9 | A | Q | |---|---|---|---|---| Balance: $19.28 | Bet: $1.00 | Win: $0.90 Total Winnings: $6.28 |---|---|---|---|---| | Q | 7 | A | Q | Q | | 8 | K | K | K | Q | | 7 | 8 | K | 9 | 8 | |---|---|---|---|---| Balance: $18.28 | Bet: $1.00 | Win: $0.00 Total Winnings: $6.28 |---|---|---|---|---| | 8 | Q | Q | 8 | Q | | K | Q | 7 | A | Q | | 9 | Q | K | A | 8 | |---|---|---|---|---| Balance: $17.28 | Bet: $1.00 | Win: $0.00 Total Winnings: $6.28
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 |---|---|---|---|---| | 9 | A | K | 8 | 9 | | 9 | A | 8 | Q | 8 | | 8 | K | 8 | K | 7 | |---|---|---|---|---| Balance: $16.28 | Bet: $1.00 | Win: $0.00 Total Winnings: $6.28 |---|---|---|---|---| | A | 7 | A | K | 9 | | 9 | Q | A | K | K | | 8 | 7 | 9 | A | 8 | |---|---|---|---|---| Balance: $15.28 | Bet: $1.00 | Win: $0.00 Total Winnings: $6.28 |---|---|---|---|---| | K | Q |[9]| K | 7 | | A | Q | K | 9 | 9 | |[9]|[9]| Q |[9]| Q | |---|---|---|---|---| Balance: $14.68 | Bet: $1.00 | Win: $0.40 Total Winnings: $6.68 |---|---|---|---|---| | 8 | 8 | K | Q | 9 | | A | 8 | Q | 9 | A | | 8 | Q | Q | Q | Q | |---|---|---|---|---| Balance: $13.68 | Bet: $1.00 | Win: $0.00 Total Winnings: $6.68 |---|---|---|---|---| | 8 | K | 9 | A | K | | 8 | A | 9 | A | Q | | 7 | A | 9 | A | 7 | |---|---|---|---|---| Balance: $12.68 | Bet: $1.00 | Win: $0.00 Total Winnings: $6.68 |---|---|---|---|---| |[8]|[8]|[8]| A | A | | 9 | 7 | 7 |[8]| 8 | | K | 8 | K | A | Q | |---|---|---|---|---| Balance: $12.12 | Bet: $1.00 | Win: $0.44 Total Winnings: $7.12 |---|---|---|---|---| | K | K | Q | 7 | Q | | Q | 8 | 9 | A | 7 | | Q | 8 | Q | 8 | Q | |---|---|---|---|---| Balance: $11.12 | Bet: $1.00 | Win: $0.00 Total Winnings: $7.12 |---|---|---|---|---| | K | K | 7 | 9 | A | | Q | K | A | K | A | | 9 | K | 9 | 9 | 8 | |---|---|---|---|---| Balance: $10.12 | Bet: $1.00 | Win: $0.00 Total Winnings: $7.12 |---|---|---|---|---| | 9 | K | 7 | Q | Q | | 9 | 9 | 7 | 7 | 7 | | 7 | 9 | Q | 8 | K | |---|---|---|---|---| Balance: $9.12 | Bet: $1.00 | Win: $0.00 Total Winnings: $7.12 |---|---|---|---|---| | K | A | A | A | 9 | | A | 8 | 8 | 7 | Q | | 7 | Q | Q | A | 7 | |---|---|---|---|---| Balance: $8.12 | Bet: $1.00 | Win: $0.00 Total Winnings: $7.12 |---|---|---|---|---| | 8 | K | Q | K | A | | A | Q | K | 9 | K | | K | 8 | 8 | K | 7 | |---|---|---|---|---| Balance: $7.12 | Bet: $1.00 | Win: $0.00 Total Winnings: $7.12
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 |---|---|---|---|---| | K | Q | 8 | A | 7 | | A | Q | 8 | A | 8 | | 7 | Q | A | A | A | |---|---|---|---|---| Balance: $6.12 | Bet: $1.00 | Win: $0.00 Total Winnings: $7.12 |---|---|---|---|---| | 8 | Q | 7 | Q | A | | Q | 8 | 8 | A | K | | Q | A | 7 | 7 | K | |---|---|---|---|---| Balance: $5.12 | Bet: $1.00 | Win: $0.00 Total Winnings: $7.12 |---|---|---|---|---| | Q | 9 | K | 9 | K | | K | Q | 9 | 9 | K | | K | A | 8 | A | 8 | |---|---|---|---|---| Balance: $4.12 | Bet: $1.00 | Win: $0.00 Total Winnings: $7.12 |---|---|---|---|---| | K | K | 8 | 9 | 8 | | 9 | 7 | A | 9 | A | | 8 | Q | 8 | 8 | 9 | |---|---|---|---|---| Balance: $3.12 | Bet: $1.00 | Win: $0.00 Total Winnings: $7.12 |---|---|---|---|---| | K | 8 | K | 9 | 8 | |[K]|[9]|[K]| K | 8 | |[9]|[K]|[9]| A | A | |---|---|---|---|---| Balance: $2.92 | Bet: $1.00 | Win: $0.80 Total Winnings: $7.92 |---|---|---|---|---| | Q | 7 | 9 | A |[8]| |[8]|[8]| 9 |[8]| K | |[8]|[8]|[8]| Q | 9 | |---|---|---|---|---| Balance: $5.06 | Bet: $1.00 | Win: $3.14 Total Winnings: $11.06 |---|---|---|---|---| | 9 | 7 | A | 7 | 9 | | Q | Q | A | K | 9 | | 9 | Q | 7 | Q | K | |---|---|---|---|---| Balance: $4.06 | Bet: $1.00 | Win: $0.00 Total Winnings: $11.06 |---|---|---|---|---| | 7 | K | 9 | 8 | 8 | | 8 | Q | A | A | 8 | | 7 | Q | Q | 8 | 9 | |---|---|---|---|---| Balance: $3.06 | Bet: $1.00 | Win: $0.00 Total Winnings: $11.06 |---|---|---|---|---| | K | 8 | K | Q | 9 | | 8 |[A]|[A]| 9 | A | |[A]| K | 9 | A | A | |---|---|---|---|---| Balance: $2.36 | Bet: $1.00 | Win: $0.30 Total Winnings: $11.36 |---|---|---|---|---| | 7 | Q | 7 | K | Q | | Q | K | K | 7 | 8 | | Q | Q | K | 9 | 8 | |---|---|---|---|---| Balance: $1.36 | Bet: $1.00 | Win: $0.00 Total Winnings: $11.36 |---|---|---|---|---| | 8 | Q | A | 7 | Q | | Q | A | A | 7 | 9 | | 8 | A | K | 7 | 8 | |---|---|---|---|---| Balance: $0.36 | Bet: $1.00 | Win: $0.00 Total Winnings: $11.36 Insufficient funds
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 Insufficient funds Profiling This profile is after fixing up the low-hanging fruit on WinCandidate.win_class. There are other optimisations possible, especially if this is intended for headless simulation. 5538495 function calls (5464053 primitive calls) in 2.292 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 223326 0.451 0.000 0.571 0.000 288690.py:150(_format_row) 310175 0.339 0.000 0.481 0.000 288690.py:71(map) 322582 0.168 0.000 0.784 0.000 288690.py:134(_get_candidates) 74442 0.150 0.000 0.150 0.000 {built-in method _locale.localeconv} 310175 0.135 0.000 0.135 0.000 288690.py:141(<listcomp>) 322582 0.131 0.000 0.252 0.000 288690.py:123(_get_winnings) 37221 0.080 0.000 0.303 0.000 locale.py:265(currency) 339265 0.076 0.000 0.101 0.000 types.py:176(__get__) 310175 0.057 0.000 0.092 0.000 <string>:1(<lambda>) 972468 0.056 0.000 0.056 0.000 {built-in method builtins.len} 86849/12407 0.053 0.000 0.984 0.000 {method 'join' of 'str' objects} 37221 0.050 0.000 0.076 0.000 random.py:519(<listcomp>) 12407 0.046 0.000 1.119 0.000 288690.py:110(__init__)
{ "domain": "codereview.stackexchange", "id": 45344, "lm_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 }
c++, functional-programming, c++20 Title: Is it valid to pass struct through std::fold_left to persist state? Question: I am exploring functional programming design with C++. The code below uses a struct passed to ranges::fold_left for processing. The final result is returned in the struct. **Updated to remove a toy version of code since full code was requested and supplied Is this an appropriate functional programming design? Specifically, using LineTotal appropriate to maintain state information through the interactions of fold_left used in extract_values? #include <algorithm> #include <iomanip> #include <iostream> #include <ranges> #include "../AdventCpp.h" namespace rng = std::ranges; namespace vws = std::views; //------------------------------------------------------- execFunc execute = [ ](std::string_view&& aoc_data) noexcept -> uint64_t { using vws::slide, vws::split, rng::fold_left, // vws::take, vws::zip, vws::filter; using std::string_view, std::string; auto summation = [ ](uint64_t sum, auto&& aoc_dual) noexcept -> uint64_t { auto top_line = string(string_view(aoc_dual.front())); auto bottom_line = string(string_view(aoc_dual.next().front())); // change dots to spaces so ispunct doesn't see dots rng::replace(top_line, '.', ' '); rng::replace(bottom_line, '.', ' '); // generate container with pairs of chars from the two lines of data auto zip_lines = zip(top_line, bottom_line); // change dots to spaces so ispunct doesn't see dots auto two_line_proc = [ ](uint64_t sum, auto&& lines) { // some structs to pass data through fold_left struct LineState { uint64_t digits_sum { }; bool have_symbol { }; }; struct LineTotal { uint64_t total { }; LineState top_data; LineState bot_data; };
{ "domain": "codereview.stackexchange", "id": 45345, "lm_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++, functional-programming, c++20", "url": null }
c++, functional-programming, c++20 auto out_sd = [&](char const tag, LineTotal s_d) { auto [total, top, bot] = s_d; std::cout << tag << '\t' << total << '\t' // << top.digits_sum << '\t' << top.have_symbol << '\t' << bot.digits_sum << '\t' << bot.have_symbol << '\n'; }; // is the value valid with symbols tagging it? auto is_value = [ ](uint64_t value, bool symbol) noexcept -> uint64_t { return (value != 0 and symbol) ? value : 0; }; // calculate running value of digits from a line auto calc_value = [ ](uint64_t value, char ch) noexcept -> uint64_t { if (isdigit(ch)) { value = value * 10 + (ch - '0'); } return value; }; auto extract_values = [&is_value, &calc_value](LineTotal sum_data, auto&& two_char) { auto [top_char, bot_char] = two_char; auto& [total, top, bottom] = sum_data; if (top_char == ' ' and ispunct(bot_char)) { total += bottom.digits_sum; total += top.digits_sum; top = {0, true}; bottom = {0, true}; } else if (bot_char == ' ' and ispunct(top_char)) { top = {top.digits_sum, true}; total += bottom.digits_sum; bottom = {0, bottom.have_symbol}; } else if (top_char == ' ' and bot_char == ' ') { total += is_value(top.digits_sum, bottom.have_symbol); total += is_value(bottom.digits_sum, top.have_symbol or bottom.have_symbol); top = { }; bottom = { }; } else { top = {calc_value(top.digits_sum, top_char), top.have_symbol or ispunct(top_char)};
{ "domain": "codereview.stackexchange", "id": 45345, "lm_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++, functional-programming, c++20", "url": null }
c++, functional-programming, c++20 bottom = {calc_value(bottom.digits_sum, bot_char), bottom.have_symbol or ispunct(bot_char)}; } return sum_data; }; // process two lines of aoc_data return sum + fold_left(lines, LineTotal { }, extract_values).total; }; return two_line_proc(sum, zip_lines); }; return fold_left(aoc_data | split('\n') | slide(2), 0ul, summation); }; int main() { advent_cpp(test_data1, aoc_data, execute, 4361); // 4361 / 528799 return 0; } Answer: It's not pure functional programming There are different ways to think about functional programming. Is it just a tool in your programming toolbox? Is it something you should strive towards? Or should you write something that is embracing the function programming paradigm 100%? You are using a functional programming style a lot, but there are statements that are definitely not FP, like: rng::replace(top_line, '.', ' '); This modifies a std::string in-place, which means this statement has side-effects. If you want to make this functional, I'd use something like std::ranges::transform_view(): auto top_line_no_dots = rng::transform_view(top_line, [](auto c){return c == '.' ? ' ' : c;});
{ "domain": "codereview.stackexchange", "id": 45345, "lm_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++, functional-programming, c++20", "url": null }
c++, functional-programming, c++20 Similarly, you define lambdas that capture by reference, so they technically are functions with side-effects, again that's also not very FP. Even just adding something to an existing variable can be considered to be non-functional. In functional programming languages you then have to jump through hoops to do that anyway. I am sure you can rewrite your code to be completely functional; it's all doable in C++, although it lacks the concise notation of functional programming languages in this area. You single out std::ranges::fold_left() in your question, but that's just a tool in your toolbox. It helps write functional code, but the mere fact of using it doesn't make your code functional per se. Also, internally it's implemented using the good old imperative for-loop, make of that what you will. You did write it in a way that doesn't have side effects, so in that regard its use here is indeed pure functional. Pass std::string_views by value You let execute() take a std::string_view by r-value reference, but that is unnecessary; just take it by value instead. Unnecessary use of lambdas Sure, functional programming languages like their lambda functions. But a lambda function assigned to a variable with a name is pretty much just a regular function. The only time that isn't the case is when you have captures. So consider declaring execute() as a regular function. You could also define some of the other lamdas as regular functions. Then there is this pattern: auto two_line_proc = [ ](uint64_t sum, auto&& lines) { // Do some stuff … return sum + fold_left(lines, LineTotal { }, extract_values).total; }; return two_line_proc(sum, zip_lines); You could instead immediately execute the lambda: return [ ](uint64_t sum, auto&& lines) { // Do some stuff … return sum + fold_left(lines, LineTotal { }, extract_values).total; }(sum, zip_lines);
{ "domain": "codereview.stackexchange", "id": 45345, "lm_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++, functional-programming, c++20", "url": null }
c++, functional-programming, c++20 But why use a lambda at all? You can just write: // Do some stuff … return sum + fold_left(lines, LineTotal { }, extract_values).total; Naming things I have a hard time understanding what the code is supposed to do. I'm guessing it's one of the Advent of Code problems. But which day? What is the problem? Neither the comments nor the names of functions and variables give me any hints. Try to give better names to functions and variables such that their meaning becomes more obvious to someone who isn't already familiar with the exact problem you are trying to solve. Use comments to fill in where you can't with just the function and variable names.
{ "domain": "codereview.stackexchange", "id": 45345, "lm_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++, functional-programming, c++20", "url": null }
c, console, game-of-life Title: Conway's Game of Life Terminal Visualization in C Question: I'm currently learning C, and decided to practice what I've been working on with a project, namely implementing Conway's Game of Life as a terminal visualization. This is my first project in C. The result: and my code: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/ioctl.h> #define DEAD ' ' #define ALIVE "█" int WIDTH, HEIGHT; typedef enum { alive, dead, } cell_t; cell_t** grid; cell_t** new_grid; void clear_screen() { printf("\x1b[2J"); } void hide_cursor() { printf("\x1b[?25l"); } void show_cursor() { printf("\x1b[?25h"); } void move_home() { printf("\x1b[0;0H"); } void move_to(int row, int col) { printf("\x1b[%d;%dH", row + 1, col * 2 + 1); } void free_grids() { for (int i = 0; i < HEIGHT; ++i) { free(grid[i]); free(new_grid[i]); } free(grid); free(new_grid); } int count_neighbors(int row, int col) { int count = 0; for (int y = row - 1; y <= row + 1; ++y) { for (int x = col - 1; x <= col + 1; ++x) { if (y >= 0 && y < HEIGHT && x >= 0 && x < WIDTH && !(y == row && x == col)) { count += (grid[y][x] == alive) ? 1 : 0; } } } return count; } void init_grid() { grid = (cell_t**)malloc(HEIGHT * sizeof(cell_t*)); new_grid = (cell_t**)malloc(HEIGHT * sizeof(cell_t*)); for (int i = 0; i < HEIGHT; ++i) { grid[i] = (cell_t*)malloc(WIDTH * sizeof(cell_t)); new_grid[i] = (cell_t*)malloc(WIDTH * sizeof(cell_t)); for (int j = 0; j < WIDTH; ++j) { grid[i][j] = (rand() % 2) ? alive : dead; } } }
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
c, console, game-of-life void print_grid() { for (int y = 0; y < HEIGHT; ++y) { for (int x = 0; x < WIDTH; ++x) { if (grid[y][x] == alive) { move_to(y, x); int n = count_neighbors(y, x); if (n < 2) { // underpopulation printf("\x1b[36m"); } else if (n == 2 || n == 3) { // good printf("\x1b[34m"); } else if (n > 3) { // overpopulation printf("\x1b[35m"); } printf(ALIVE); printf(ALIVE); printf("\x1b[0m"); } } if (y < HEIGHT - 1) { printf("\n"); } } fflush(stdout); } void next() { for (int y = 0; y < HEIGHT; ++y) { for (int x = 0; x < WIDTH; ++x) { int neighbors = count_neighbors(y, x); if (grid[y][x] == alive) { new_grid[y][x] = (neighbors == 2 || neighbors == 3) ? alive : dead; } else { new_grid[y][x] = (neighbors == 3) ? alive : dead; } } } for (int y = 0; y < HEIGHT; ++y) { for (int x = 0; x < WIDTH; ++x) { grid[y][x] = new_grid[y][x]; } } } void init_terminal_size() { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); WIDTH = w.ws_col / 2; HEIGHT = w.ws_row; } int main() { init_terminal_size(); init_grid(); hide_cursor(); atexit(free_grids); atexit(show_cursor); while (1) { move_home(); clear_screen(); print_grid(); usleep(100 * 1000); next(); } return 0; } I'd like some feedback/suggestions on how I can improve it. The main issues I can identify are:
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
c, console, game-of-life I'd like some feedback/suggestions on how I can improve it. The main issues I can identify are: Blinking (probably due to the amount of printf statements I am making) Lack of proper program termination Possibly leaking memory as a result of problem 2 Usage of preprocessor directives (DEAD isn't used-- forgot to delete it, but I'm not sure if I should be using string constants instead). Trying to fix issue 1, I attempted to create a char* that I could append to using reallocations and just print out the entire char* after I'd appended every character to the dynamic char*. This didn't work and I had to revert it. Additionally, with this method I'd be worried about the amount of allocations I'm making (not sure if this would impact performance or increase performance). I currently try to use atexit() to free the memory at exit, but the cursor isn't being shown on exit so I can assume that neither of those functions are being executed. Finally, I attempted to use getchar() to check if q was being pressed on the keyboard, but this halted the program and wouldn't exit. I just realized this was probably because I hadn't entered raw mode. Advise is appreciated. Answer: I'm impressed that this is your first project in C -- it's good! What follows are some comments on what's good that you should continue to do and then some suggestions for improvements. What's good? There's a lot here that is good, including: good naming of functions and variables decomposing the project into logical functions reasonable program flow thought about freeing memory and restoring the terminal
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
c, console, game-of-life These are all good things that you should definitely strive to continue. Possible improvements These are some suggestions for how you might improve this program. Gracefully exit the program You're right that the atexit functions are not called because there's no way to gracefully exit the program. One way to do that would be, as you suspected, to alter the terminal settings. Here's one way to do that by modifying your hide_cursor function: #include <termios.h> #include <fcntl.h> static struct termios oldterm, newterm; static int oldf; void hide_cursor(void) { printf("\x1b[?25l"); tcgetattr(STDIN_FILENO, &oldterm); /* grab old terminal i/o settings */ newterm = oldterm; /* make new settings same as old settings */ newterm.c_lflag &= ~ICANON; /* disable buffered i/o */ newterm.c_lflag &= ~ECHO; /* disable echo mode */ tcsetattr(STDIN_FILENO, TCSANOW, &newterm); /* use these new terminal i/o settings now */ oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); } This matched with a corresponding alteration in the show_cursor routine: void show_cursor(void) { tcsetattr(STDIN_FILENO, TCSANOW, &oldterm); fcntl(STDIN_FILENO, F_SETFL, oldf); printf("\x1b[?25h\n"); } What this does is to allow you to gracefully exit by changing the while (1) to this: for (int ch = getchar(); ch == EOF; ch = getchar()) {
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
c, console, game-of-life Tell the compiler when no arguments are expected For most of these functions that don't take arguments, instead of writing void next() write void next(void). Otherwise the compiler will accept any number of arguments to that function, and that's probably not what you want. Avoid using global variables In this case, the use of global variables is not terrible since it's a single file program. However, as you write larger programs, try to avoid global variables. They can hide linkages between different parts of the code and make them harder to maintain and understand. If you must have global variables, make them static to give them file scope rather than global scope. Don't use ALLCAPS for variables In C, the traditional use for ALLCAPS is for macros, so unless it's a macro (basically any #define), use conventional naming instead. Understand that return 0 is optional for main Unlike every other function that returns an int, main is special and does not require you to specifically write return 0;. If you don't that's the implicit behavior anyway. Some people write it anyway; I prefer to omit it. Either way, you may encounter code that either has it or doesn't, so it's good to know about. Check for errors The calls to malloc can fail, and when they do, they return NULL. You should check for that before using the memory. Consolidate constants The colors shown for the different numbers of neighbors would be easier to understand and modify if they were pulled out as named constants. Avoid copies if practical In this case, the last part of next() copies everything from one array to the other. Rather than doing that, an alternative would be to simply toggle which array is the next one vs. the current one. Add a bit of variation
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
c, console, game-of-life Add a bit of variation By design, rand() starts with a seed value of 0 unless otherwise told, which means that you will get the same pattern every time the program is run. To make it different, but controllable by the user, you could seed with a user-supplied number by modifying the first part of main like this: int main(int argc, char *argv[]) { if (argc > 1) { srand(atoi(argv[1])); }
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
c, console, game-of-life Use more modern C If you are using a compiler that supports at least C11, there are a lot of improvements that you can make without sacrificing readability. Step by step, here are the changes. Use structures to group data The height and width and the two cell arrays are central to this program, so we can introduce structures to capture this. struct dims { int width; int height; }; struct Grid { int current; struct dims dim; void* g; }; You may wonder why g is defined as a void * when what it really contains is cell_t data. We sacrifice a little readability here in exchange for a very useful technique later. Return a structure The point to init_terminal_size() is to get the width and height of the terminal. Rather than setting global variables, we can return a structure directly: struct dims init_terminal_size() { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); return (struct dims){ .width = w.ws_col / 2, .height = w.ws_row}; } Allocate memory as few times as possible Memory allocation is more efficient and easier to track when we minimize the number of allocations. In this program, we can reduce the number of allocations to a single one. First, in main, we can create and initialize the grids like this: struct Grid cells = { .dim =init_terminal_size() }; if (!init_grid(&cells)) { return 1; } Here's what is inside init_grid: bool init_grid(struct Grid* grid) { cell_t (*pGrid)[2][grid->dim.height][grid->dim.width] = malloc(sizeof(*pGrid)); if (!pGrid) { return false; } grid->g = pGrid; for (int i = 0; i < grid->dim.height; ++i) { for (int j = 0; j < grid->dim.width; ++j) { (*pGrid)[0][i][j] = (rand() % 2) ? alive : dead; } } return true; }
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
c, console, game-of-life First, unless you are using a C23 compiler, which has it as a keyword, you'll need to #include <stdbool.h> to get bool. This line uses syntax that is unfamiliar even to many C programmers, so I'll explain it in some detail: cell_t (*pGrid)[2][grid->dim.height][grid->dim.width] = malloc(sizeof(*pGrid)); This declares a variable pGrid as a three-dimensional array of cell_t. This is using the much-maligned variable-length array (VLA) syntax, but is not a VLA. (See this ACCU talk for a good explanation of what is wrong with VLA, and also how to use syntax like this.) The two big advantages, are that it greatly simplifies calculating the size because we can use the sizeof() operator to do it for us, and that we can use the natural subscripting syntax to access members. Note that the height and width parameters are only available at runtime; we do not know their values during compiling and so we can't use constants. That's why void* is the type used in the structure declaration. The first dimension uses the idea above and indicates which of the two grid arrays we're using, so it should be pretty clear that this line is randomly assigning alive or dead to each of the cells in the first array: (*pGrid)[0][i][j] = (rand() % 2) ? alive : dead;
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
c, console, game-of-life We could alternatively use a pointer and simply increment it to the end of the array, but this way shows the intent a bit more clearly and we're not that concerned about performance here, since it's only done once. Pass pointers to avoid global variables Using this same syntax as described above, we can easily modify some of the other functions. For example, here is count_neighbors: int count_neighbors(const struct Grid grid[static restrict 1], int row, int col) { const int height = grid->dim.height; const int width = grid->dim.width; const cell_t (*pGrid)[2][height][width] = grid->g; int count = 0; for (int y = row - 1; y <= row + 1; ++y) { for (int x = col - 1; x <= col + 1; ++x) { if (y >= 0 && y < height && x >= 0 && x < width && !(y == row && x == col)) { count += ((*pGrid)[grid->current][y][x] == alive) ? 1 : 0; } } } return count; }
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
c, console, game-of-life return count; } Here the [static restrict 1] means that the pointer, grid in this instance, must have at least one valid instance (static) and further that it must have exactly that many (restrict). This can help the compiler generate optimal code and clearly signals the intent to a programmer reading the code. The next() function uses this, too, and also changes the current grid to avoid copies as mentioned above, also with a small change to use a switch for clarity: void next(struct Grid grid[static restrict 1]) { const int height = grid->dim.height; const int width = grid->dim.width; cell_t (*pGrid)[2][height][width] = grid->g; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { switch (count_neighbors(grid, y, x)) { case 3: // stay alive or become born (*pGrid)[1 - grid->current][y][x] = alive; break; case 2: // stay unchanged (*pGrid)[1 - grid->current][y][x] = (*pGrid)[grid->current][y][x]; break; default: // all other cases (*pGrid)[1 - grid->current][y][x] = dead; } } } grid->current = 1 - grid->current; }
{ "domain": "codereview.stackexchange", "id": 45346, "lm_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, console, game-of-life", "url": null }
beginner, c, bitwise Title: Reading/writing single bits from/to FILE Question: I'm implementing a Huffman encoding/decoding program and I need a way to deal with single bits. I tried to keep things as simple as possible, I "pack" bits inside a single byte and I have only one index to worry about (of course this is a bit inefficient). I'd like to get general feedback. Any suggestion is welcome! bitbuf.h #ifndef BITBUF_HEADER #define BITBUF_HEADER #include <stdio.h> #include <stdlib.h> #include <stdbool.h> //#define NDEBUG #include <assert.h> #define BITS_IN_BUF 8 struct bitbuf { FILE *fp; bool is_writer; unsigned char buf; unsigned int idx; }; /** * bitbuf_new: allocates a new bitbuf and returns its pointer. * * If writer is true, it will be usable for writing bits to fp, * otherwise for reading bits from fp. * writer must be setted according to the opening mode of fp ("w", * "a" -> true, "r" -> false). * * Read and write ("w+", "r+", "a+") modes are a bit tricky to * handle so they are not "officially" supported. * * On alloc failure, returns NULL. */ struct bitbuf *bitbuf_new(FILE *fp, bool writer); #define bitbuf_new_bit_writer(fp) bitbuf_new((fp), true) #define bitbuf_new_bit_reader(fp) bitbuf_new((fp), false) /** * bitbuf_write_bit: writes a bit (1 if bit == true, 0 if bit == false) and * returns true. * * Bits are buffered inside a byte from left to right. Only * with a successful call to bitbuf_flush() they will be * written to the underlying FILE pointer. This happens * automatically when the buffer (byte) if full (or when * bitbuf_free() is called). * * On flush failure, returns false. */ bool bitbuf_write_bit(struct bitbuf *bit_writer, bool bit);
{ "domain": "codereview.stackexchange", "id": 45347, "lm_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, c, bitwise", "url": null }
beginner, c, bitwise /** * bitbuf_flush: flushes the buffer (a byte) to the underlying FILE pointer and * returns true. * * If the buffer is not full, it will be written "0 padded". * If the buffer is empty, nothing will be written and true will * be returned. * * On write failure, returns false. */ bool bitbuf_flush(struct bitbuf *bit_writer); /** * bitbuf_read_bit: reads a bit and returns 0 or 1 accordingly. * * Bits are buffered inside a byte and read from left to * right. They will be loaded automatically from the * underlying FILE pointer when the buffer is empty. * * On load failure, returns EOF. */ int bitbuf_read_bit(struct bitbuf *bit_reader); /** * bitbuf_load: reads a byte from the underlying FILE pointer, sets it as new * buffer to read from (with bitbuf_read_bit()) and returns true. * * On read failure (or EOF), returns false. */ bool bitbuf_load(struct bitbuf *bit_reader); /** * bitbuf_free: frees memory occupied by bitbuf. If bitbuf is a "bit_writer", * the buffer will be flushed using bitbuf_flush(). * * It's safe to pass a NULL pointer. */ void bitbuf_free(struct bitbuf *bitbuf); /** * bitbuf_close: frees bitbuf (using bitbuf_free()) and calls fclose() on the * underlying FILE pointer used by bitbuf. * * It's safe to pass a NULL pointer. */ void bitbuf_close(struct bitbuf *bitbuf); #endif bitbuf.c #include "bitbuf.h" struct bitbuf *bitbuf_new(FILE *fp, bool writer) { struct bitbuf *new_bb = malloc(sizeof(*new_bb)); if (new_bb == NULL) { return NULL; } new_bb->fp = fp; new_bb->is_writer = writer; new_bb->buf = 0; new_bb->idx = (writer) ? 0 : BITS_IN_BUF; /* to force load upon first read */ return new_bb; }
{ "domain": "codereview.stackexchange", "id": 45347, "lm_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, c, bitwise", "url": null }
beginner, c, bitwise bool bitbuf_write_bit(struct bitbuf *bw, bool bit) { assert(bw->is_writer); if (bw->idx == BITS_IN_BUF && ! bitbuf_flush(bw)) { return false; } if (bit) { bw->buf |= (0x80 >> bw->idx); /* 0x80 is 0b10000000 */ } bw->idx++; return true; } bool bitbuf_flush(struct bitbuf *bw) { assert(bw->is_writer); if (bw->idx > 0) { if (fputc(bw->buf, bw->fp) == EOF) { return false; } bw->buf = 0; bw->idx = 0; } return true; } int bitbuf_read_bit(struct bitbuf *br) { assert( ! br->is_writer); if (br->idx == BITS_IN_BUF && ! bitbuf_load(br)) { return EOF; } return ((0x80 >> br->idx++) & br->buf) == 0 ? 0 : 1; } bool bitbuf_load(struct bitbuf *br) { assert( ! br->is_writer); int byte = fgetc(br->fp); if (byte == EOF) { return false; } br->buf = byte; br->idx = 0; return true; } void bitbuf_free(struct bitbuf *bitbuf) { if (bitbuf == NULL) { return; } if (bitbuf->is_writer) { bitbuf_flush(bitbuf); } free(bitbuf); } void bitbuf_close(struct bitbuf *bitbuf) { if (bitbuf == NULL) { return; } FILE *fp = bitbuf->fp; bitbuf_free(bitbuf); fclose(fp); } I also wrote two simple test programs: test_sequence.c #include "bitbuf.h" #define N 1013 void test_write_bit(struct bitbuf *bw, int n) { srand(n); for (int i = 0; i < n; i++) { bitbuf_write_bit(bw, rand() % 2 == 0); } } void test_read_bit(struct bitbuf *br, int n) { srand(n); for (int i = 0; i < n; i++) { assert(bitbuf_read_bit(br) == (rand() % 2 == 0) ? 1 : 0); } }
{ "domain": "codereview.stackexchange", "id": 45347, "lm_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, c, bitwise", "url": null }
beginner, c, bitwise int main(void) { FILE *fp = fopen("test_sequence_file", "w"); if (fp == NULL) { perror("Error"); return 1; } struct bitbuf *bw = bitbuf_new_bit_writer(fp); test_write_bit(bw, N); bitbuf_free(bw); freopen(NULL, "r", fp); struct bitbuf *br = bitbuf_new_bit_reader(fp); test_read_bit(br, N); bitbuf_close(br); puts("Test OK"); } test_copy.c #include "bitbuf.h" bool open_files(char *in_path, FILE **in_file, char *out_path, FILE **out_file) { *in_file = fopen(in_path, "r"); if (*in_file == NULL) { perror("Error"); return false; } *out_file = fopen(out_path, "w"); if (*out_file == NULL) { perror("Error"); fclose(*out_file); return false; } return true; } int main(int argc, char **argv) { if (argc != 3) { fprintf(stderr, "Error: usage: %s [source] [dest]\n", argv[0]); return 1; } FILE *in_file, *out_file; if ( ! open_files(argv[1], &in_file, argv[2], &out_file)) { return 1; } struct bitbuf *br = bitbuf_new_bit_reader(in_file); struct bitbuf *bw = bitbuf_new_bit_writer(out_file); int bit; while ((bit = bitbuf_read_bit(br)) != EOF) { bitbuf_write_bit(bw, bit == 1); } bitbuf_close(br); bitbuf_close(bw); }
{ "domain": "codereview.stackexchange", "id": 45347, "lm_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, c, bitwise", "url": null }
beginner, c, bitwise bitbuf_close(br); bitbuf_close(bw); } Here some testing output: bitbuf$ cc -std=c11 -Wall -Wextra -Werror -c -o bitbuf.o bitbuf.c bitbuf$ cc -std=c11 -Wall -Wextra -Werror -o test_sequence bitbuf.o test_sequence.c bitbuf$ cc -std=c11 -Wall -Wextra -Werror -o test_copy bitbuf.o test_copy.c bitbuf$ ./test_sequence Test OK bitbuf$ dd if=/dev/urandom bs=1M count=20 > original 20+0 records in 20+0 records out 20971520 bytes (21 MB, 20 MiB) copied, 0.179982 s, 117 MB/s bitbuf$ time ./test_copy original copy real 0m5.850s user 0m5.796s sys 0m0.052s bitbuf$ ls -l original copy -rw-r--r-- 1 marco marco 20971520 Jan 21 17:17 copy -rw-r--r-- 1 marco marco 20971520 Jan 21 17:16 original bitbuf$ diff original copy bitbuf$ echo $? 0 bitbuf$
{ "domain": "codereview.stackexchange", "id": 45347, "lm_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, c, bitwise", "url": null }
beginner, c, bitwise Answer: For a beginner, this is pretty decent! Here are some things that could be improved. Naming Many of your variable names are 2 or 3 characters long. That's difficult to read and understand. I recommend using longer names that are descriptive. fp could be file; buf should be buffer or better yet byte_buffer, and idx should be bit_index. Using a single generic word (like idx) is usually a sign that you need better naming. What does it index? Why remove those 2 extra characters? Don't Let A Caller Shoot Themselves in the Foot The bitbuf_new() function takes a file pointer and a boolean value for whether the file is opened for reading or writing. There are many ways a user of this function can screw it up. They can pass in a NULL file pointer. They can pass in a file pointer that's open for read, but say that it's open for writing, or the reverse. They can pass in a stale file pointer (one that was already closed, for example). The macros don't solve this problem. They're just "shortcuts" that are actually longer to type than their textual replacement. It would make more sense to have them pass in a file name and an open mode string, just like is sent to fopen() and to call fopen() in the bitbuf_new() function. Especially given the fact that bitbuf_close() closes the file. That's especially troublesome - you have to open the file yourself, pass it to bitbuf_new() but bitbuf_close() will close it for you. And bitbuf_close() also frees the buffer? Why? This all seems inconsistent and confusing. I would make bitbuf_new() take a file name and a mode string. I would remove bitbuf_close() and just have bitbuf_free() also close the file. Performance
{ "domain": "codereview.stackexchange", "id": 45347, "lm_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, c, bitwise", "url": null }
beginner, c, bitwise Performance You mention "this is a bit inefficient". I recommend reading in a larger buffer of around 1-4k and getting bits out of that. You should probably profile to figure out the ideal size, but that's probably a good place to start. Having 1 extra index will only add 4-8 bytes to the structure, so that shouldn't be too onerous. Are you reading from or writing to lots of files at the same time? If not, then it's negligible.
{ "domain": "codereview.stackexchange", "id": 45347, "lm_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, c, bitwise", "url": null }
javascript, react.js, typescript Title: How to encapsulated javascript code using imutable method? Question: I have this code, but I need to return pure functions instead the mutating functions. Is it possible? Perhaps using OOP? I don't know how to improve it. I tried to return the values in each function, but I haven't had success. import { AssetStatusType } from '@domain/interfaces/common' import { BothComponentType, ComponentsType, GroupFiltersType, OperationType, OverviewModelType, PendenciesOverviewType, PendenciesType, StructurePendenciesCount, StructureStatusCount } from '../../types' const updateStatusCount = ( statusCount: StructureStatusCount, status: AssetStatusType ) => { statusCount[status] = (statusCount[status] || 0) + 1 } const updatePendenciesCount = ( pendenciesCount: StructurePendenciesCount, key: AssetStatusType, subKey: OperationType | PendenciesOverviewType ) => { pendenciesCount[key] = pendenciesCount[key] ?? {} pendenciesCount[key][subKey] = (pendenciesCount[key]?.[subKey] || 0) + 1 } const processOverviewPendencies = ( pendencies: PendenciesType[] | null | undefined, pendenciesCount: StructurePendenciesCount, countedIds: Set<string>, id: string ) => { if (pendencies?.length) { for (const { state, pendencyType } of pendencies) { const uniqueId = `${state}-${pendencyType}-${id}` if (!countedIds.has(uniqueId)) { updatePendenciesCount(pendenciesCount, state, pendencyType) countedIds.add(uniqueId) } } } } const processOverviewComponents = ( components: ComponentsType[], isGroupByTree: boolean, statusCount: StructureStatusCount, pendenciesCount: StructurePendenciesCount, countedIds: Set<string>, id: string, type: BothComponentType ) => { for (const { pendencies, status, operationType } of components) { if (isGroupByTree && type === 'location') { updateStatusCount(statusCount, status)
{ "domain": "codereview.stackexchange", "id": 45348, "lm_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, react.js, typescript", "url": null }
javascript, react.js, typescript if (operationType) { updatePendenciesCount(pendenciesCount, status, operationType) } } processOverviewPendencies(pendencies, pendenciesCount, countedIds, id) } } const processOverviewData = ( data: OverviewModelType[], groupBy: GroupFiltersType, statusCount: StructureStatusCount, pendenciesCount: StructurePendenciesCount, countedIds: Set<string> ) => { const isGroupByTree = groupBy === 'tree' const isGroupByAsset = groupBy === 'asset' for (const { id, status, components, operationType, type } of data) { if (isGroupByAsset || type === 'asset') { updateStatusCount(statusCount, status) if (operationType) { updatePendenciesCount(pendenciesCount, status, operationType) } } processOverviewComponents( components, isGroupByTree, statusCount, pendenciesCount, countedIds, id, type ) } } export const calculateOverviewCounts = ( data: OverviewModelType[], groupBy: GroupFiltersType ) => { const statusCount: StructureStatusCount = {} as StructureStatusCount const pendenciesCount: StructurePendenciesCount = {} as StructurePendenciesCount const countedIds = new Set<string>() processOverviewData(data, groupBy, statusCount, pendenciesCount, countedIds) return { ...statusCount, pendencies: pendenciesCount } } Is there a cleaner and more elegant way to do this? I need to return an object like this: // calculateOverviewCounts return this { pendencies: StructurePendenciesCount; working: number; inAlert: number; warning: number; stopped: number; off: number; } StructurePendenciesCount is: Answer: I don't really understand what the code is trying to do, but I can comment in general. When you have a tree structure like this, you can usually flatten it to make the problem much easier to solve. Some tips:
{ "domain": "codereview.stackexchange", "id": 45348, "lm_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, react.js, typescript", "url": null }
javascript, react.js, typescript Use Array.flatMap to un-nest the tree. Use lodash uniqBy (or write your own) on the flattened tree to get unique pendency items before counting them Use lodash countBy (or write your own) to count by status Replace if (pendencies?.length) with pendencies ?? [] to reduce branching (and shouldn't it be "dependencies"?) Try to answer each question with a different function (as opposed to answering all questions within one iteration of the tree structure). If performance is a concern (doubtful), you may ignore this Fix the data structure, if that's possible. Name things the same (state vs status). groupBy asset is on a type of asset, but groupBy tree is on a location. Seems a bit odd. Status in general seems like it could be in a separate, attached object instead of inlined in each model. For example, to get status counts (all code is untested. The filters seem wrong): const components = overviews.flatMap(overview => overview.components) const assetOverviews = overviews.filter(overview => groupBy === 'asset' && overview.type === 'asset') const treeComponents = components.filter(component => groupBy === 'tree' && component.type === 'location') const statusCounts = _.countBy([...assetOverviews,...treeComponents], x => x.status) Similarly for pendencies: const uniquePendencies = _(overviews) .flatMap(overview => overview.components.map(component => ({ component, overview }))) .flatMap(({ overview, component }) => (component.pendencies ?? []).map(pendency => ({ overview, pendency }))) .uniqBy(({ overview, pendency }) => `${pendency.state}-${pendency.pendencyType}-${overview.id}`) .map(x => x.pendency) .value()
{ "domain": "codereview.stackexchange", "id": 45348, "lm_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, react.js, typescript", "url": null }
javascript, react.js, typescript You can then map to a common structure for all your arrays: const pendencyCountItems = [ ...overviews.filter(o => o.operationType).map(o => ({ key: o.status, subKey: o.operationType })), ...components.filter(o => o.operationType).map(o => ({ key: o.status, subKey: o.operationType })), ...uniquePendencies.map(o => ({ key: o.state, subKey: o.pendencyType })), ] Which you can then group and count: const pendencyCounts = _(pendencyCountItems) .groupBy('key') .mapValues(itemsThisStatus => _.countBy(itemsThisStatus, 'subType')) .value()
{ "domain": "codereview.stackexchange", "id": 45348, "lm_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, react.js, typescript", "url": null }
python, programming-challenge, string-processing Title: Advent of Code 2023 - Day 15: Lens Library Question: Part 1: The task involves initializing the Lava Production Facility using an initialization sequence. The sequence consists of steps, each requiring the application of the Holiday ASCII String Helper algorithm (HASH). The HASH algorithm involves turning a string into a single number in the range 0 to 255. The sum of the results of running the HASH algorithm on each step in the initialization sequence is the solution. The HASH algorithm is a way to turn any string of characters into a single number in the range 0 to 255. To run the HASH algorithm on a string, start with a current value of 0. Then, for each character in the string starting from the beginning: Determine the ASCII code for the current character of the string. Increase the current value by the ASCII code you just determined. Set the current value to itself multiplied by 17. Set the current value to the remainder of dividing itself by 256. For example: rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7 This initialization sequence specifies 11 individual steps; the result of running the HASH algorithm on each of the steps is as follows: rn=1 becomes 30. cm- becomes 253. qp=3 becomes 97. cm=2 becomes 47. qp- becomes 14. pc=4 becomes 180. ot=9 becomes 9. ab=5 becomes 197. pc- becomes 48. pc=6 becomes 214. ot=7 becomes 231. In this example, the sum of these results is 1320. #!/usr/bin/env python3 from pathlib import Path from typing import Iterable import typer def hash_line(line: str) -> int: current = 0 for c in line: current = (current + ord(c)) * 17 % 256 return current def hash(line: str) -> int: return sum(hash_line(pattern) for pattern in line.strip().split(",")) def total_sum(lines: Iterable[str]) -> int: return sum(map(hash, lines))
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing def total_sum(lines: Iterable[str]) -> int: return sum(map(hash, lines)) def main(initialization_sequence: Path) -> None: """Solves Part 1 of Day 15 Advent of Code. See: https://adventofcode.com/2023/day/15""" with open(initialization_sequence) as f: print(total_sum(f)) if __name__ == "__main__": typer.run(main) Part 2: In Part Two, the task extends to configuring lenses in a series of 256 boxes. The initialization sequence specifies operations for inserting or removing lenses from specific boxes. Each lens operation includes a label, an operation character (= or -), and, if applicable, the focal length of the lens. The focusing power of a lens is calculated based on its position in the box, box number, and focal length. The goal is to follow the entire initialization sequence, perform the specified lens operations, and determine the total focusing power of the resulting lens configuration.
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing Inside each box, there are several lens slots that will keep a lens correctly positioned to focus light passing through the box. The side of each box has a panel that opens to allow you to insert or remove lenses as necessary. Along the wall running parallel to the boxes is a large library containing lenses organized by focal length ranging from 1 through 9. The reindeer also brings you a small handheld label printer. The book goes on to explain how to perform each step in the initialization sequence, a process it calls the Holiday ASCII String Helper Manual Arrangement Procedure, or HASHMAP for short. Each step begins with a sequence of letters that indicate the label of the lens on which the step operates. The result of running the HASH algorithm on the label indicates the correct box for that step. The label will be immediately followed by a character that indicates the operation to perform: either an equals sign (=) or a dash (-). If the operation character is a dash (-), go to the relevant box and remove the lens with the given label if it is present in the box. Then, move any remaining lenses as far forward in the box as they can go without changing their order, filling any space made by removing the indicated lens. (If no lens in that box has the given label, nothing happens.) If the operation character is an equals sign (=), it will be followed by a number indicating the focal length of the lens that needs to go into the relevant box; be sure to use the label maker to mark the lens with the label given in the beginning of the step so you can find it later. There are two possible situations: If there is already a lens in the box with the same label, replace the old lens with the new lens: remove the old lens and put the new lens in its place, not moving any other lenses in the box.
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing If there is not already a lens in the box with the same label, add the lens to the box immediately behind any lenses already in the box. Don't move any of the other lenses when you do this. If there aren't any lenses in the box, the new lens goes all the way to the front of the box. Here is the contents of every box after each step in the example initialization sequence above:
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing After "rn=1": Box 0: [rn 1] After "cm-": Box 0: [rn 1] After "qp=3": Box 0: [rn 1] Box 1: [qp 3] After "cm=2": Box 0: [rn 1] [cm 2] Box 1: [qp 3] After "qp-": Box 0: [rn 1] [cm 2] After "pc=4": Box 0: [rn 1] [cm 2] Box 3: [pc 4] After "ot=9": Box 0: [rn 1] [cm 2] Box 3: [pc 4] [ot 9] After "ab=5": Box 0: [rn 1] [cm 2] Box 3: [pc 4] [ot 9] [ab 5] After "pc-": Box 0: [rn 1] [cm 2] Box 3: [ot 9] [ab 5] After "pc=6": Box 0: [rn 1] [cm 2] Box 3: [ot 9] [ab 5] [pc 6] After "ot=7": Box 0: [rn 1] [cm 2] Box 3: [ot 7] [ab 5] [pc 6] All 256 boxes are always present; only the boxes that contain any lenses are shown here. Within each box, lenses are listed from front to back; each lens is shown as its label and focal length in square brackets. To confirm that all of the lenses are installed correctly, add up the focusing power of all of the lenses. The focusing power of a single lens is the result of multiplying together: One plus the box number of the lens in question. The slot number of the lens within the box: 1 for the first lens, 2 for the second lens, and so on. The focal length of the lens. At the end of the above example, the focusing power of each lens is as follows: rn: 1 (box 0) * 1 (first slot) * 1 (focal length) = 1 cm: 1 (box 0) * 2 (second slot) * 2 (focal length) = 4 ot: 4 (box 3) * 1 (first slot) * 7 (focal length) = 28 ab: 4 (box 3) * 2 (second slot) * 5 (focal length) = 40 pc: 4 (box 3) * 3 (third slot) * 6 (focal length) = 72 So, the above example ends up with a total focusing power of 145. #!/usr/bin/env python3 from pathlib import Path from typing import Iterable import typer TOTAL_BOXES = 256 def hash_csv(line: str) -> int: current = 0 for c in line: current = (current + ord(c)) * 17 % 256 return current def remove_slot(csv: str, boxes: list[list[list[str | int]]]) -> None: # label- label, *_ = csv.split("-") box_idx = hash_csv(label)
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing # Loop over a copy to avoid modifying the list whilst iterating over it. for slot in boxes[box_idx][:]: if label == slot[0]: boxes[box_idx].remove(slot) break def add_slot(csv: str, boxes: list[list[list[str | int]]]) -> None: # label=focal_length label, focal_len = csv.split("=") box_idx = hash_csv(label) # If the label already exists, update it. Else, append it to the end. for slot in boxes[box_idx]: if label == slot[0]: slot[1] = int(focal_len) return boxes[box_idx].append([label, int(focal_len)]) def build_boxes(line: str, boxes: list[list[list[str | int]]]) -> None: for csv in line.strip().split(","): add_slot(csv, boxes) if "=" in csv else remove_slot(csv, boxes) def calculate_focusing_pow(boxes: list[list[tuple[str, int]]]) -> int: total = 0 for box_idx, box in enumerate(boxes, 1): total += sum( box_idx * slot_idx * slot[1] for slot_idx, slot in enumerate(box, 1) ) return total def line_focusing_pow(line: str) -> int: boxes = [[] for i in range(TOTAL_BOXES)] build_boxes(line, boxes) return calculate_focusing_pow(boxes) def total_focusing_pow(lines: Iterable[str]) -> int: return sum(map(line_focusing_pow, lines)) def main(initialization_sequence: Path) -> None: """Solves Part 2 of Day 15 Advent of Code. See: https://adventofcode.com/2023/day/15""" with open(initialization_sequence) as f: print(total_focusing_pow(f)) if __name__ == "__main__": typer.run(main) Review Request: General coding comments, style, etc. What are some possible simplifications? What would you do differently?
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing Answer: Part 1 Your code produces the correct answers, so well done! Consequently, I will be commenting mostly on style and choice of names for variables and functions. As I mentioned in a comment to your post, you should avoid assigning names to variables and (especially) functions that are the same as built-in functions. First, when somebody sees a call to hash they may erroneously assume what that function is doing. Moreover, be redefining a built-in function, the potential for breaking existing code that uses that function exists. I would, therefore, rename function hash to hash_step as follows: def hash_step(step: str) -> int: h = 0 for c in step: h = (h + ord(c)) * 17 % 256 return h The input consists of a sequence of comma-delimited "steps" where a single step is, for example, 'gp=3'. This is not a "line", so the function name I have chosen is hash_step and its argument is step because the function computes a hash for a single step. I have also modified loop variable current to h (for "hash") because "current" asks the question "current what?". Using a name such as current_hash would have also been fine. Finally, I don't want any empty lines between the initialization of the hash (i.e. h = 0) and the loop that uses it since the two are closely tied together. Similarly, function name total_sum asks the question "sum of what?" So I would rename this to total_hash. I see no other changes required. But let me pose another possibility depending on how literally you want to take the program description in implementing your code. The description states: The initialization sequence (your puzzle input) is a comma-separated list of steps to start the Lava Production Facility. Ignore newline characters when parsing the initialization sequence.
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing The way I interpret this description is that function total_hash is really the function to be called to solve the problem and it is passed the initialization sequence, which is a comma-separated list of steps, i.e. a string. That this string is coming from an input file is just one possibility. According to this way of thinking the docstring describing what the function does should be moved to the actual function that is doing it! So we then have: #!/usr/bin/env python3 from pathlib import Path from typing import Iterable, Union import typer def hash_step(step: str) -> int: h = 0 for c in step: h = (h + ord(c)) * 17 % 256 return h def part1(initialization_sequence: str) -> int: """Solves Part 1 of Day 15 Advent of Code. See: https://adventofcode.com/2023/day/15 We are passed a comma-delimited sequence of steps for which we must compute the sum of their hashes. The input may contain newline characters that are to be ignored.""" # Ignore any newlines: initialization_sequence = initialization_sequence.replace('\n', '') return sum( hash_step(step) for step in initialization_sequence.split(',') ) if __name__ == "__main__": def main(initialization_sequence_path: Path) -> None: with open(initialization_sequence_path) as f: print(part1(f.read())) typer.run(main)
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing typer.run(main) Part 2 Comments I made about using safer and more descriptive function and variable names apply here. What Is The Optimal Functional Decomposition? I don't know if there is an optimal; it's a balance between maintainability and readability, which are not always the same thing. When performing functional decomposition for solving a programming task one has determine how fine-grained the functions should be. If code is used repeatedly it should clearly be a candidate for standing alone in its own function (for maintainability). Other than that, I would perform a functional decomposition so that the resulting code is is the clearest possible even if it means having larger functions. I have included my code version at the end as an example of not creating functions that are too fine-grained. For example, I could have created individual functions for add_slot or remove_slot, but they would have been "one-liners". In the end that would have made it harder to see the forest for all the trees. Would your code gain in readability without loosing maintainability if you combined some of your functions? This is for you to answer. Efficiency In function remove_slot you are iterating a copy of the list you are potentially removing an element from. But since you immediately stop iterating the list as soon as an element is removed, there was no need in iterating a copy. You also have: label, *_ = csv.split("-") But csv is terminated by the minus sign. Simpler (and better) would be: label = csv[:-1]
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing But csv is terminated by the minus sign. Simpler (and better) would be: label = csv[:-1] Your boxes variable is a list of lists with each sub-list representing the contents of a box. Consequently, your remove_slot function has to perform a linear search to determine whether a label exists and then when you call remove the list has to be searched again and elements moved. Since Python 3.6 insertion order is maintained in a dictionary. Testing whether a label exists is an O(1) operation if that label is a key of a dictionary and then deleting the key is also an O(1) operation. Finally, when you iterate the keys (labels) and values (lenses) of the dictionary you will be doing so in key-insertion order. Consider using a regular expression for parsing a "step": ([a-z]+)([=-])([0-9]*) ([a-z]+) - Capture group 1 consists of one or more lower case letters. ([=-]) - Followed by capture group 2 consisting of either '=' or '-'. ([0-9]*) - Followed by optional digits (not present when capture group2 is '-'). Then you can use method re.finditer over the entire input. Commas and newline characters will never be matched. My Implementation The following code incorporates my suggestions: #!/usr/bin/env python3 import re def hash_label(label: str) -> int: box = 0 for c in label: box = (box + ord(c)) * 17 % 256 return box def part2(initialization_sequence: str) -> int: """Solves Part 2 of Day 15 Advent of Code. See: https://adventofcode.com/2023/day/15""" boxes = [{} for _ in range(256)] rex = re.compile(r'([a-z]+)([=-])([0-9]*)') for m in rex.finditer(initialization_sequence): label, action, lens = m.groups() box = boxes[hash_label(label)] if action == '-': if label in box: del box[label] else: box[label] = int(lens)
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing return sum ( box_number * slot_number * lens for box_number, box in enumerate(boxes, start=1) for slot_number, lens in enumerate(box.values(), start=1) ) if __name__ == "__main__": with open('test.txt') as f: print(part2(f.read()))
{ "domain": "codereview.stackexchange", "id": 45349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
c++, calculator Title: Quadratic equation solution solution searcher Question: Here is a simple Learner practice piece of Code, which supposses to comply and give solutions to a Quadrant Equity problem (requires to give it values of a, b and c for a Quadrant function). Please any tips and Tricks highly welcome, and suggestions of Improving the code. Thanks. #include <iostream> #include <math.h> using namespace std; void main(){ double a, b, c; cin >> a >> b >> c; if(a == 0){ if(b == 0){ if(c == 0){ cout<<"All real numbers are solutions!"; //always zero return 0; } cout<<"No solutions!"; //no soultion Found return 0; } cout<<"Solution x0 is "<< -c / b; // Line equity return 0; } double delta = b*b - 4*a*c; // calculate the derivative for Quadrant if(delta<0){ cout <<"No real solutions!"; //none Found } else if(delta==0){ cout <<"Solution x0 is "<<-b / (2*a); //Double solution } else { cout <<"Solution x1 is "<<( -b - sqrt( delta ) ) / (2*a) << endl; cout <<"Solution x2 is "<<( -b + sqrt( delta ) ) / (2*a); } return 0; }
{ "domain": "codereview.stackexchange", "id": 45350, "lm_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++, calculator", "url": null }
c++, calculator Answer: Let's start with one formal advise: Your formatting is inconsistent. In particular, placement of spaces around operators is inconsistent. Use your IDE's autoformatter. Then, there are a few cases where comments basically just reflect the code. For example, cout<<"No solutions!"; //no soultion Found. The comment contains two typos and removing it would improve your code. As a general advise, don't document what the code does. Sparingly document how the code does something (e.g. a link to a page explaining how to solve quadratic equations) somewhere would help. Always document why your code does something the way it does, though there is little to explain in your code. There is one thing in your workflow that's probably wrong. You declare void main() (which in and of itself is wrong), but then return values from it. Usually, the compiler will tell you about such nonsense, but I guess you didn't compile with warnings, did you? Make sure you enable warnings and understand them. Finally, some nitpicking: In the beginning, you read some input. In case you target a human, they will never know what these values are. Actually, even reading the code, it's unclear what a, b, and c are. Only from looking deeper I see that they are polynomial factors. Input can fail. Using e.g. if (!(cin >> a >> b >> c)) return EXIT_FAILURE; would make your program more robust. delta could be a constant. Making things constant makes it clear to the reader that the value never changes and also guarantees that you don't change it accidentally. using namespace std will pollute your namespace. All you need is cin, cout, endl and sqrt. Put an endline at the end of every line of output. For that, just use '\n'.
{ "domain": "codereview.stackexchange", "id": 45350, "lm_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++, calculator", "url": null }
css, react.js Title: Icon styling in Tailwind/React Question: This is a React icon component, with a few Tailwind classes. This icon component looks as follows in the UI. The name LongIcon is to differentiate with smaller, fully round icons that are used elsewhere. Normal: Hovered: I'm using flex to center the icon SVG inside the green background. import Image from 'next/image'; import React from 'react'; export default function LongIcon({ type }: { type: string }) { return ( // flex used to center the type icon inside the colored div <div className={` ${type} h-[30px] w-[80px] p-1 flex justify-between rounded-md transition-all hover:saturate-200 hover:scale-110`} > {/* Capitalize type */} <span className='text-white font-medium'>{type.replace(/\b\w/, c => c.toUpperCase())}</span> <Image src={`/type-icons/${type}.svg`} alt={type} title={type} width={30 * 0.6} height={30 * 0.6} /> </div> ); } Answer: I have two main observations: I'm not a big fan of the baked-in capitalization. For one, even in English title case not all words should be capitalized. And if the application is ever translated there are languages in which title case may be inappropriate. In my opinion the label should be capitalized correctly to begin with. If you do keep it, you should consider using the CSS style text-transformation: capitalize (Tailwind class capitalize) instead, or at the very least define it as a separate function outside the component to make the HTML less busy. Hover effects usually suggest to the user that the element is clickable. Since this component otherwise doesn't seem interactive, this may be confusing for the user.
{ "domain": "codereview.stackexchange", "id": 45351, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "css, react.js", "url": null }
c++, image, template, classes, variadic Title: An Updated Multi-dimensional Image Data Structure with Variadic Template Functions in C++ Question: This is a follow-up question for Multi-dimensional Image Data Structure with Variadic Template Functions in C++. Considering the suggestion from G. Sliepen: Make everything work for more than 5 dimensions I can see why you stopped at 5 dimensions if you still have to manually write the code for each number of dimensions separately. Just spend a little bit of time to figure out how to write this in a generic way, then you'll actually have to do less typing and make the code work for any number of dimensions. Whenever you have to loop over a parameter pack, you can always do this: auto function = [&](auto index) { ... }; (function(indexInput), ...); Now function() will be called for every element in indexInput in succession. In that lambda you can do anything you want, including incrementing a loop counter. So use that to build up the index you need to read from image_data. This is left as an excercise for the reader. I am trying to do the excercise of looping over parameter packs with the given structure. The experimental implementation Image Class Implementation // image.h namespace TinyDIP { template <typename ElementT> class Image { public: Image() = default; template<std::same_as<std::size_t>... Sizes> Image(Sizes... sizes): size{sizes...}, image_data((1 * ... * sizes)) {} template<std::ranges::input_range Range, std::same_as<std::size_t>... Sizes> Image(const Range& input, Sizes... sizes): size{sizes...}, image_data(begin(input), end(input)) { if (image_data.size() != (1 * ... * sizes)) { throw std::runtime_error("Image data input and the given size are mismatched!"); } }
{ "domain": "codereview.stackexchange", "id": 45352, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight) { size.reserve(2); size.emplace_back(newWidth); size.emplace_back(newHeight); if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); // Reference: https://stackoverflow.com/a/51706522/6667035 } Image(const std::vector<std::vector<ElementT>>& input) { size.reserve(2); size.emplace_back(input[0].size()); size.emplace_back(input.size()); for (auto& rows : input) { image_data.insert(image_data.end(), std::ranges::begin(input), std::ranges::end(input)); // flatten } return; } template<typename... Args> constexpr ElementT& at(const Args... indexInput) { checkBoundary(indexInput...); constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } std::size_t parameter_pack_index = 0; std::size_t image_data_index = 0; auto function = [&](auto index) { std::size_t m = 1; for(std::size_t i = 0; i < parameter_pack_index; ++i) { m*=size[i]; } image_data_index+=(index * m); parameter_pack_index = parameter_pack_index + 1; }; (function(indexInput), ...); return image_data[image_data_index]; }
{ "domain": "codereview.stackexchange", "id": 45352, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic template<typename... Args> constexpr ElementT const& at(const Args... indexInput) const { checkBoundary(indexInput...); constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } std::size_t parameter_pack_index = 0; std::size_t image_data_index = 0; auto function = [&](auto index) { std::size_t m = 1; for(std::size_t i = 0; i < parameter_pack_index; ++i) { m*=size[i]; } image_data_index+=(index * m); parameter_pack_index = parameter_pack_index + 1; }; (function(indexInput), ...); return image_data[image_data_index]; } constexpr std::size_t getDimensionality() const noexcept { return size.size(); } constexpr std::size_t getWidth() const noexcept { return size[0]; } constexpr std::size_t getHeight() const noexcept { return size[1]; } constexpr auto getSize() noexcept { return size; } std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data
{ "domain": "codereview.stackexchange", "id": 45352, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic void print(std::string separator = "\t", std::ostream& os = std::cout) const { if(size.size() == 1) { for(std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x) << separator; } os << "\n"; } else if(size.size() == 2) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; } else if (size.size() == 3) { for(std::size_t z = 0; z < size[2]; ++z) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y, z) << separator; } os << "\n"; } os << "\n"; } os << "\n"; } }
{ "domain": "codereview.stackexchange", "id": 45352, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }
c++, image, template, classes, variadic // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } void setAllValue(const ElementT input) { std::fill(image_data.begin(), image_data.end(), input); } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; rhs.print(separator, os); return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; } Image<ElementT>& operator-=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 45352, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, image, template, classes, variadic", "url": null }