text
stringlengths
1
2.12k
source
dict
collections, c++20, circular-list (I've also omitted the initialisers that duplicate the in-class initialisers, as they are just clutter). It would be nice if the move-constructor, when moving from one allocator to another, could reduce its memory overheads. I don't think this is possible whilst retaining the strong exception guarantee, though. If we can't, we could at least reduce duplication, by copy-construct and swap: template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(cqueue &&other, const_alloc_reference alloc) { if (alloc == other.mAllocator) { swap(other); } else { cqueue q{other, alloc}; swap(q); cqueue{std::move(other)}; // clear the source queue } } (That final clearing of source was needed to make the test pass - that might be over-testing, since we should only care that the moved-from object is sufficiently valid to be destructed). Member functions Because operator=() uses copy-and-swap, there's no need to test for self-assignment: template<std::copyable T, typename Allocator> constexpr auto gto::cqueue<T, Allocator>::operator=(const cqueue &other) -> cqueue& { cqueue tmp(other); swap(tmp); return *this; }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list Similarly, swap() itself functions perfectly well for self-swap, so we can eliminate the condition there. Note also that the trailing return type allows us to use a simpler name; that becomes especially valuable for those functions returning a size_type. If an exception is thrown in resize(), we should destruct the objects so far in reverse order of construction, but we're doing it in forward order. I don't know if this ever makes a practical difference, but it's not hard to change. Consider using a smart pointer for the storage, to reduce the cleanup we need in the catch clause: template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::resize(size_type len) { auto const deleter = [&](value_type* p){ allocator_traits::deallocate(mAllocator, p, len); }; std::unique_ptr<value_type, decltype(deleter)> utmp{allocator_traits::allocate(mAllocator, len), deleter}; auto *const tmp = utmp.get(); ⋮ // deallocate mData allocator_traits::deallocate(mAllocator, mData, mReserved); // assign new content mData = utmp.release(); mReserved = len; mFront = 0; } Modified code Sorry my indentation differs from the original; I didn't bother reconfiguring my editor from its usual settings. #include <memory> #include <limits> #include <utility> #include <concepts> #include <algorithm> #include <stdexcept> namespace gto { /** * @brief Circular queue. * @details Iterators are invalidated by: * push(), push_front(), emplace(), pop(), pop_back(), reserve(), * shrink_to_fit(), reset() and clear(). * @see https://en.wikipedia.org/wiki/Circular_buffer * @see https://github.com/torrentg/cqueue * @note This class is not thread-safe. * @version 1.1.0 */ template<std::copyable T, typename Allocator = std::allocator<T>> class cqueue {
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list template<typename U> class iter { public: using iterator_category = std::random_access_iterator_tag; using value_type = U; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; private: friend class iter<std::add_const_t<value_type>>; using size_type = std::size_t; using queue_type = std::conditional_t<std::is_const_v<value_type>, const cqueue, cqueue>; queue_type *queue = nullptr; difference_type pos = 0; auto cast(difference_type n) const { return (n < 0 ? queue->size() : static_cast<size_type>(n)); } auto size() const { return static_cast<difference_type>(queue->size()); } auto clamp(difference_type p) const { return std::clamp<difference_type>(p, -1, size()); } public: explicit iter(queue_type *o, difference_type p = 0) : queue{o}, pos{clamp(p)} {} iter(const iter<std::remove_const_t<value_type>>& other) requires std::is_const_v<value_type> : queue{other.queue}, pos{other.pos} {} iter(const iter<value_type>& other) = default; reference operator*() { return queue->operator[](cast(pos)); } pointer operator->() { return &(queue->operator[](cast(pos))); } reference operator[](difference_type rhs) const { return queue->operator[](cast(pos + rhs)); }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list auto operator<=>(const iter &rhs) const { return queue == rhs.queue ? pos <=> rhs.pos : std::partial_ordering::unordered; } auto operator==(const iter &rhs) const { return *this <=> rhs == 0; } iter& operator++() { return *this += 1; } iter& operator--() { return *this += -1; } [[nodiscard]] iter operator++(int) { iter tmp{queue, pos}; ++*this; return tmp; } [[nodiscard]] iter operator--(int) { iter tmp{queue, pos}; --*this; return tmp; } auto& operator+=(difference_type rhs) { pos = clamp(pos + rhs); return *this; } auto& operator-=(difference_type rhs) { pos = clamp(pos - rhs); return *this; } auto operator+(difference_type rhs) const { return iter{queue, pos + rhs}; } auto operator-(difference_type rhs) const { return iter{queue, pos - rhs}; } friend iter operator+(difference_type lhs, const iter &rhs) { return iter{rhs.queue, lhs + rhs.pos}; } friend iter operator-(difference_type lhs, const iter &rhs) { return iter{rhs.queue, lhs - rhs.pos}; } auto operator-(const iter &rhs) const { return pos - rhs.pos; } }; public: // declarations // Aliases using value_type = T; using reference = value_type &; using const_reference = const value_type &; using pointer = T *; using const_pointer = const pointer; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using allocator_type = Allocator; using const_alloc_reference = const allocator_type &; using iterator = iter<T>; using const_iterator = iter<const T>; private: // declarations using allocator_traits = std::allocator_traits<allocator_type>; private: // static members //! Capacity increase factor. static constexpr size_type GROWTH_FACTOR = 2; //! Default initial capacity (power of 2). static constexpr size_type DEFAULT_RESERVED = 8; private: // members
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list private: // members //! Memory allocator. [[no_unique_address]] allocator_type mAllocator = {}; //! Buffer. pointer mData = nullptr; //! Buffer size. size_type mReserved = 0; //! Maximum number of elements (always > 0). size_type mCapacity = 0; //! Index representing first entry (0 <= mFront < mReserved). size_type mFront = 0; //! Number of entries in the queue (empty = 0, full = mReserved). size_type mLength = 0; private: // methods //! Convert from pos to index (throw exception if out-of-bounds). constexpr size_type getCheckedIndex(size_type pos) const noexcept(false); //! Convert from pos to index. constexpr size_type getUncheckedIndex(size_type pos) const noexcept; //! Compute memory size to reserve. constexpr size_type getNewMemoryLength(size_type n) const noexcept; //! Resize buffer. constexpr void resizeIfRequired(size_type n); //! Resize buffer. void resize(size_type n); //! Clear and dealloc memory (preserve capacity and allocator). void reset() noexcept; public: // static methods //! Maximum capacity the container is able to hold. static constexpr size_type max_capacity() noexcept { return (std::numeric_limits<difference_type>::max()); } public: // methods //! Constructor. constexpr explicit cqueue(const_alloc_reference alloc = Allocator()) : cqueue(0, alloc) {} //! Constructor (capacity=0 means unlimited). constexpr explicit cqueue(size_type capacity, const_alloc_reference alloc = Allocator()); //! Copy constructor. constexpr cqueue(const cqueue &other); //! Copy constructor with allocator. constexpr cqueue(const cqueue &other, const_alloc_reference alloc); //! Move constructor. constexpr cqueue(cqueue &&other) noexcept { this->swap(other); } //! Move constructor. constexpr cqueue(cqueue &&other, const_alloc_reference alloc); //! Destructor. ~cqueue() noexcept { reset(); };
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list //! Copy assignment. constexpr cqueue & operator=(const cqueue &other); //! Move assignment. constexpr cqueue & operator=(cqueue &&other) { this->swap(other); return *this; } //! Return container allocator. constexpr allocator_type get_allocator() const noexcept { return mAllocator; } //! Return queue capacity. constexpr size_type capacity() const noexcept { return (mCapacity == max_capacity() ? 0 : mCapacity); } //! Return the number of items. constexpr size_type size() const noexcept { return mLength; } //! Current reserved size (numbers of items). constexpr size_type reserved() const noexcept { return mReserved; } //! Check if there are items in the queue. constexpr bool empty() const noexcept { return (mLength == 0); } //! Return the first element. constexpr const_reference front() const { return operator[](0); } //! Return the first element. constexpr reference front() { return operator[](0); } //! Return the last element. constexpr const_reference back() const { return operator[](mLength-1); } //! Return the last element. constexpr reference back() { return operator[](mLength-1); } //! Insert an element at the end. constexpr void push(T val); //! Insert an element at the front. constexpr void push_front(const T &val); //! Insert an element at the front. constexpr void push_front(T &&val); //! Construct and insert an element at the end. template <class... Args> constexpr void emplace(Args&&... args); //! Remove the front element. constexpr bool pop(); //! Remove the back element. constexpr bool pop_back(); //! Returns a reference to the element at position n. constexpr reference operator[](size_type n) { return mData[getCheckedIndex(n)]; } //! Returns a const reference to the element at position n. constexpr const_reference operator[](size_type n) const { return mData[getCheckedIndex(n)]; }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list //! Returns an iterator to the first element. constexpr iterator begin() noexcept { return iterator(this, 0); } //! Returns an iterator to the element following the last element. constexpr iterator end() noexcept { return iterator(this, static_cast<difference_type>(size())); } //! Returns an iterator to the first element. constexpr const_iterator begin() const noexcept { return const_iterator(this, 0); } //! Returns an iterator to the element following the last element. constexpr const_iterator end() const noexcept { return const_iterator(this, static_cast<difference_type>(size())); } //! Clear content. void clear() noexcept; //! Swap content. constexpr void swap (cqueue &x) noexcept; //! Ensure buffer size. constexpr void reserve(size_type n); //! Shrink reserved memory to current size. constexpr void shrink_to_fit(); }; } // namespace gto /** * @param[in] capacity Container capacity. * @param[in] alloc Allocator to use. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(size_type capacity, const_alloc_reference alloc) : mAllocator(alloc), mCapacity{capacity == 0 ? max_capacity() : capacity} { if (capacity > max_capacity()) { throw std::length_error("cqueue max capacity exceeded"); } } /** * @param[in] other Queue to copy. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other) : cqueue{other, allocator_traits::select_on_container_copy_construction(other.get_allocator())} { } /** * @param[in] other Queue to copy. * @param[in] alloc Allocator to use. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other, const_alloc_reference alloc) : mAllocator{alloc}, mCapacity{other.mCapacity} { resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(other[i]); } }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list /** * @param[in] other Queue to copy. * @param[in] alloc Allocator to use */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(cqueue &&other, const_alloc_reference alloc) { if (alloc == other.mAllocator) { swap(other); } else { cqueue q{other, alloc}; swap(q); cqueue{std::move(other)}; // clear the source queue } } /** * @param[in] other Queue to copy. */ template<std::copyable T, typename Allocator> constexpr auto gto::cqueue<T, Allocator>::operator=(const cqueue &other) -> cqueue& { cqueue tmp(other); swap(tmp); return *this; } /** * @param[in] num Element position. * @return Index in buffer. */ template<std::copyable T, typename Allocator> constexpr auto gto::cqueue<T, Allocator>::getUncheckedIndex(size_type pos) const noexcept -> size_type { return (mFront + pos) % (mReserved == 0 ? 1 : mReserved); } /** * @param[in] num Element position. * @return Index in buffer. * @exception std::out_of_range Invalid position. */ template<std::copyable T, typename Allocator> constexpr auto gto::cqueue<T, Allocator>::getCheckedIndex(size_type pos) const noexcept(false) -> size_type { if (pos >= mLength) { throw std::out_of_range("cqueue access out-of-range"); } return getUncheckedIndex(pos); } /** * @details Remove all elements. */ template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::clear() noexcept { for (size_type i = 0; i < mLength; ++i) { size_type index = getUncheckedIndex(i); allocator_traits::destroy(mAllocator, mData + index); } mFront = 0; mLength = 0; } /** * @details Remove all elements and frees memory. */ template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::reset() noexcept { clear(); allocator_traits::deallocate(mAllocator, mData, mReserved); mData = nullptr; mReserved = 0; }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list /** * @details Swap content with another same-type cqueue. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::swap(cqueue &other) noexcept { if constexpr (allocator_traits::propagate_on_container_swap::value) { std::swap(mAllocator, other.mAllocator); } std::swap(mData, other.mData); std::swap(mFront, other.mFront); std::swap(mLength, other.mLength); std::swap(mReserved, other.mReserved); std::swap(mCapacity, other.mCapacity); } /** * @brief Compute the new buffer size. * @param[in] n New queue size. */ template<std::copyable T, typename Allocator> constexpr auto gto::cqueue<T, Allocator>::getNewMemoryLength(size_type n) const noexcept -> size_type { size_type ret = (mReserved == 0 ? std::min(mCapacity, DEFAULT_RESERVED) : mReserved); while (ret < n) { ret *= GROWTH_FACTOR; } return std::min(ret, mCapacity); } /** * @param[in] n Expected future queue size. * @exception std::length_error Capacity exceeded. * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::resizeIfRequired(size_type n) noexcept(false) { if (n < mReserved) { [[likely]] return; } else if (n > mCapacity) { [[unlikely]] throw std::length_error("cqueue capacity exceeded"); } else { size_type len = getNewMemoryLength(n); resize(len); } } /** * @param[in] n Expected future queue size. * @exception std::length_error Capacity exceeded. * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::reserve(size_type n) { if (n < mReserved) { return; } else if (n > mCapacity) { throw std::length_error("cqueue capacity exceeded"); } else { resize(n); } }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list /** * @details Memory is not shrink if current length below DEFAULT_RESERVED. * @exception std::length_error Capacity exceeded. * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::shrink_to_fit() { if (mLength == 0 || mLength == mReserved || mLength <= DEFAULT_RESERVED) { return; } else { resize(mLength); } } /** * @param[in] n New reserved size. * @details Provides strong exception guarantee. * @see https://en.cppreference.com/w/cpp/language/exceptions#Exception_safety * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::resize(size_type len) { auto const deleter = [&](value_type* p){ allocator_traits::deallocate(mAllocator, p, len); }; std::unique_ptr<value_type, decltype(deleter)> utmp{allocator_traits::allocate(mAllocator, len), deleter}; auto *const tmp = utmp.get(); if constexpr (std::is_nothrow_move_constructible<T>::value) { // move elements from mData to tmp for (size_type i = 0; i < mLength; ++i) { size_type index = getUncheckedIndex(i); allocator_traits::construct(mAllocator, tmp + i, std::move(mData[index])); } } else { // copy elements from mData to tmp size_type i = 0; try { for (i = 0; i < mLength; ++i) { size_type index = getUncheckedIndex(i); allocator_traits::construct(mAllocator, tmp + i, mData[index]); } } catch (...) { while (i-- > 0) { allocator_traits::destroy(mAllocator, tmp + i); } throw; } } // destroy mData elements for (size_type j = 0; j < mLength; ++j) { size_type index = getUncheckedIndex(j); allocator_traits::destroy(mAllocator, mData + index); } // deallocate mData allocator_traits::deallocate(mAllocator, mData, mReserved);
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list // deallocate mData allocator_traits::deallocate(mAllocator, mData, mReserved); // assign new content mData = utmp.release(); mReserved = len; mFront = 0; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push(T val) { resizeIfRequired(mLength + 1); size_type index = getUncheckedIndex(mLength); allocator_traits::construct(mAllocator, mData + index, std::move(val)); ++mLength; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push_front(T val) { resizeIfRequired(mLength + 1); size_type index = (mLength == 0 ? 0 : (mFront == 0 ? mReserved : mFront) - 1); allocator_traits::construct(mAllocator, mData + index, std::move(val)); mFront = index; ++mLength; } /** * @param[in] args Arguments of the new item. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> template <class... Args> constexpr void gto::cqueue<T, Allocator>::emplace(Args&&... args) { resizeIfRequired(mLength + 1); size_type index = getUncheckedIndex(mLength); allocator_traits::construct(mAllocator, mData + index, std::forward<Args>(args)...); ++mLength; } /** * @return true = an element was erased, false = no elements in the queue. */ template<std::copyable T, typename Allocator> constexpr bool gto::cqueue<T, Allocator>::pop() { if (mLength == 0) { return false; } allocator_traits::destroy(mAllocator, mData + mFront); mFront = getUncheckedIndex(1); --mLength; return true; }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list /** * @return true = an element was erased, false = no elements in the queue. */ template<std::copyable T, typename Allocator> constexpr bool gto::cqueue<T, Allocator>::pop_back() { if (mLength == 0) { return false; } size_type index = getUncheckedIndex(mLength - 1); allocator_traits::destroy(mAllocator, mData + index); --mLength; return true; } ```
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
c, arduino Title: Simulate 2-bit half adder with 2-bit inputs on Arduino without using logic gates Question: You are to simulate a 2-bit half adder. You are not required to implement a real 2-bit half adder using logic gates; you are going to implement a black-box system using the microcontroller that functions as a 2-bit half adder. Your system will have 4 inputs (2 for the first 2-bit number, and another 2 for the second 2-bit number), and 2 outputs (2-bit output for the sum). Inputs: Each input is controlled via a separate push-down button. The inputs should be toggled each time the buttons are released,as opposed to being LOW while the button is released, and HIGH while the button is pushed. The initial values of inputs will be LOW. Outputs: Each output is controlled via a separate LED. The LED will be off while the output is LOW, and on while the output is HIGH. Since the states of the inputs will be invisible to the naked eye, you are to represent the input states with additional LEDs as well. byte numberOneFirstDigit = 3; byte numberOneSecondDigit = 2; byte numberTwoFirstDigit = 5; byte numberTwoSecondDigit = 4; byte sumFirstDigit=7; byte sumSecondDigit=6; byte carryDigit=12; byte numberOneFirstDigitButton = 9; byte numberOneSecondDigitButton = 8; byte numberTwoFirstDigitButton = 11; byte numberTwoSecondDigitButton= 10; void setup() { pinMode(numberOneFirstDigit,OUTPUT); pinMode(numberOneSecondDigit,OUTPUT); pinMode(numberTwoFirstDigit,OUTPUT); pinMode(numberTwoSecondDigit,OUTPUT); pinMode(sumFirstDigit,OUTPUT); pinMode(sumSecondDigit,OUTPUT); pinMode(carryDigit,OUTPUT); pinMode(numberOneFirstDigitButton,INPUT); pinMode(numberOneSecondDigitButton,INPUT); pinMode(numberTwoFirstDigitButton,INPUT); pinMode(numberTwoSecondDigitButton,INPUT); }
{ "domain": "codereview.stackexchange", "id": 44101, "lm_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, arduino", "url": null }
c, arduino void loop() { byte numberOneFirstDigit_state = digitalRead(numberOneFirstDigitButton); byte numberOneSecondDigit_state = digitalRead(numberOneSecondDigitButton); byte numberTwoFirstDigit_state = digitalRead(numberTwoFirstDigitButton); byte numberTwoSecondDigit_state = digitalRead(numberTwoSecondDigitButton); if(numberOneSecondDigit_state == LOW && numberOneFirstDigit_state == LOW && numberTwoSecondDigit_state == LOW && numberTwoFirstDigit_state == LOW) { digitalWrite(numberOneFirstDigit , LOW); digitalWrite(numberOneSecondDigit , LOW); digitalWrite(numberTwoFirstDigit , LOW); digitalWrite(numberTwoSecondDigit , LOW); digitalWrite(sumFirstDigit , LOW); digitalWrite(sumSecondDigit , LOW); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == LOW && numberOneFirstDigit_state == LOW && numberTwoSecondDigit_state == LOW && numberTwoFirstDigit_state == HIGH) { digitalWrite(numberOneFirstDigit , LOW); digitalWrite(numberOneSecondDigit , LOW); digitalWrite(numberTwoFirstDigit , HIGH); digitalWrite(numberTwoSecondDigit , LOW); digitalWrite(sumFirstDigit , HIGH); digitalWrite(sumSecondDigit , LOW); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == LOW && numberOneFirstDigit_state == LOW && numberTwoSecondDigit_state == HIGH && numberTwoFirstDigit_state == LOW) { digitalWrite(numberOneFirstDigit , LOW); digitalWrite(numberOneSecondDigit , LOW); digitalWrite(numberTwoFirstDigit , LOW); digitalWrite(numberTwoSecondDigit , HIGH); digitalWrite(sumFirstDigit , LOW); digitalWrite(sumSecondDigit , HIGH); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == LOW && numberOneFirstDigit_state == LOW && numberTwoSecondDigit_state == HIGH && numberTwoFirstDigit_state == HIGH) { digitalWrite(numberOneFirstDigit , LOW);
{ "domain": "codereview.stackexchange", "id": 44101, "lm_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, arduino", "url": null }
c, arduino { digitalWrite(numberOneFirstDigit , LOW); digitalWrite(numberOneSecondDigit , LOW); digitalWrite(numberTwoFirstDigit , HIGH); digitalWrite(numberTwoSecondDigit , HIGH); digitalWrite(sumFirstDigit , HIGH); digitalWrite(sumSecondDigit , HIGH); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == LOW && numberOneFirstDigit_state == HIGH && numberTwoSecondDigit_state == LOW && numberTwoFirstDigit_state == LOW) { digitalWrite(numberOneFirstDigit , HIGH); digitalWrite(numberOneSecondDigit , LOW); digitalWrite(numberTwoFirstDigit , LOW); digitalWrite(numberTwoSecondDigit , LOW); digitalWrite(sumFirstDigit , HIGH); digitalWrite(sumSecondDigit , LOW); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == LOW && numberOneFirstDigit_state == HIGH && numberTwoSecondDigit_state == LOW && numberTwoFirstDigit_state == HIGH) { digitalWrite(numberOneFirstDigit , HIGH); digitalWrite(numberOneSecondDigit , LOW); digitalWrite(numberTwoFirstDigit , HIGH); digitalWrite(numberTwoSecondDigit , LOW); digitalWrite(sumFirstDigit , LOW); digitalWrite(sumSecondDigit , HIGH); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == LOW && numberOneFirstDigit_state == HIGH && numberTwoSecondDigit_state == HIGH && numberTwoFirstDigit_state == LOW) { digitalWrite(numberOneFirstDigit , HIGH); digitalWrite(numberOneSecondDigit , LOW); digitalWrite(numberTwoFirstDigit , LOW); digitalWrite(numberTwoSecondDigit , HIGH); digitalWrite(sumFirstDigit , HIGH); digitalWrite(sumSecondDigit , HIGH); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == LOW && numberOneFirstDigit_state == HIGH && numberTwoSecondDigit_state == HIGH && numberTwoFirstDigit_state == HIGH) { digitalWrite(numberOneFirstDigit , HIGH);
{ "domain": "codereview.stackexchange", "id": 44101, "lm_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, arduino", "url": null }
c, arduino { digitalWrite(numberOneFirstDigit , HIGH); digitalWrite(numberOneSecondDigit , LOW); digitalWrite(numberTwoFirstDigit , HIGH); digitalWrite(numberTwoSecondDigit , HIGH); digitalWrite(sumFirstDigit , LOW); digitalWrite(sumSecondDigit , LOW); digitalWrite(carryDigit , HIGH); } else if(numberOneSecondDigit_state == HIGH && numberOneFirstDigit_state == LOW && numberTwoSecondDigit_state == LOW && numberTwoFirstDigit_state == LOW) { digitalWrite(numberOneFirstDigit , LOW); digitalWrite(numberOneSecondDigit , HIGH); digitalWrite(numberTwoFirstDigit , LOW); digitalWrite(numberTwoSecondDigit , LOW); digitalWrite(sumFirstDigit , LOW); digitalWrite(sumSecondDigit , HIGH); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == HIGH && numberOneFirstDigit_state == LOW && numberTwoSecondDigit_state == LOW && numberTwoFirstDigit_state == HIGH) { digitalWrite(numberOneFirstDigit , LOW); digitalWrite(numberOneSecondDigit , HIGH); digitalWrite(numberTwoFirstDigit , HIGH); digitalWrite(numberTwoSecondDigit , LOW); digitalWrite(sumFirstDigit , HIGH); digitalWrite(sumSecondDigit , HIGH); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == HIGH && numberOneFirstDigit_state == LOW && numberTwoSecondDigit_state == HIGH && numberTwoFirstDigit_state == LOW) { digitalWrite(numberOneFirstDigit , LOW); digitalWrite(numberOneSecondDigit , HIGH); digitalWrite(numberTwoFirstDigit , LOW); digitalWrite(numberTwoSecondDigit , HIGH); digitalWrite(sumFirstDigit , LOW); digitalWrite(sumSecondDigit , LOW); digitalWrite(carryDigit , HIGH); } else if(numberOneSecondDigit_state == HIGH && numberOneFirstDigit_state == LOW && numberTwoSecondDigit_state == HIGH && numberTwoFirstDigit_state == HIGH) { digitalWrite(numberOneFirstDigit , LOW);
{ "domain": "codereview.stackexchange", "id": 44101, "lm_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, arduino", "url": null }
c, arduino { digitalWrite(numberOneFirstDigit , LOW); digitalWrite(numberOneSecondDigit , HIGH); digitalWrite(numberTwoFirstDigit , HIGH); digitalWrite(numberTwoSecondDigit , HIGH); digitalWrite(sumFirstDigit , HIGH); digitalWrite(sumSecondDigit , LOW); digitalWrite(carryDigit , HIGH); } else if(numberOneSecondDigit_state == HIGH && numberOneFirstDigit_state == HIGH && numberTwoSecondDigit_state == LOW && numberTwoFirstDigit_state == LOW) { digitalWrite(numberOneFirstDigit , HIGH); digitalWrite(numberOneSecondDigit , HIGH); digitalWrite(numberTwoFirstDigit , LOW); digitalWrite(numberTwoSecondDigit , LOW); digitalWrite(sumFirstDigit , HIGH); digitalWrite(sumSecondDigit , HIGH); digitalWrite(carryDigit , LOW); } else if(numberOneSecondDigit_state == HIGH && numberOneFirstDigit_state == HIGH && numberTwoSecondDigit_state == LOW && numberTwoFirstDigit_state == HIGH) { digitalWrite(numberOneFirstDigit , HIGH); digitalWrite(numberOneSecondDigit , HIGH); digitalWrite(numberTwoFirstDigit , HIGH); digitalWrite(numberTwoSecondDigit , LOW); digitalWrite(sumFirstDigit , LOW); digitalWrite(sumSecondDigit , LOW); digitalWrite(carryDigit , HIGH); } else if(numberOneSecondDigit_state == HIGH && numberOneFirstDigit_state == HIGH && numberTwoSecondDigit_state == HIGH && numberTwoFirstDigit_state == LOW) { digitalWrite(numberOneFirstDigit , HIGH); digitalWrite(numberOneSecondDigit , HIGH); digitalWrite(numberTwoFirstDigit , LOW); digitalWrite(numberTwoSecondDigit , HIGH); digitalWrite(sumFirstDigit , HIGH); digitalWrite(sumSecondDigit , LOW); digitalWrite(carryDigit , HIGH); } else if(numberOneSecondDigit_state == HIGH && numberOneFirstDigit_state == HIGH && numberTwoSecondDigit_state == HIGH && numberTwoFirstDigit_state == HIGH) { digitalWrite(numberOneFirstDigit , HIGH);
{ "domain": "codereview.stackexchange", "id": 44101, "lm_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, arduino", "url": null }
c, arduino { digitalWrite(numberOneFirstDigit , HIGH); digitalWrite(numberOneSecondDigit , HIGH); digitalWrite(numberTwoFirstDigit , HIGH); digitalWrite(numberTwoSecondDigit , HIGH); digitalWrite(sumFirstDigit , LOW); digitalWrite(sumSecondDigit , HIGH); digitalWrite(carryDigit , HIGH); } }
{ "domain": "codereview.stackexchange", "id": 44101, "lm_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, arduino", "url": null }
c, arduino I have showed the question and the circuit I did. I am open to any suggestions to improve my code (and maybe the circuit). I want a program which is not too many lines. Answer: Avoid code duplication Your implementation is like that of a truth table: for all possible inputs, you have pre-calculated the output. That is one way of doing it. But instead of having lots of if-then statements, implement it using a look-up table. This is quite easy if you pack all the bits in a single integer: static const byte table[16] = { /* 0b0000 -> */ 0b000, /* 0b0001 -> */ 0b001, /* 0b0010 -> */ 0b010, ... /* 0b1101 -> */ 0b100, /* 0b1110 -> */ 0b101, /* 0b1111 -> */ 0b110, }; Then in loop(), you just need to do this (un)packing using a combination of bit shifting, OR and AND operations: loop() { byte input = digitalRead(numberOneFirstDigitButton) << 0 | digitalRead(numberOneSecondDigitButton) << 1 | digitalRead(numberTwoFirstDigitButton) << 2 | digitalRead(numberTwoSecondDigitButton) << 3; byte result = table[input]; digitalWrite(numberOneFirstDigit, (input >> 0) & 1); digitalWrite(numberOneSecondDigit, (input >> 1) & 1); digitalWrite(numberTwoFirstDigit, (input >> 2) & 1); digitalWrite(numberTwoSecondDigit, (input >> 3) & 1); digitalWrite(sumFirstDigit, (result >> 0) & 1); digitalWrite(sumSecondDigit, (result >> 1) & 1); digitalWrite(carryDigit, (result >> 2) & 1); }
{ "domain": "codereview.stackexchange", "id": 44101, "lm_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, arduino", "url": null }
c, arduino Note how this removes a huge amount of code duplication, which makes the code easier to read and easier to maintain. The implementation using a table has a counterpart in digital logic, and that is using a ROM chip to implement combinatorial logic. Alternatively, you can also implement this by parsing the input as two int values, adding them together, and then writing the result back to the output pins: unsigned int numberOne = digitalRead(numberOneFirstDigitButton) << 0 | digitalRead(numberOneSecondDigitButton) << 1; unsigned int numberTwo = digitalRead(numberTwoFirstDigitButton) << 0 | digitalRead(numberTwoSecondDigitButton) << 1; unsigned int result = numberOne + numberTwo; digitalWrite(sumFirstDigit, (result >> 0) & 1)); digitalWrite(sumSecondDigit, (result >> 1) & 1)); digitalWrite(carryDigit, (result >> 2) & 1)); This avoids needing to make a table. Make constants static const or even static constexpr The constants used for the pin numbers, like numberOneFirstDigit, are stored in non-const variables. It is better to make them const, or even better, constexpr. Also, make it a habit of marking constants and functions that don't have to be accessed by anything outside of the current source file as static. Both of these things can allow the compiler to generate more optimal code (also in size), and const will ensure the compiler generates an error if you accidentally do write to one of these constants. So: static constexpr byte numberOneFirstDigit = 3; ...
{ "domain": "codereview.stackexchange", "id": 44101, "lm_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, arduino", "url": null }
c# Title: Printing hex dump of a byte array Question: The goal is readabilty. Performance is not much of a concern, since it's not going to be used with large amount of data. Except for degenerate case when the length of the incoming byte array is zero, the dump does not end with a new line character. This is regardless whether ASCII part of the dump is shown or not. The code is also careful not to put any trailing spaces in dump lines, since the dump is intended to be copy-pasted and used as part of other texts. Code: class Hex { private readonly byte[] _bytes; private readonly int _bytesPerLine; private readonly bool _showHeader; private readonly bool _showOffset; private readonly bool _showAscii; private readonly int _length; private int _index; private readonly StringBuilder _sb = new StringBuilder(); private Hex(byte[] bytes, int bytesPerLine, bool showHeader, bool showOffset, bool showAscii) { _bytes = bytes; _bytesPerLine = bytesPerLine; _showHeader = showHeader; _showOffset = showOffset; _showAscii = showAscii; _length = bytes.Length; } public static string Dump(byte[] bytes, int bytesPerLine = 16, bool showHeader = true, bool showOffset = true, bool showAscii = true) { if (bytes == null) { return "<null>"; } return (new Hex(bytes, bytesPerLine, showHeader, showOffset, showAscii)).Dump(); } private string Dump() { if (_showHeader) { WriteHeader(); } WriteBody(); return _sb.ToString(); } private void WriteHeader() { if (_showOffset) { _sb.Append("Offset(h) "); } for (int i = 0; i < _bytesPerLine; i++) { _sb.Append($"{i & 0xFF:X2}"); if (i + 1 < _bytesPerLine) { _sb.Append(" "); } } _sb.AppendLine(); }
{ "domain": "codereview.stackexchange", "id": 44102, "lm_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# private void WriteBody() { while (_index < _length) { if (_index % _bytesPerLine == 0) { if (_index > 0) { if (_showAscii) { WriteAscii(); } _sb.AppendLine(); } if (_showOffset) { WriteOffset(); } } WriteByte(); if (_index % _bytesPerLine != 0 && _index < _length) { _sb.Append(" "); } } if (_showAscii) { WriteAscii(); } } private void WriteOffset() { _sb.Append($"{_index:X8} "); } private void WriteByte() { _sb.Append($"{_bytes[_index]:X2}"); _index++; } private void WriteAscii() { int backtrack = ((_index-1)/_bytesPerLine)*_bytesPerLine; int length = _index - backtrack; // This is to fill up last string of the dump if it's shorter than _bytesPerLine _sb.Append(new string(' ', (_bytesPerLine - length) * 3)); _sb.Append(" "); for (int i = 0; i < length; i++) { _sb.Append(Translate(_bytes[backtrack + i])); } } private string Translate(byte b) { return b < 32 ? "." : Encoding.GetEncoding(1252).GetString(new[] {b}); } } Usage: Console.OutputEncoding = Encoding.GetEncoding(1252); byte[] example = Enumerable.Range(0, 256).Select(x=>(byte)x).ToArray(); Console.WriteLine(Hex.Dump(example)); Sample output: Answer: Thing I like less is that you're forcing caller to deal with a static method. I appreciate that kind of helpers but they should be an alternative (maybe with default settings) instead of the only way to go. Why?
{ "domain": "codereview.stackexchange", "id": 44102, "lm_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# If you need more parameters (or to reorder them) then you need to change all calling points. If you add complex parameters (such as a formatter) then calling point will quickly become a mess. They're viral. If you separate UI from underlying logic and you need to delegate some decisions to different places then you can't pass around an Hex class (where each component/control may fill its own properties) because you have a single method call. If a static method becomes complex enough then it will also be harder to test. I'd also change name from Hex to something that describe what your class is doing. HexStringFormatter? HexStringConverter? I'd give two alternatives: var formatter = new HexStringFormatter(); Console.WriteLine(formatter.ConvertToString(example)); Note that in this simple case it may even be (an helper method here just save few characters, what's for?): Console.WriteLine(new HexStringFormatter().ConvertToString(example)); A more complex case may be like this: var formatter = new HexStringFormatter(); formatter.BytesPerLine = 32; formatter.Content = HexStringFormatterOutput.Ascii | HexStringFormatterOutput.Header; These settings may come from UI, now you can return formatter object to another method for example in charge to read data without knowing where settings come from... Note that I also introduced an enum instead of multiple boolean properties but it's not mandatory and not even always suggested, it depends case by case (I like the enum because I can save it in one shot without any effort in my configuration files). Also you may want to make Hex sealed, it's not intended (so far) to be extended.
{ "domain": "codereview.stackexchange", "id": 44102, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# You may accept IEnumerable<byte> instead of byte[]. Performance impact in WriteBody() with foreach is negligible, and you do not need ToArray() in your example. Not such big gain but it will let you read huge files that does not fit in memory (because you can read them block by block without need to convert to byte[] all the content). In this regard you may want to change the output of your class. Now you need to build a huge output string, if content will be written to disk then it's a waste of resources. Write output to a TextWriter. Caller will have responsibility to give you a StringWriter if he wants to output to a string. In this case it may be nice to introduce a static helper method for the most common use case. More complex use case may be like this: using (var output = new StringWriter()) { var formatter = new HexStringFormatter(); formatter.Output = output; formatter.BytesPerLine = 32; formatter.ConvertToString(example); Console.WriteLine(output.ToString()); } HOWEVER note that HexStringFormatter accepts a TextWriter and Console.Out is a TextWriter! Code will then be simplified to: var formatter = new HexStringFormatter(); formatter.Output = Console.Out; formatter.BytesPerLine = 32; formatter.ConvertToString(example); What if you need to write it to a text file? using (var stream = new StreamWriter("path_to_file")) { var formatter = new HexStringFormatter(); formatter.Output = stream; formatter.BytesPerLine = 32; formatter.ConvertToString(example); } Of course you may want to introduce few helper methods for this (now they can make sense but keep them as simple as possible), something like this: public static string DumpToString(IEnumerable<byte> data) { using (var output = new StringWriter()) { var formatter = new HexStringFormatter(); formatter.Output = output; formatter.ConvertToString(data); return output.ToString(); } }
{ "domain": "codereview.stackexchange", "id": 44102, "lm_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# formatter.ConvertToString(data); return output.ToString(); } } public static void DumpToFile(string path, IEnumerable<byte> data) { using (var output = new StreamWriter(path)) { var formatter = new HexStringFormatter(); formatter.Output = output; formatter.ConvertToString(data); } } public static void DumpToConsole(IEnumerable<byte> data) { var formatter = new HexStringFormatter(); formatter.Output = Console.Out; formatter.ConvertToString(data); } Now your first example will be again like this: HexStringFormatter.DumpToConsole( Enumerable.Range(0, 256).Select(x => (byte)x)); Few other minor things. Your Translate() function should be simplified and made static). Also do not need to get a new encoding for each call, use Encoding.ASCII. b < 32 is clear for most of us but I'd make it explicit. For now let's keep GetString() but see later... private static string Translate(byte b) { if (IsPrintableCharacter(b)) return Encoding.ASCII.GetString(new[] { b }); return "." } private static bool IsPrintableCharacter(byte b) => b > 32; Now let's think...you're working with ASCII and byte is in range [0...255] then you may directly cast it to char (after leave to representation issues you mentioned in your Console codepage settings), you avoid to create so many strings and you do not even need any encoding: private static char Translate(byte b) => IsPrintableCharacter(b) ? (char)b : '.';
{ "domain": "codereview.stackexchange", "id": 44102, "lm_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# Code like i & 0xFF in WriteHeader() is little bit misleading, IMO. If _bytesPerLine contains an invalid value then it should throw ArgumentOutOfRangeException when you set it, it shouldn't be silently ignored. Your code will then be simplified everywhere. About your main loop, you do not need to save _length field because you already have the input buffer. I'd also try to give names to all those ifs (=introduce bool locals or separate functions) anyway after refactoring to use IEnumerable<byte> it should look much simpler.
{ "domain": "codereview.stackexchange", "id": 44102, "lm_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 }
algorithm, search, qasm, quantum-computing Title: Unstructured quantum search algorithm for unknown solutions Question: This code was tested on IBM's 5-Qubit processor as an implementation of Grover's search algorithm, but for an unknown number of solutions. This code is based on Arthur Pittenger's book, "An Introduction to Quantum Computing Algorithms" and the mathematical structure was posted as a proof-verification question here. h q[0]; h q[1]; x q[2]; s q[0]; cx q[1], q[2]; t q[3]; cx q[0], q[2]; s q[3]; x q[0]; z q[1]; s q[2]; tdg q[3]; cx q[0], q[2]; id q[3]; cx q[1], q[2]; h q[0]; h q[1]; h q[2]; x q[0]; x q[1]; x q[2]; cx q[0], q[2]; h q[0]; cx q[1], q[2]; s q[2]; h q[2]; tdg q[2]; h q[2]; measure q[0]; measure q[1]; measure q[2]; measure q[3]; measure q[4]; For successful implementations of Grover's algorithm, there has to be a bias towards $$\vert 0 \rangle$$ while $$\vert 1 \rangle$$ only occurs upon a successful query of the qubit oracle. In line with this, the output produces a probabilistic distribution across all possible output permutations of the 5-qubit system, with a |0> bias. Since I am using the "amplitude amplification" method, or "reflection about the mean" the output value will generate a fluctuation in probabilities based on the solution to the problem presented. The fifth qubit Q4 is unused, and is reserved for problem encoding. While IBM allows anyone to publicly access their 5 qubit processor, you will need to be upgraded to Expert User status to copy/paste the QASM code provided. Otherwise, as a Standard User you can build this same algorithm by following the drag and drop operations provided. I've already run this experiment on their live system using 4096 shots, as I do with all tests I run live. I'd like feedback on suggestions of whether I need to keep the Q4 qubit reserved strictly for problem encoding, or if a problem would be more optimally encoded distributed across all qubits.
{ "domain": "codereview.stackexchange", "id": 44103, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, search, qasm, quantum-computing", "url": null }
algorithm, search, qasm, quantum-computing Answer: Now that IBM has upgraded their quantum processor, and further reflection on how to implement a Shor-Grover algorithm on what is available through IBM I believe this question is answered by saying there needs to be additional registers in order to implement any sort of problem to be solved by the algorithm. If you implement the following code without measurement, you see the following areas are naturally encoded into the search space. Bear in mind the measurement is rotated through the search space. OPENQASM 2.0; include "qelib1.inc"; gate nG0(param) q { h q; } gate nG1(param) q { h q; } gate nG2(param) q { h q; } gate nG3(param) q { h q; } gate nG4(param) q { h q; } qreg q[5]; creg c0[3]; creg c1[3]; creg c2[3]; creg c[7]; ccx q[0], q[1], q[2]; nG0(pi * 2) q[3]; y q[0]; ry(pi + 1) q[1]; cswap q[2], q[3], q[4]; cswap q[0], q[1], q[2]; cx q[3], q[4]; rz((pi * 2) + 1) q[2]; cy q[0], q[4]; rxx(21) q[3], q[4]; gate nG8(param) q { h q; } gate nG9(param) q { h q; } h q[0]; h q[1]; x q[2]; t q[3]; rz(pi / 2) q[4]; s q[0]; cx q[1], q[2]; s q[3]; cx q[0], q[2]; tdg q[3]; x q[0]; z q[1]; s q[2]; id q[3]; cx q[0], q[2]; tdg q[3]; h q[0]; cx q[1], q[2]; z q[3]; x q[0]; h q[1]; s q[3]; cx q[0], q[2]; rxx(pi / 2) q[3], q[4]; nG0(pi / 2) q[0]; h q[1]; tdg q[2]; cswap q[2], q[3], q[4]; cy q[2], q[3]; ccx q[0], q[1], q[2]; rz(pi / 2) q[3]; swap q[0], q[1]; nG0(pi / 2) q[2]; swap q[3], q[4]; rz(pi / 2) q[0]; rx(pi / 2) q[2]; ry(pi / 2) q[4]; The output with measurement results in $$|01000>$$ which aligns with a successful query. Encoding a problem requires additional registers, rather than integrating the operations into the search algorithm itself.
{ "domain": "codereview.stackexchange", "id": 44103, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, search, qasm, quantum-computing", "url": null }
java, array, matrix Title: Multidimensional array in Java Question: I have this multidimensional array that generalizes vectors and matrices: com.github.coderodde.util.MultidimensionalArray.java: package com.github.coderodde.util; /** * This class implements a multidimensional array. * * @author Rodion "rodde" Efremov * @version 1.6 (Nov 13, 2022) * @since 1.6 (Nov 13, 2022) */ public final class MultidimensionalArray<E> {
{ "domain": "codereview.stackexchange", "id": 44104, "lm_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, array, matrix", "url": null }
java, array, matrix private final int[] dimensions; private final E[] storage; public MultidimensionalArray(int dimension1, int... otherDimensions) { dimensions = new int[1 + otherDimensions.length]; dimensions[0] = checkDimension(dimension1); for (int i = 0; i < otherDimensions.length; i++) { dimensions[i + 1] = checkDimension(otherDimensions[i]); } storage = (E[]) new Object[multiplyDimensions()]; } public E get(int... coordinates) { checkCoordinates(coordinates); return storage[convertCoordinatesToIndex(coordinates)]; } public void set(E element, int... coordinates) { checkCoordinates(coordinates); storage[convertCoordinatesToIndex(coordinates)] = element; } private void checkCoordinates(int... coordinates) { if (coordinates.length < dimensions.length) { throw new IllegalArgumentException( "The number of coordinates is too small: " + coordinates.length + ". Must be " + dimensions.length + "."); } if (coordinates.length > dimensions.length) { throw new IllegalArgumentException( "The number of coordinates is too large: " + coordinates.length + ". Must be " + dimensions.length + "."); } for (int i = 0; i < dimensions.length; i++) { checkCoordinate(coordinates[i], dimensions[i]); } } private void checkCoordinate(int index, int limit) { if (index < 0) { throw new IndexOutOfBoundsException( "Coordinate is negative: " + index
{ "domain": "codereview.stackexchange", "id": 44104, "lm_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, array, matrix", "url": null }
java, array, matrix "Coordinate is negative: " + index + ". Must be at least zero (0)."); } if (index >= limit) { throw new IndexOutOfBoundsException( "Coordinae is too large: " + index + ". Must be at most " + (limit - 1) + "."); } } private int convertCoordinatesToIndex(int... coordinates) { checkCoordinates(coordinates); int index = 0; int multiplier = 1; for (int i = dimensions.length - 1; i >= 0; i--) { index += multiplier * coordinates[i]; multiplier *= dimensions[i]; } return index; } private int multiplyDimensions() { int ret = dimensions[0]; for (int i = 1; i < dimensions.length; i++) { ret *= dimensions[i]; } return ret; } private static int checkDimension(int dimensionCandidate) { if (dimensionCandidate < 1) { throw new IllegalArgumentException( "Dimension too small: " + dimensionCandidate + ". Must be at least 1."); } return dimensionCandidate; } }
{ "domain": "codereview.stackexchange", "id": 44104, "lm_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, array, matrix", "url": null }
java, array, matrix com.github.coderodde.util.Demo.java: package com.github.coderodde.util; public final class Demo { public static void main(String[] args) { MultidimensionalArray<Integer> arr = new MultidimensionalArray<>(2, 3, 4); for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 4; k++) { arr.set(100 * i + 10 * j + k, i, j, k); } } } for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 4; k++) { System.out.println(arr.get(i, j, k)); } } } } } com.github.coderodde.util.MultidimensionalArrayTest.java: package com.github.coderodde.util; import org.junit.Test; import static org.junit.Assert.*;
{ "domain": "codereview.stackexchange", "id": 44104, "lm_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, array, matrix", "url": null }
java, array, matrix import org.junit.Test; import static org.junit.Assert.*; public final class MultidimensionalArrayTest { @Test public void setAndGet() { MultidimensionalArray<Integer> arr = new MultidimensionalArray<>(2, 3, 5); arr.set(1, 1, 2, 0); arr.set(2, 0, 0, 4); assertEquals(Integer.valueOf(1), arr.get(1, 2, 0)); assertEquals(Integer.valueOf(2), arr.get(0, 0, 4)); } @Test(expected = IllegalArgumentException.class) public void throwsOnTooManyCoordinates() { MultidimensionalArray<Integer> arr = new MultidimensionalArray<>(3, 2, 4, 5); arr.get(0, 1, 1, 2, 0); } @Test(expected = IllegalArgumentException.class) public void throwsOnTooLittleCoordinates() { MultidimensionalArray<Integer> arr = new MultidimensionalArray<>(3, 2, 4, 5); arr.get(0, 1, 1); } @Test(expected = IndexOutOfBoundsException.class) public void throwsOnTooSmallCoordinate() { MultidimensionalArray<Integer> arr = new MultidimensionalArray<>(3, 2, 4, 5); arr.get(0, 1, 1, -1); } @Test(expected = IndexOutOfBoundsException.class) public void throwsOnTooLargeCoordinate() { MultidimensionalArray<Integer> arr = new MultidimensionalArray<>(3, 2, 4, 5); arr.get(0, 2, 1, 0); } } Critique request As always, I would like to hear anything that comes to mind.
{ "domain": "codereview.stackexchange", "id": 44104, "lm_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, array, matrix", "url": null }
java, array, matrix Critique request As always, I would like to hear anything that comes to mind. Answer: I am missing exposed information about dimension sizes. multiplyDimensions could be just called length, possibly public too, although it would be redundant information if you expose dimension sizes Cool thing to have would be to pass initializer function to constructor - function, that accepts coordinates of all dimensions and returns instance of the object. Then constructor loops over the whole array and fills it using this function. That leads to possibility of creating immutable version of this class, missing set method. I would consider using functional approach and replacing foreaches (not the multi-dimensinal ones), some of your cycle code would be a lot nicer and shorter.
{ "domain": "codereview.stackexchange", "id": 44104, "lm_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, array, matrix", "url": null }
c++ Title: Make an array of names and if the names are the same add a number at the end of the name - version 2 Question: I'm writing something like the Unity's shader graph and I'm kinda stuck on a property panel. I add a float property, which name is Float, and then I add a second float property, which also is named Float (until I rename it). I'd like the second property name to be renamed to Float(1) What I tried at the beginning was a simple vector of properties: struct Property { Property(std::string_view name, std::any value) : name(name), value(std::move(value)) {} std::string name; std::any value; }; template<typename PropertyT> void Add(std::string_view name, PropertyT&& value) { static uint32_t counter = 0; auto finalName = counter == 0 ? name : fmt::format("{}({})", name, counter); properties.emplace_back(finalName, std::move(value)); ++counter; } void Remove(std::string_view name) { std::erase_if(properties, [name](const auto& prop){ return prop.name == name; }); } std::vector<Property> properties; But the static uint32_t counter is not a valid solution, because it's a static variable the counter is never decremented, so if Float(1) is removed, then the next float property will be Float(2), but it should be Float(1). So I thought I'd do a map of the property pool by name. #include <unordered_map> #include <vector> #include <string_view> #include <string> #include <any> #include <functional> struct Property { Property(std::string_view name, std::any value, size_t index) : name(name), value(std::move(value)) { if (index != 0) { this->name += "(" + std::to_string(index) + ")"; } } const bool isValid() const { return value.has_value() && !name.empty(); } std::any value; std::string name; private: friend struct PropertyPool; int64_t next = 0; };
{ "domain": "codereview.stackexchange", "id": 44105, "lm_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++ int64_t next = 0; }; struct PropertyPool { [[nodiscard]] inline size_t Add(std::string_view name, std::any&& value) { if (nextFree != -1) { const size_t index = (size_t)nextFree; nextFree = pool[nextFree].next; auto& prop = pool[index]; prop = Property(name, std::move(value), index); nameToId[prop.name] = index; return index; } else { const size_t index = pool.size(); auto& prop = pool.emplace_back(name, std::move(value), index); nameToId[prop.name] = index; return index; } } void Remove(size_t index) { auto& prop = pool[index]; prop.name.clear(); prop.value.reset(); prop.next = nextFree; nextFree = (int64_t)index; } Property* tryGetByName(const std::string& name) { if(!nameToId.contains(name)) { return nullptr; } const size_t index = nameToId.at(name); if(pool.size() <= index) { return nullptr; } if(!pool[index].isValid()) { return nullptr; } return &pool[index]; } const Property* const tryGetByName(const std::string& name) const { if (!nameToId.contains(name)) { return nullptr; } const size_t index = nameToId.at(name); if (pool.size() <= index) { return nullptr; } if (!pool[index].isValid()) { return nullptr; } return &pool[index]; } const int64_t getIDByName(const std::string& name) const { return nameToId.at(name); } std::unordered_map<std::string, int64_t> nameToId; std::vector<Property> pool; int64_t nextFree = -1; };
{ "domain": "codereview.stackexchange", "id": 44105, "lm_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++ struct PropertySet { template<typename T> Property& Add(std::string_view name, T&& value) { const uint32_t hash = getHash(name); auto& pool = pools[hash]; size_t index = pool.Add(name, std::move(value)); return pool.pool[index]; } void Remove(std::string_view name) { const uint32_t hash = getHash(name); auto& pool = pools[hash]; pool.Remove(pool.nameToId[std::string(name)]); } const uint32_t getHash(std::string_view name) const { auto it = name.find_last_of("("); if (it != std::string_view::npos) { name.remove_suffix(name.size() - it); } return std::hash<std::string_view>{}(name); } std::unordered_map<uint32_t, PropertyPool> pools; }; int main() { PropertySet properties; properties.Add("Float", 2.0f); properties.Add("Float", 3.0f); properties.Add("Float", 0.32f); properties.Remove("Float(1)"); properties.Add("Float", 0.84); return 0; } expected values: Float Float(1) Float(2) after Remove Float Float(2) add after remove Float Float(1) Float(2) https://godbolt.org/z/6K8E7Ya5f The code looks awful, but it more or less works as I wish. The main limitation is that this whole code is written only to support properties with the same names, that will most probably be renamed. Thus this solution is kinda useless because let's say there are 4 properties named: Float, x, y, z. The std::unordered_map<uint32_t, PropertyPool> pools will allocate memory, and the PropertyPool will also allocate memory, so it's kinda waste. What do you think about it? How would you implement something like this? What would you change in my code? (I bet everything :D, but keep it for real, though)
{ "domain": "codereview.stackexchange", "id": 44105, "lm_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: Several types are missing their namespace, throughout the code: std::size_t, std::int64_t, std::uint32_t. I'm guessing your compiler has exercised its privilege to also define global-namespace equivalents, but portable code can't depend on that, so properly qualify the names where you use them. Also, consider whether you really need those exact-width types (and should therefore fail to compile on platforms that don't have them), or whether possibly-larger types would satisfy your needs - e.g. std::int_fast64_t. We should write initialisers in the order that they will run (the order in which the fields are declared). This constructor looks like it will initialise name before value, which is misleading: Property(std::string_view name, std::any value, size_t index) : name(name), value(std::move(value)) const bool isValid() const The const on the return type is superfluous, as it's a value and so can be assigned to a non-const variable anyway. Just omit that: bool isValid() const Similarly: const Property* tryGetByName(const std::string& name) const std::int64_t getIDByName(const std::string& name) const std::uint32_t getHash(std::string_view name) const In getHash(), we have an implicit narrowing conversion, because std::hash() returns a std::size_t. Make this explicit with a static_cast. Or just use the type unchanged throughout the class. getHash() doesn't use any of the object state, so it could be declared static. I don't think it's a good idea to have so many of the data members publicly visible. Outside code could easily break a Property by setting its name, or by modifying a PropertyPool's pool vector. I'm not convinced that PropertyPool class needs to be visible. I don't see the value in indirecting access to PropertyPool through an ID number.
{ "domain": "codereview.stackexchange", "id": 44105, "lm_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++ I don't see the value in indirecting access to PropertyPool through an ID number. If I were writing this, I'd probably keep the name and suffix separated, and just maintain a set of suffixes used for each name, like this: #include <algorithm> #include <any> #include <map> #include <set> #include <string> #include <vector> class Property { std::any value_ = {}; std::string name_ = {}; std::size_t suffix_ = {}; public: Property(std::string name, std::size_t suffix, std::any value) : value_{std::move(value)}, name_{std::move(name)}, suffix_{suffix} { } Property() = default; auto name() const { if (suffix_) { return name_ + '(' + std::to_string(suffix_) + ')'; } return name_; } auto const& value() const { return value_; } auto& value() { return value_; } bool isValid() const { return value_.has_value() && !name_.empty(); } friend class PropertySet; }; class PropertySet { std::map<std::string, std::set<std::size_t>> suffixes_used = {}; std::map<std::string, Property> values = {}; public: template<typename T> Property& Add(std::string name, T value) { // choose first unused suffix auto& suffixes = suffixes_used[name]; auto const suffix = next_suffix(suffixes); auto p = Property{std::move(name), suffix, std::move(value)}; suffixes.insert(suffix); return values[p.name()] = p; } void Remove(std::string name) { auto property = values.at(name); auto& suffixes = suffixes_used[property.name_]; suffixes.erase(property.suffix_); if (suffixes.empty()) { suffixes_used.erase(property.name_); } values.erase(name); }
{ "domain": "codereview.stackexchange", "id": 44105, "lm_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++ private: static std::size_t next_suffix(const std::set<std::size_t>& s) { if (s.empty()) { return 0; } auto predicate = [](auto a, auto b){ return a + 1 != b; }; if (auto it = std::ranges::adjacent_find(s, predicate); it != s.end()) { return *it + 1; } return *s.rbegin() + 1; } }; This eliminates the need for the PropertyPool class. With a little further thought, it might be possible to remove the friend relation. friend is often the sign of a design that can be improved.
{ "domain": "codereview.stackexchange", "id": 44105, "lm_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++, asynchronous, queue Title: Asynchronous file writer : queue, mutex, condition variable Question: As we know, it is better to write to a disk in a separate thread because the bottleneck may be the disk, which is slower than the CPU (at the condition only one thread writes to the disk). So I have implemented a "Consumer - Producer". In fact, I realize I think it could be used for any generic task queue. I would like to know if the implementation is OK (performance, undefined behaviour especially). And also I am not sure if the implementation of a limit size of the queue is well done. I don't know if m_condition.wait() on two separate threads is okay. AsyncFileWriter.h #pragma once #include <thread> #include <condition_variable> #include <mutex> #include <opencv2/core.hpp> #include <queue> /** * Write OpenCV asynchronously to a file. * Because writing to a disk is slow, this is to achieve running the computation and writing to a disk in parallel. * * This class stores one thread to do this job. * Creating a thread is not cheap, only one instance of this class is probably needed. */ class AsynFileWriter { public: /** * @param maxPendingOperations * To prevent the thread to be too much delayed with the computation, you can set * a limit of pending operations. If the limit is reached, adding another operation will be blocking until the * count of pending operations is below the limit. */ explicit AsynFileWriter(int maxPendingOperations = 10); /** * If this object is destroyed, the thread is joined. * That means it will be blocking until all pending operations are completed. */ ~AsynFileWriter(); /** * @{ * Prevent copy and assignation. */ AsynFileWriter(const AsynFileWriter&) = delete; AsynFileWriter& operator=(const AsynFileWriter&) = delete; AsynFileWriter&& operator=(AsynFileWriter&&) = delete; AsynFileWriter(AsynFileWriter&&) = delete; /** * @} */
{ "domain": "codereview.stackexchange", "id": 44106, "lm_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++, asynchronous, queue", "url": null }
c++, asynchronous, queue /** * Append a pending operation to the thread. * If the limit of pending operations is reached, this call is blocking until the count of pending operations * is below the limit. * * @note About memory management: * We don't know when the file will be written. The caller function may have exited his scope. * Consequently, the caller matrix maybe won't exist anymore. We have to ensure the matrix is still * valid in the thread. To do so, we can just store a cv::Mat variable which uses a reference counter. * HOWEVER, the caller can't cache the Matrix and change it because it could be change the original matrix * we want to write. That's why this function ALWAYS makes a copy of the original matrix and keep its own copy. */ void async_imwrite(const std::string& path, const cv::Mat& image); private: void runInThread(); struct Operation { std::string path; cv::Mat image; }; // THE ORDER OF VARIABLES IS IMPORTANT: they are initialized in the order they appear in class // The thread is last, because if it is run immediately and m_condition and/or m_mutex is not initialized, // then it is undefined behavior and will probably crash int m_maxPendingOperations; std::queue<Operation> m_pendingOperations; bool m_noMoreOperations; std::mutex m_mutex; ///< For synchronization of m_pendingOperations std::condition_variable m_condition; ///< To tell the thread: Wake up!!! There is job to do! std::thread m_thread; }; AsyncFileWriter.cpp #include "AsynFileWriter.h" #include <opencv2/imgcodecs.hpp> #include <cassert> AsynFileWriter::AsynFileWriter(int maxPendingOperations) : m_maxPendingOperations(maxPendingOperations), m_noMoreOperations(false), m_thread(&AsynFileWriter::runInThread, this) { } AsynFileWriter::~AsynFileWriter() { { std::unique_lock lock(m_mutex); m_noMoreOperations = true;
{ "domain": "codereview.stackexchange", "id": 44106, "lm_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++, asynchronous, queue", "url": null }
c++, asynchronous, queue m_condition.notify_one(); // Notify the thread "We want you to stop immediately" } m_thread.join(); } void AsynFileWriter::async_imwrite(const std::string& path, const cv::Mat& image) { std::unique_lock lock(m_mutex); m_pendingOperations.push(Operation{path, image.clone()}); m_condition.notify_one(); // Notify the thread "We have job for you" if(m_pendingOperations.size() >= m_maxPendingOperations) { // Thread says: "I have too much work boss, please come later" m_condition.wait(lock, [this]() { return m_pendingOperations.size() < m_maxPendingOperations; }); } } void AsynFileWriter::runInThread() { bool shouldStop = false; Operation operation; while(!shouldStop) { { // Only lock once per file to write because locking is costly std::unique_lock lock(m_mutex); // Check if there is pending work if (!m_pendingOperations.empty()) { // Get the next operation if there is one operation = m_pendingOperations.front(); m_pendingOperations.pop(); } else if(m_noMoreOperations) { // No more operations and all operations are completed, stop the thread shouldStop = true; } else { // If there is no pending work, sleep until work is ready OR we are asked to stop m_condition.wait(lock, [this]() { return !m_pendingOperations.empty() || m_noMoreOperations; }); // Get the information again shouldStop = m_noMoreOperations; if(!shouldStop) { // If shouldStop == false, then necessarily there is pending work du to the wait() condition !empty() assert(!m_pendingOperations.empty());
{ "domain": "codereview.stackexchange", "id": 44106, "lm_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++, asynchronous, queue", "url": null }
c++, asynchronous, queue operation = m_pendingOperations.front(); m_pendingOperations.pop(); } } } if(!shouldStop) { // Do the work: one line!!! (all for that...) cv::imwrite(operation.path, operation.image); } } } Answer: Split it into a thread-safe queue and a writer thread So I have implemented a "Consumer - Producer". In fact, I realize I think it could be used for any generic task queue. Indeed, but by combining the queue with the image writer, you have made it more complex and at the same time less flexible. Consider splitting the code up into a generic thread-safe queue that doesn't have to know anything about image writing, and an image writer thread that just reads from the queue and doesn't have to know anything about thread safety. Ideally you would write code like this: struct Operation { std::string path; cv::Mat image; }; ThreadSafeQueue<Operation> imagesToWrite; std::thread writerThread([&]{ while (...) { auto operation = imagesToWrite.pop(); cv::imWrite(operation.path, operation.image); } });
{ "domain": "codereview.stackexchange", "id": 44106, "lm_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++, asynchronous, queue", "url": null }
c++, asynchronous, queue I didn't address how to check if the writer thread should stop, but apart from that, it is possible to make a ThreadSafeQueue so that it's really that simple to write the above code. Allow images to be moved instead of copied Your async_imwrite() function takes an image by const reference. However, you need to put this in the queue somehow, so the only thing you can do then is to make a copy of it. But this can be very expensive if you have large images, and perhaps the caller doesn't need the image any more after they called async_imwrite(), so it would be better if the image could just be moved. Consider writing an overload of async_imwrite() (or of push() if you implement a generic thread-safe queue) that takes the argument by r-value reference: void async_imwrite(const std::string& path, cv::Mat&& image) { ... m_pendingOperations.emplace(path, std::move(image)); ... }
{ "domain": "codereview.stackexchange", "id": 44106, "lm_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++, asynchronous, queue", "url": null }
c++, asynchronous, queue This will use cv::Mat's move constructor to efficiently move the image without having to make a copy of it. You could avoid the resulting code duplication by using perfect forwarding. Don't block unnecessarily In async_imwrite(), you unconditionally push an image to the queue, and then check if the queue is full, and if so you block. But this causes you to wait unnecessarily if you don't have anything else to push. Instead, you should wait before you push. Also consider that m_condition.wait() will first check the condition you give it, and only start waiting if it is false, so you don't need the if-statement around it. Finally, you can unlock the mutex before notifying, this avoids the write thread from receiving a signal but having to immediately wait again for the mutex to be unlocked: void AsynFileWriter::async_imwrite(const std::string& path, const cv::Mat& image) { { std::unique_lock lock(m_mutex); m_condition.wait(lock, [this]() { return m_pendingOperations.size() < m_maxPendingOperations; }); m_pendingOperations.emplace(path, image); } m_condition.notify_one(); } Multiple threads waiting on the same condition variable I don't know if m_condition.wait() on two separate threads is ok.
{ "domain": "codereview.stackexchange", "id": 44106, "lm_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++, asynchronous, queue", "url": null }
c++, asynchronous, queue I don't know if m_condition.wait() on two separate threads is ok. That is perfectly fine. Condition variables can be waited on by multiple threads. There's a notify_all() that should have given you a hint. However, you must make sure that every thread that waits gets notified at some point. I see a call to wait() in async_imwrite(), but no corresponding notify_one() in runInThread(). Make sure you add one there as well, so async_imwrite() gets woken up once the queue is no longer full. Just return when m_noMoreOperations == true Your runInThread() is quite complex, mainly because the checks for when to stop. Note that if you see that m_noMoreOperations == true, you can just immediately return, the lock object will automatically be released. Also again, you are checking more often than necessary; just let m_condition.wait() do most of the work: void AsynFileWriter::runInThread() { while (true) { Operation operation; { std::unique_lock lock(m_mutex); m_condition.wait(lock, [this]() { return !m_pendingOperations.empty() || m_noMoreOperations; }); if (m_noMoreOperations && m_pendingOperations.empty()) { return; } operation = std::move(m_pendingOperations.front()); m_pendingOperations.pop(); } m_condition.notify_one(); cv::imwrite(operation.path, operation.image); } }
{ "domain": "codereview.stackexchange", "id": 44106, "lm_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++, asynchronous, queue", "url": null }
c++, asynchronous, queue Race condition when destroying the AsynFileWriter When the destructor of AsynFileWriter is called, you set m_noMoreOperations. It looks like runInThread() should empty the queue before exitting, however while it's blocked in wait(), it waits until !m_pendingOperations.empty() || m_noMoreOperations. Consider that another thread at that time might enqueue an element and set m_noMoreOperations in quick succession. Once runInThread() wakes up, it then checks if m_noMoreOperations is set, and if so quits, but there could still be elements in the queue. Make sure you only quit if the queue is really empty. Naming AsynFileWriter looks like it should have been AsyncFileWriter. You also have some inconsistencies in how you name things: async_imwrite() uses snake_case, but runInThread() used camelCase. Doxygen comments I see you documented some of the functions and parameters using something that looks like Doxygen. However, it is not done very consistently. Ideally, every function and member variable is documented. Function documentation should start with a one-line @brief summary, and every parameter should be documented using @param. You can configure Doxygen to warn about all these things, and make sure you run doxygen on your code once in a while. If you are using a build system, make it run doxygen automatically. Error handling Consider that an error might occur when cv::imwrite() is called, either because it couldn't convert the image data to the desired file format, or because there was an I/O error writing to the file. cv::imwrite() returns a bool to indicate success or failure, and the documentation suggests that it can also throw an cv::Exception as well. If an error happens and it didn't throw an exception, then you will have silently not written the file you wanted. If an exception is throw, you are not catching it, so this will cause your whole program to be terminated. Is either behavior OK?
{ "domain": "codereview.stackexchange", "id": 44106, "lm_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++, asynchronous, queue", "url": null }
c++, asynchronous, queue Make sure you handle errors appropriately. Consider that the user might want to be informed that something bad happened, you can do this by writing an error message to std::cerr. If the program is running as part of a larger script, you want to make sure it exits with a non-zero exit code (preferrably EXIT_FAILURE), so the script can detect that something went wrong. Finally, it might be that your program might want to be able to do something when a file could not be written. Consider storing the result of the asynchronous actions in some way, for example by returning a std::future when enqueueing an image.
{ "domain": "codereview.stackexchange", "id": 44106, "lm_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++, asynchronous, queue", "url": null }
python, beginner, tic-tac-toe, ai Title: TicTacToe in Python with MiniMax/AlphaBeta Question: I know barely anything about Python, I just jumped into this project as I've already coded it in different languages and it's my go-to when figuring things out in a new one, any feedback will be appreciated. I deliberately tried to avoid making things too object-oriented with private attributes and whatnot. This runs slower than the Java / C++ versions I made, despite having already improved the performance by doing a lightweight clone instead of a deep copy. Board.py from enum import Enum class Board:
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
python, beginner, tic-tac-toe, ai class Board: #the three states each cell can be in class State(Enum): empty = 0 x = 1 o = -1 def __init__(self): self.reset() #resets the board def reset(self): self.cells = [self.State.empty] * 9 self.turn = self.State.x self.currentTurn = 0 self.winner = self.State.empty self.gameOver = False #applies a move based on the current turn def applyMove(self, move): if self.gameOver == False and self.cells[move] == self.State.empty: self.cells[move] = self.turn; self.update() #updates the turn def endTurn(self): if self.turn == self.State.x: self.turn = self.State.o else: self.turn = self.State.x self.currentTurn += 1 def getTurn(self): return self.turn def xWon(self): self.winner = self.State.x self.gameOver = True def oWon(self): self.winner = self.State.o self.gameOver = True def draw(self): self.gameOver = True def getWinner(self): return self.winner.value # returns a list of the empty cells def getMoves(self): moves = [] for i in range(len(self.cells)): if self.cells[i] == self.State.empty: moves.append(i) return moves #checks for a winner/draw def update(self): self.endTurn()
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
python, beginner, tic-tac-toe, ai for i in range(3): xWin = True; oWin = True; for j in range(i*3, i*3+3): if self.cells[j] != self.State.x: xWin = False if self.cells[j] != self.State.o: oWin = False; if xWin: self.xWon() return if oWin: self.oWon() return xWin = True oWin = True for j in range(i, i+7, 3): if self.cells[j] != self.State.x: xWin = False if self.cells[j] != self.State.o: oWin = False if xWin: self.xWon() return if oWin: self.oWon() return step = 4 for i in range(0, 3, 2): xWin = True oWin = True for j in range(3): if self.cells[i+(j*step)] != self.State.x: xWin = False if self.cells[i+(j*step)] != self.State.o: oWin = False if xWin: self.xWon() return if oWin: self.oWon() return step = 2; if self.currentTurn == 9: self.draw() Brain.py (wrapper for the minimax algorithm) import copy from Board import * class Brain: def __init__(self, board): self.originalBoard = board self.count = 0 #returns the best move according to the minimax method def bestMove(self): if self.originalBoard.gameOver: return self.count = 0 scores = [] moves = self.originalBoard.getMoves() for m in moves: scores.append(self.miniMax(self.originalBoard, m))
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
python, beginner, tic-tac-toe, ai print(self.count) if (self.originalBoard.getTurn() == self.originalBoard.State.x): return moves[self.max(scores)] else: return moves[self.min(scores)] #classic minimax with alphabeta pruning def miniMax(self, board, move, alpha = -1, beta = 1): self.count += 1 clone = copy.deepcopy(board) >now replaced as I said in the intro< clone.applyMove(move) if clone.gameOver: return clone.getWinner() availableMoves = board.getMoves() if clone.getTurn() == clone.State.x: for m in availableMoves: score = self.miniMax(clone, m, alpha, beta) if score > alpha: alpha = score if alpha >= beta: break return alpha else: for m in availableMoves: score = self.miniMax(clone, m, alpha, beta) if score < beta: beta = score if alpha >= beta: break return beta #helper method that returns the index of the highest number in a list def max(self, list): max = -1 index = 0 if list.__len__() == 1: return index for i in range (len(list)): if (list[i] > max): max = list[i] index = i return index #helper method that returns the index of the lowest number in a list def min(self, list): min = 1 index = 0 if list.__len__() == 1: return index for i in range (len(list)): if (list[i] < min): min = list[i] index = i return index
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
python, beginner, tic-tac-toe, ai TicTacToe.py (main file) from tkinter import * from Board import * from Brain import * from math import floor as floor CELLS_ROW = 3 WIDTH = 400 HEIGHT = 400 CELLWIDTH = WIDTH / CELLS_ROW CELLHEIGHT = HEIGHT / CELLS_ROW tk = Tk() tk.title("Tic Tac Toe") board = Board() brain = Brain(board) # Draws the background def drawBG(): def getBGColor(i, j): return "#222222" if i % 2 == j % 2 else "#444444" for i in range(0, CELLS_ROW): for j in range(0, CELLS_ROW) : canvas.create_rectangle(i*CELLWIDTH, j*CELLHEIGHT, CELLWIDTH+i*CELLWIDTH, CELLHEIGHT+j*CELLHEIGHT, fill=getBGColor(i, j)) #Draws the naughts and crosses def drawMarks(): thickness = 20 def drawMark(x, y, mark): if mark == board.State.x: canvas.create_line(x*CELLWIDTH+thickness, y*CELLHEIGHT+CELLHEIGHT-thickness, x*CELLWIDTH+CELLWIDTH-thickness, y*CELLHEIGHT+thickness, fill="#d32f2f", width = thickness, capstyle = ROUND) canvas.create_line(x*CELLWIDTH+thickness, y*CELLHEIGHT+thickness, x*CELLWIDTH+CELLWIDTH-thickness, y*CELLHEIGHT+CELLHEIGHT-thickness, fill="#d32f2f", width = thickness, capstyle = ROUND) else: canvas.create_oval(x*CELLWIDTH+thickness, y*CELLHEIGHT+thickness, x*CELLWIDTH+CELLWIDTH-thickness, y*CELLHEIGHT+CELLHEIGHT-thickness, outline="#5a64c8", width = thickness) for i in range(3): for j in range(3): if board.cells[i*3+j] != board.State.empty: drawMark(j, i, board.cells[i*3+j]) #Applies a move based on the mouse position def click(event): def translateCoords(_x, _y): x = floor(_x / CELLWIDTH) y = floor(_y / CELLHEIGHT) return x + y * CELLS_ROW board.applyMove(translateCoords(event.x, event.y)) updateCanvas() #Resets the board def reset(event): board.reset() updateCanvas()
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
python, beginner, tic-tac-toe, ai #Resets the board def reset(event): board.reset() updateCanvas() #Asks the MiniMax algorithm for the best move and applies is def requestMove(event): if board.gameOver == False: board.applyMove(brain.bestMove()) updateCanvas() #Calls the functions that draw the window def updateCanvas(): drawBG() drawMarks() tk.update() canvas = Canvas(tk, width=WIDTH, height=HEIGHT) canvas.bind("<Button-1>", click) canvas.bind("<Button-2>", reset) canvas.bind("<Button-3>", requestMove) updateCanvas() canvas.pack() tk.mainloop() Answer: Your program looks pretty good for a beginner. A couple of things could make the code easier to work with though, and thus reduce the risk of bugs and extra maintenance should you ever pick this up again. State You set a winner as follows: def xWon(self): self.winner = self.State.x self.gameOver = True def oWon(self): self.winner = self.State.o self.gameOver = True def draw(self): self.gameOver = True winner is a State and the gameOver is a separate variable. gameOver can't be part of State, because State is actually being abused for something it wasn't supposed to do: #the three states each cell can be in class State(Enum): empty = 0 x = 1 o = -1
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
python, beginner, tic-tac-toe, ai You're not using it just for the cell state. You're using it for the cell state, the board state (who has won) and even the turn state. Apparently it's acceptable to have a board without winner and without next-player (board state and turn state can be set to empty). If you set either of those to empty, I'd assume the game to be over as well and thus there's no need for a gameOver state. But there's an even better way. You've tried to reduce duplication by using the same class twice. However, by doing so, you've introduced duplication elsewhere in a way that makes less sense than when you'd have allowed the duplication (making either 2 separate constructs to hold state or make 1 that's configurable). Holding game-state in an Enum is a great idea. Holding cell-state in an Enum is too. But their possible states are not the same. A board/game state for Tic Tac Toe can be the following: Incomplete (ongoing) Complete (finished, game over) To keep things simple, we can replace the latter by 3 more specific states: X won Y won Draw A cell state can be the following: X Y Empty Do we have to check for those 3 specific states now to check whether a game is finished? No. Just check whether the board is unfinished. If it's not unfinished, it must be finished. Because those are the only states defined. This would simplify some of the checks you have later on. For example: if xWin: self.xWon() return if oWin: self.oWon() return Note: this construct is used 3 times in the same function (update(self)), which indicates the function is either poorly structured or doing too much. Or both. If the winner is part of the game state, you can return it straight away and not bother with a double if checking temporary variables. The only question at this point is whether there should be returned at all. This could look like the following: if gameState.xWon or gameState.yWon: return This: xWin = True oWin = True for j in range(3):
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
python, beginner, tic-tac-toe, ai This: xWin = True oWin = True for j in range(3): if self.cells[i+(j*step)] != self.State.x: xWin = False if self.cells[i+(j*step)] != self.State.o: oWin = False Completely defies the whole point of working with states in the first place. Why have states at all when at one point you set the game to assume two winners? One false step in those next lines of code and you've broken an otherwise perfectly safe program. Comments near definitions You like to state the purpose of what happens near a definition: #the three states each cell can be in class State(Enum): #applies a move based on the current turn def applyMove(self, move): #Resets the board def reset(event): #Asks the MiniMax algorithm for the best move and applies is def requestMove(event): #Calls the functions that draw the window def updateCanvas(): This is commendable. Did you know Python has an in-built feature that makes this even better? It's called docstrings. Consider PEP 257 – Docstring Conventions. Docstrings provide a convenient way of putting human-readable documentation in the code itself that's easily extracted by other scripts/programs. They can be used on modules, functions, classes and methods. A straightforward conversion would result in: class State(Enum): """The three states each cell can be in.""" def applyMove(self, move): """Applies a move based on the current turn.""" def reset(event): """Resets the board.""" def requestMove(event): """Asks the MiniMax algorithm for the best move and applies it.""" def updateCanvas(): """Calls the functions that draw the window."""
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
python, beginner, tic-tac-toe, ai def updateCanvas(): """Calls the functions that draw the window.""" Minor note: if requestMove fails to perform a move, it will not provide feedback in any way and there was a typo in the comment. Implementing docstrings allows other programs, the Python interpreter and most IDEs to provide guidance on the functions you're using (with IntelliSense). You can then extent this even further using typing (assuming Python 3.5+) and verify whether everything that needs a docstring has one with doctest. This can be very useful when using code defined in a different file/module/library. Readability Most of your code is quite easy to read. Whenever it's hard to follow, that's usually due to how you play around with states. See above. Other parts of your code are easily improved. For example: def drawMark(x, y, mark): if mark == board.State.x: canvas.create_line(x*CELLWIDTH+thickness, y*CELLHEIGHT+CELLHEIGHT-thickness, x*CELLWIDTH+CELLWIDTH-thickness, y*CELLHEIGHT+thickness, fill="#d32f2f", width = thickness, capstyle = ROUND) canvas.create_line(x*CELLWIDTH+thickness, y*CELLHEIGHT+thickness, x*CELLWIDTH+CELLWIDTH-thickness, y*CELLHEIGHT+CELLHEIGHT-thickness, fill="#d32f2f", width = thickness, capstyle = ROUND) else: canvas.create_oval(x*CELLWIDTH+thickness, y*CELLHEIGHT+thickness, x*CELLWIDTH+CELLWIDTH-thickness, y*CELLHEIGHT+CELLHEIGHT-thickness, outline="#5a64c8", width = thickness)
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
python, beginner, tic-tac-toe, ai I think you'll agree with me that the following is much easier on the eyes: def drawMark(x, y, mark): if mark == board.State.x: canvas.create_line( x * CELLWIDTH + thickness, y * CELLHEIGHT + CELLHEIGHT - thickness, x * CELLWIDTH + CELLWIDTH - thickness, y * CELLHEIGHT + thickness, fill = "#d32f2f", width = thickness, capstyle = ROUND ) canvas.create_line( x * CELLWIDTH + thickness, y * CELLHEIGHT + thickness, x * CELLWIDTH + CELLWIDTH - thickness, y * CELLHEIGHT + CELLHEIGHT - thickness, fill = "#d32f2f", width = thickness, capstyle = ROUND ) else: canvas.create_oval( x * CELLWIDTH + thickness, y * CELLHEIGHT + thickness, x * CELLWIDTH + CELLWIDTH - thickness, y * CELLHEIGHT + CELLHEIGHT - thickness, outline = "#5a64c8", width = thickness ) Now the differences and similarities between the canvas calls are clear at a single glance (don't forget to update the canvas.create_rectangle call as well). You're only using canvas.create_line twice, but if you'd use it more often I'd consider writing a new function for it as a wrapper. It might be a bit overkill at this point. Give your operators some breathing room, don't make your lines too long and be consistent with whitespace. There are a couple of magic numbers in your code. Some of the numbers you've turned into a pseudo-constant, like CELLS_ROW = 3. But there are a lot of 3 remaining in your code and all colours are hardcoded. If you put a value into a constant, make sure it's properly named. For example: for i in range(0, CELLS_ROW): for j in range(0, CELLS_ROW): One of those is going to be a column, not a row. Consider PEP 8 - Style Guide for Python Code.
{ "domain": "codereview.stackexchange", "id": 44107, "lm_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, beginner, tic-tac-toe, ai", "url": null }
javascript, jquery Title: Building HTML in JS and append Question: I am working on this project where I need to building html from this object. There a a lot of loops and counter and wanted to see if there is a better way to do this Any suggestions/comments are greatly appreciated to improve the code further. Thanks. full function https://jsfiddle.net/tjmcdevitt/xLbusdk3/10/ $.each(question.MeetingPollingParts, function (index, value) { if (value.MeetingPollingPartsTypeId === MeetingPollingPartsTypeId.Image) { $.each(value.MeetingPollingPartsValues, function (index, parts) { console.log(parts); HTML += "<div class='row'>"; HTML += "<div class='col-md-12'>"; HTML += "<div class='form-group'>"; let strImage = "data:" + parts.FileType + ";base64," + parts.FileData; console.log(strImage); HTML += "<img src='" + strImage + "' />"; HTML += "</div>"; HTML += "</div>"; HTML += "</div>"; }); } if (value.MeetingPollingPartsTypeId === MeetingPollingPartsTypeId.Answer) { $.each(value.MeetingPollingPartsValues, function (index, parts) { if (parts.MeetingPollingPartsValuesTypeId === MeetingPollingPartsValuesTypeId.Radio) { htmlthTable += "<th>"; htmlthTable += parts.QuestionValue; htmlthTable += "</th>"; countRadio = countRadio + 1; } });
{ "domain": "codereview.stackexchange", "id": 44108, "lm_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, jquery", "url": null }
javascript, jquery } console.log(countRadio); if (value.MeetingPollingPartsTypeId === MeetingPollingPartsTypeId.RowQuestion) { $.each(value.MeetingPollingPartsValues, function (index, parts) { if (parts.MeetingPollingPartsValuesTypeId === MeetingPollingPartsValuesTypeId.MultipleChoiceGrid) { htmltrTable += "<tr><td>"; htmltrTable += parts.QuestionValue; htmltrTable += "</td>"; for (var i = 1; i <= countRadio; i++) { htmltrTable += "<td>"; htmltrTable += "<input type='radio'>"; htmltrTable += "</td>"; } htmltrTable += "</tr>"; } }); } });
{ "domain": "codereview.stackexchange", "id": 44108, "lm_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, jquery", "url": null }
javascript, jquery Answer: The naming conventions are irregular; it is conventional in JS to use camelCase for variables, and Capitalized for class names, and ALLCAPS for constants such as static properties of classes, and perhaps even the “enums” you appear to have for the type id to name -maps (but which are absent from both here and the fiddle). String concatenation of hypertext using innerHtml is subject to malicious content since it doesn’t do any sanity checks, unlike for example textContent. Code-wise, it brings mental burden to the reader when there are different branching paths concatenating to the same hypertext string variable. Consider using backtick strings which can use ${code} inside, making it more readable. The variable names seem to follow the logic of tracking the object hierarchy. I’m not sure why you’d want to do that, as long as you keep the namespace scope as tight as possible (which is a natural consequence of using smaller functions, preferably with a single responsibility per function). This point extends all the way to naming database fields. I would consider to first partition the parts array by type to make it more readable, avoiding the need to branch out in the same function. Documenting the different object hierarchies using JSDoc would also help the reader immensely, especially in case of any transformations. For example (as per above, I’ve shortened the property names below, the original names can be seen in the comments): /** @typedef {Object} Question * @property {Number} id - MeetingPollingQuestionId * @property {?String} type - MeetingPollingQuestionType * @property {Number} pollId - MeetingPollingId * @property {Number} typeId - MeetingPollingQuestionTypeId * @property {Number} order - SequenceOrder * @property {Array.<Part>} parts - MeetingPollingParts * * @typedef {Object} Part * @property {Number} id - MeetingPollingPartsId * @property {?String} type - Type
{ "domain": "codereview.stackexchange", "id": 44108, "lm_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, jquery", "url": null }
javascript, jquery * @property {?String} type - Type * @property {Number} typeId - MeetingPollingPartsTypeId * @property {Number} questionId - MeetingPollingQuestionId * @property {Array.<Option>} options - MeetingPollingPartsValues * * @typedef {Object} Option * @property {Number} id - MeetingPollingPartsValuesId * @property {Number} partId - MeetingPollingPartsId * @property {Number} typeId - MeetingPollingPartsValuesTypeId * @property {String} content - QuestionValue * @property {?Number} fileManagerId - FileManagerId * @property {?String} fileName - FileName * @property {?String} fileData - FileData * @property {?String} fileType - FileType * @property {?Array} images - XXX MeetingPollingPartsValuesImages */
{ "domain": "codereview.stackexchange", "id": 44108, "lm_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, jquery", "url": null }
c++, algorithm, graph, breadth-first-search Title: Find center of an undirected graph Question: Task: implement an algorithm to find graph center \$Z(G)\$ given undirected tree \$G\$. This is my first time programming in C++ so any (elementary) feedback is appreciated. The way I did it is: Run BFS from any node \$v_0\$ in \$G\$. Find node \$v_1\$ with \$\max_{v_1\in V(G)} \text{dist} (v_0,v_1)\$. Run BFS from \$v_1\$. Find node \$v_2\$ with \$\max_{v_2\in V(G)} \text{dist} (v_1,v_2)\$. Given tree \$G\$ its center consists of either one or two nodes in the middle of the \$v_1v_2\$ path. Run BFS from both ends of the path and terminate as soon as BFS is halfway through. Save all nodes in the middle of the graph in two vectors \$A,B\$ and take their intersection \$A\cap B\$. Done. My implementation: helloworld.cpp #include <algorithm> #include <iostream> #include <chrono> #include <ctime> #include <set> #include "graph.h" Graph bfs(Graph g, int nodeId) { Graph path(0, Graph::undirected); return path; };
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search Graph bfs(Graph g, int nodeId) { Graph path(0, Graph::undirected); return path; }; int main(int argc, char* argv[]) { int v_0 = 0; if (argc > 1) { // initialize graph Graph g(argv[1], Graph::undirected); // start clock auto start = std::chrono::system_clock::now(); // start BFS in random node and find v_1 such that d(v_0, v_1) is maximal std::pair<int,int> v_1 = g.farthestNode(v_0); // start BFS in v_1 and find v_2 such that d(v_1, v_2) is maximal std::pair<int,int> v_2 = g.farthestNode(v_1.first); // find nodes in the middle between v_1 and v_2 std::vector<int> cand1 = g.middleNodes(v_1.first, v_2.first, v_2.second); std::vector<int> cand2 = g.middleNodes(v_2.first, v_1.first, v_2.second); // find intersection of cand1, cand2 // sort both cand1 and cand2 std::sort(cand1.begin(), cand1.end()); std::sort(cand2.begin(), cand2.end()); // intersect cand 1 and cand2 std::vector<int> cand3(cand1.size()+cand2.size()); std::vector<int>::iterator it, st; it = set_intersection(cand1.begin(), cand1.end(), cand2.begin(), cand2.end(), cand3.begin()); cand3.resize(distance(cand3.begin(), it)); // remove duplicates std::vector<int>::iterator mt; mt = unique(cand3.begin(), cand3.end()); cand3.resize(distance(cand3.begin(), mt)); // stop clock auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::cout << "Elapsed time: " << elapsed_seconds.count() << "s\n"; std::cout << "Center of a graph G is: \n"; for (auto i : cand3) std::cout << i << " "; } else { std::cout << "No instance given."; } } graph.cpp #include "graph.h" #include <bits/stdc++.h>
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search graph.cpp #include "graph.h" #include <bits/stdc++.h> #include <fstream> // fstream provides streams for reading/writing files #include <limits> #include <sstream> // sstream provides conversion between strings and streams #include <stdexcept> const Graph::NodeId Graph::invalid_node = -1; const double Graph::infinite_weight = std::numeric_limits<double>::max(); void Graph::add_nodes(NodeId num_new_nodes) { // The resize adds num_new_nodes. // A std::vector has two sizes: visible size and allocated size s.t. allocaded size >= visible // size If the allocated size needs to be extended it is extended by a constant factor, e.g. // doubled. Thereby n additions of single nodes takes O(n log n) time in total and possible // twice the minimum required space. _nodes.resize(num_nodes() + num_new_nodes); } Graph::Neighbor::Neighbor(Graph::NodeId n, double w) : _id(n), _edge_weight(w) {} Graph::Graph(NodeId num, DirType dtype) : dirtype(dtype), _nodes(num) {} void Graph::add_edge(NodeId tail, NodeId head, double weight) { if (tail >= num_nodes() or tail < 0 or head >= num_nodes() or head < 0) { throw std::runtime_error("Edge cannot be added due to undefined endpoint."); } // for digraphs we store only successors for undirected graphs we store all neighbors. _nodes[tail].add_neighbor(head, weight); if (dirtype == Graph::undirected) { _nodes[head].add_neighbor(tail, weight); } } void Graph::Node::add_neighbor(Graph::NodeId nodeid, double weight) { _neighbors.push_back(Graph::Neighbor(nodeid, weight)); }
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search /** the first const refers to the reference to the vector, which thereby cannot be modified by the * caller. The second const refers to the current object, which must not be modified by this method. * It is required if the member function is called from a const reference to the current object, * i.e. if we a variable such as const Graph::Node& node; */ const std::vector<Graph::Neighbor>& Graph::Node::adjacent_nodes() const { return _neighbors; } Graph::NodeId Graph::num_nodes() const { return _nodes.size(); } const Graph::Node& Graph::get_node(NodeId node) const { if (node < 0 or node >= static_cast<int>(_nodes.size())) { throw std::runtime_error("Invalid nodeid in Graph::get_node."); } return _nodes[node]; } Graph::NodeId Graph::Neighbor::id() const { return _id; } double Graph::Neighbor::edge_weight() const { return _edge_weight; } void Graph::print() const { if (dirtype == Graph::directed) { std::cout << "Digraph "; } else { std::cout << "Undirected graph "; } std::cout << "with " << num_nodes() << " vertices, numbered 0,...," << num_nodes() - 1 << ".\n"; /** The type "auto" automatically substitutes to the type defined by the type or return-type of the function right of the '=', here int. */ for (auto nodeid = 0; nodeid < num_nodes(); ++nodeid) { std::cout << "The following edges are "; if (dirtype == Graph::directed) { std::cout << "leaving"; } else { std::cout << "incident to"; } std::cout << " vertex " << nodeid << ":\n";
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search /** Here auto resolves to a vector iterator of 'const std::vector<Neighbor> &' * The ':' stands for iterating through the elements of the vector from start to end. * The following line is equivalent to (but much shorter and better readable than): * for (auto neighbor = _nodes[nodeid].adjacent_nodes().begin(); neighor != * _nodes[nodeid].adjacent_nodes().end(); neighbor++) { */ for (auto neighbor : _nodes[nodeid].adjacent_nodes()) { std::cout << nodeid << " - " << neighbor.id() << " weight = " << neighbor.edge_weight() << "\n"; } } } Graph::Graph(char const* filename, DirType dtype) : dirtype(dtype) { std::ifstream file(filename); // open file // file is implicitly a pointer to an underlying file object, if it's creation failed it will be // '0' (= NULL). if (not file) { throw std::runtime_error("Cannot open file."); } Graph::NodeId num = 0; std::string line; std::getline(file, line); // get first line of file std::stringstream ss(line); // convert line to a stringstream ss >> num; // for which we can use >> if (not ss) { throw std::runtime_error("Invalid file format."); } add_nodes(num); // read the lines until there is no more line. while (std::getline(file, line)) { std::stringstream ss(line); Graph::NodeId head, tail; ss >> tail >> head; /** The operator! (not operator) of std::stringstream returns true if an error had occured. */ if (not ss) { throw std::runtime_error("Invalid file format."); } double weight = 1.0; ss >> weight; if (tail != head) { add_edge(tail, head, weight); } else { throw std::runtime_error("Invalid file format: loops not allowed."); } } }
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search Graph Graph::max_simple_graph() const { // Check if graph is undirected if (dirtype == Graph::directed) { throw std::runtime_error("Wrong graph type."); } Graph maxSimpleGraph(num_nodes(), undirected); double minEdgeWeight; Graph::Node currentNode; std::vector<Neighbor> neighbors; // loop over all nodes for (auto nodeId = 0; nodeId < num_nodes(); nodeId++) { std::vector<NodeId> uniqueIds(1, -1); currentNode = get_node(nodeId); neighbors = currentNode.adjacent_nodes(); std::cout << "Node ID: " << nodeId << "\n"; // loop over all neighbors of a node for (auto neighbor : currentNode.adjacent_nodes()) { // guard variable bool u = 0; std::cout << "Neighbor ID: " << neighbor.id() << "\n"; // loop over all neighbors (second loop) and find min weight for (auto neighbor2 : neighbors) { if (neighbor2.id() == neighbor.id()) { minEdgeWeight = std::min(neighbor2.edge_weight(), neighbor.edge_weight()); } } // check if such neighbor already exists for (auto id : uniqueIds) { std::cout << "Check: " << id << " " << neighbor.id() << "\n"; u = (id == neighbor.id()) ? 1 : 0; std::cout << u << "\n"; } // if no such neighbor exists, create one if (!u) { std::cout << "Neighbor " << neighbor.id() << " added \n"; maxSimpleGraph._nodes[nodeId].add_neighbor(neighbor.id(), minEdgeWeight); uniqueIds.push_back(neighbor.id()); } std::cout << "u = " << u << "\n"; std::cout << "Minimum weight: " << minEdgeWeight << "\n"; } } return maxSimpleGraph; }
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search std::pair<int,int> Graph::farthestNode(int NodeId) { // initialize all distances with -1 std::vector<int> dist(num_nodes(), -1); std::fill(std::begin(dist),std::end(dist), -1); // create queue and push first node into it std::queue<int> q; q.push(NodeId); // set initial distance to first node as 0 dist[NodeId] = 0; while (!q.empty()) { int currentNodeId = q.front(); // std::cout << "Current node ID: " << currentNodeId << "\n"; q.pop(); Graph::Node currentNode = get_node(currentNodeId); // loop through all neighbors for (auto neighbor : currentNode.adjacent_nodes()) { // std::cout << "Neighbor of " << currentNodeId << " is " << neighbor.id() << "\n"; // if the neighbor wasn't yet visited if (dist[neighbor.id()] == -1) { // add to queue + add distance from the root q.push(neighbor.id()); dist[neighbor.id()] = dist[currentNodeId] + 1; } } } // find maximum distance int maxDist = 0; int NodeId2; for (int i = 0; i < num_nodes(); i++) { if (dist[i] > maxDist) { maxDist = dist[i]; NodeId2 = i; } } std::cout << "Farthest node is " << NodeId2 << " with distance of " << maxDist << "\n\n\n"; return std::make_pair(NodeId2, maxDist); } std::vector<int> Graph::middleNodes(int start, int end, int maxDist) { // input: start node, end node, distance between them // (1) divides max distance by 2 // (2) runs BFS halfway through // (3) returns all nodes that are (max distance / 2) away from Node ID // output: vector<int> Candidates
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search // (1) dind max distance divided by 2 // input: integer n // output: (k,k) if n=2k, (k,k+1) if n=2k+1 std::cout << "Start searching for nodes in the middle between " << start << " and " << end << "\n"; std::pair<int,int> maxDistDivBy2; if (ceilf(maxDist / 2.0)==(maxDist / 2.0)) { maxDistDivBy2 = std::make_pair(ceilf(maxDist / 2.0), ceilf(maxDist / 2.0)); } else { maxDistDivBy2 = std::make_pair(ceilf(maxDist / 2.0), floorf(maxDist / 2.0)); } std::cout << "Max distance " << maxDist << " divided by 2: " << maxDistDivBy2.first << ", " << maxDistDivBy2.second << "\n"; // (2) run BFS // initialize vector for candidate nodes std::vector<int> candidates; // initialize all distances with -1 std::vector<int> dist(num_nodes(), -1); std::fill(std::begin(dist),std::end(dist), -1); // create queue and push first node into it std::queue<int> q; q.push(start); // set initial distance to first node as 0 dist[start] = 0; // start greedy search while (!q.empty()) { int currentNodeId = q.front(); // std::cout << "Current node ID: " << currentNodeId << "\n"; q.pop(); Graph::Node currentNode = get_node(currentNodeId); // loop through all neighbors for (auto neighbor : currentNode.adjacent_nodes()) { // std::cout << "Neighbor of " << currentNodeId << " is " << neighbor.id() << "\n"; // if the neighbor wasn't yet visited if (dist[neighbor.id()] == -1) { // add to queue + add distance from the root q.push(neighbor.id()); dist[neighbor.id()] = dist[currentNodeId] + 1; } else if (dist[neighbor.id()] == maxDistDivBy2.first || dist[neighbor.id()] == maxDistDivBy2.second) { candidates.push_back(neighbor.id()); // std::cout << "Found node " << neighbor.id() << "!\n";
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search // std::cout << "Found node " << neighbor.id() << "!\n"; } else if (dist[neighbor.id()] > maxDistDivBy2.first && dist[neighbor.id()] > maxDistDivBy2.second) { break; } } } /*for (auto i: candidates) { std::cout << i << ' '; } std::cout << "\n";*/
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search return candidates; }```
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search Answer: Don't use <bits/stdc++.h> The header file <bits/stdc++.h> is not part of the C++ standard, and there is no guarantee it exists, or if it does that it will exist in the future. Never use this header file, instead just #include the standard header files you need. Missing error handling If an error happens while reading from a file, the while-loop in Graph::Graph() will exit, but that's not distinguishable from reaching the end of the file. So to check that you did succesfully read the whole file, check that file.eof() == true, and if that is not the case, throw an error. Create a function for finding the center Just like you have other functions that operate on a graph, like farthestNode(), it would be nice to create a function that given a graph, returns the center node(s). This will clean up your main() function. Optimize finding the middle nodes When you are performing a BFS from a given starting point, you can keep track of the "parent" node of each node you visit, i.e. the node from which direction you came. When you then find the farthest node, of which you should know the distance, you can simply walk back along the chain of parent nodes until you are halfway. So consider creating a farthestNodeChain() that returns a std::vector<int> containing that chain, and then it's just picking the one or two middle elements from it. That will also greatly simplify your code. Inconsistent use of Graph::NodeId and Graph::invalid_node It looks like you created a type or type alias Graph::NodeId, but farthestNode() and middleNodes() use int directly. Make sure you are consistent. Consider what would happen if you decided to change Graph::NodeId. I also see you created a constant Graph::invalid_node, but you never seem to use it anywhere else. Unnecessary use of floating points
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search Unnecessary use of floating points Your use of floating point numbers in middleNodes() is unnecessary. If you start with integer numbers and have to end up with integer numbers, avoid having floating points in the middle; it's usually unnecessary, it's less efficient, and if you are not aware of all the subtle issues (like the fact that not all integers can be represented correctly by a floating point number of the same size) it's easy to introduce bugs. Consider: if (maxDist % 2 == 0) { maxDistDivBy2 = {maxDist / 2, maxDist / 2}; } else { maxDistDivBy2 = {maxDist / 2 + 1, maxDist / 2}; }
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search You can avoid the if-statement entirely by adding 1 before dividing by 2: std::pair<int, int> maxDistDivBy2 = {(maxDist + 1) / 2, maxDist / 2}; Use more auto You already use auto in some cases, but you can reduce a lot of explicit, long type names by using more auto: auto v_1 = g.farthestNode(v_0); auto v_2 = g.farthestNode(v_1); auto cand1 = g.middleNodes(v1.first, v2.first, v2.second); ⋮ auto it = set_intersection(cand1.begin(), cand1.end(), cand2.begin(), cand2.end(), cand3.begin()); ⋮ auto mt = std::unique(cand3.begin(), cand3.end()); Use more STL algorithms The standard library comes with many algorithms that take care of common tasks for you. For example, to find the node with the maximum distance, you can use std::max_element(): auto it = std::max_element(dist.begin(), dist.end()); NodeId farthestNodeId = std::distance(dist.begin(), it); Double initialization of dist In both farthestNode() and middleNodes() you construct a vector filled with -1, and then call std::fill() to fill it with -1 again. The calls to std::fill() are unnecessary. Use of comments You have added a lot of comments to your code. Since this is your first time programming C++, it's probably a good excercise to describe in normal English what you are trying to accomplish, as this might help your learning process. That said, if this wasn't just a learning project, then I would say that you have many unnecessary comments. Basically, everything that the average C++ programmer would understand just by looking at the code itself does not need to documented. This includes things like: // initialize graph Graph g(argv[1], Graph::undirected); ⋮ // start clock auto start = std::chrono::system_clock::now(); ⋮ #include <fstream> // fstream provides streams for reading/writing files
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, algorithm, graph, breadth-first-search There are examples of comments that are helpful though, for example: // for digraphs we store only successors for undirected graphs we store all neighbors. ⋮ // check if such neighbor already exists ⋮ // if no such neighbor exists, create one That said, if you have a number of lines of code whose meaning would not be immediately clear for an average programmer, then instead of adding a comment above it, you could instead also put those lines in their own function. With a properly chosen name for the function, the meaning of the code would become much clearer without having to use a comment. This is also a reason to use algorithms and other functions from the standard library when possible; their names say what they do, and most C++ programmers already have a good knowledge of what the standard functions do. Lastly, consider using the Doxygen format to document the classes and functions in your code. The doxygen tool can then generate HTML and PDF files containing that documentation in a nicer to read, cross-referenced format, and it can warn if you forgot to document parts of your code.
{ "domain": "codereview.stackexchange", "id": 44109, "lm_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++, algorithm, graph, breadth-first-search", "url": null }
c++, game, c++11, wordle Title: Wordle game in C++ Question: I am a programmer who likes making clones of games. Having completed a version of Wordle in Python, I challenged myself with making a version of it in C++. This includes a solver as well (add a flag -s while running to activate solving mode.) I used ANSI escape codes to create coloring and an interactive experience. However, this might be MacOS only, please advise about this. Here is the code: (compiled with g++, no extra flags) // // main.cpp // wordle // // Created by Colin Ding on 10/4/22. // Copyright © 2022 Colin Ding. All rights reserved. // #include <algorithm> #include <ctime> #include <fstream> #include <iostream> #include <iterator> #include <random> #include <string> #include <vector>
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle // the following are UBUNTU/LINUX, and MacOS ONLY terminal color codes. #define RESET "\033[0m" #define BLACK "\033[30m" /* Black */ #define RED "\033[31m" /* Red */ #define GREEN "\033[32m" /* Green */ #define YELLOW "\033[33m" /* Yellow */ #define BLUE "\033[34m" /* Blue */ #define MAGENTA "\033[35m" /* Magenta */ #define CYAN "\033[36m" /* Cyan */ #define WHITE "\033[37m" /* White */ #define BOLDBLACK "\033[1m\033[30m" /* Bold Black */ #define BOLDRED "\033[1m\033[31m" /* Bold Red */ #define BOLDGREEN "\033[1m\033[32m" /* Bold Green */ #define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ #define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */ #define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */ #define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */ #define BOLDWHITE "\033[1m\033[37m" /* Bold White */ #define DIMBLACK "\033[2m\033[30m" /* Dim Black */ #define DIMRED "\033[2m\033[31m" /* Dim Red */ #define DIMGREEN "\033[2m\033[32m" /* Dim Green */ #define DIMYELLOW "\033[2m\033[33m" /* Dim Yellow */ #define DIMBLUE "\033[2m\033[34m" /* Dim Blue */ #define DIMMAGENTA "\033[2m\033[35m" /* Dim Magenta */ #define DIMCYAN "\033[2m\033[36m" /* Dim Cyan */ #define DIMWHITE "\033[2m\033[37m" /* Dim White */ #define MOVEUP "\033[" /* add integer, and add F */ #define ERASELINE "\033[2K" /* erase current line */ const int LENGTH = 5; struct { char wrong = '_'; char in_word = 'O'; char correct = '#'; } LETTERVALUES; std::string KEYBOARDCOLORS[] = { WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE};
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle std::vector<std::string> readSolutions(int length) { std::string line; std::vector<std::string> vec; std::ifstream fin; fin.open("./words/solutions.txt"); while (getline(fin, line)) { if (line.length() == length) { vec.push_back(line); } } fin.close(); return vec; } std::vector<std::string> readGuesses(int length) { std::string line; std::vector<std::string> vec; std::ifstream fin; fin.open("./words/guesses.txt"); while (getline(fin, line)) { if (line.length() == length) { vec.push_back(line); } } fin.close(); return vec; } std::string chooseRandom(std::vector<std::string> vec) { auto iterator = vec.begin(); int random_number = rand() % vec.size(); advance(iterator, random_number); return iterator[0]; } char getNthLetter(int n) { return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[n - 1]; } int getNumFromChar(char x) { return ((int)x) - 64; } std::string checkWord(std::string text, std::string correct, int len) { std::string out; for (int i = 0; i < len; i++) { char text_character = text[i]; char correct_character = correct[i]; if (text_character == correct_character) { out += LETTERVALUES.correct; // string(GREEN) + LETTERVALUES.correct + string(RESET); correct[i] = '0'; } else if (correct.find(text_character) != std::string::npos) { out += LETTERVALUES.in_word; // string(YELLOW) + LETTERVALUES.in_word + string(RESET); correct[i] = '0'; } else { out += LETTERVALUES.wrong; // string(DIMWHITE) + LETTERVALUES.wrong + string(RESET); } } return out; } std::string getKeyboardForPrinting() { std::string out; int i = 0; for (auto color : KEYBOARDCOLORS) { out += std::string(color) + getNthLetter(i) + std::string(RESET); i++; } return out; }
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle return out; } void play(std::string solution, std::vector<std::string> all_guesses) { std::cout << BOLDWHITE; std::cout << "Welcome to Wordle!" << std::endl; std::cout << "Play by guessing 5-letter words." << std::endl; std::cout << "The feedback will give you clues:" << std::endl; std::cout << " GRAY = Character not in word at all" << std::endl; std::cout << " GREEN = Character found and position correct" << std::endl; std::cout << " YELLOW = Character found but position incorrect" << std::endl; std::cout << RESET; std::cout << "\n\n"; std::cout << getKeyboardForPrinting() << std::endl; int lines_since_keyboard = 1; for (int i = 0; i <= 5; i++) { std::string guess; std::cout << BOLDWHITE << "Guess a word (" + std::to_string(i + 1) + "/6): " << RESET; std::cin >> guess; transform(guess.begin(), guess.end(), guess.begin(), ::toupper); lines_since_keyboard++; if (guess == "STOP") { return; } if (find(all_guesses.begin(), all_guesses.end(), guess) != all_guesses.end()) { std::string feedback = checkWord(guess, solution, LENGTH); std::string to_write = "Guess a word (" + std::to_string(i + 1) + "/6): "; for (int j = 0; j < 5; j++) { char inputted_character = guess[j]; char feedback_character = feedback[j]; int keyboard_colors_index = getNumFromChar(inputted_character); // inputted_character); std::string color_to_make;
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle std::string color_to_make; if (feedback_character == LETTERVALUES.wrong) { color_to_make = DIMWHITE; } else if (feedback_character == LETTERVALUES.correct) { color_to_make = GREEN; } else if (feedback_character == LETTERVALUES.in_word) { color_to_make = YELLOW; } else { color_to_make = BLACK; } to_write += color_to_make + inputted_character + RESET; if (KEYBOARDCOLORS[keyboard_colors_index] == WHITE) { KEYBOARDCOLORS[keyboard_colors_index] = color_to_make; } else if (KEYBOARDCOLORS[keyboard_colors_index] != GREEN) { if ((KEYBOARDCOLORS[keyboard_colors_index] != RED) && (color_to_make == GREEN)) { KEYBOARDCOLORS[keyboard_colors_index] = color_to_make; } } else { KEYBOARDCOLORS[keyboard_colors_index] = color_to_make; } } std::cout << std::string(MOVEUP) + "1F"; std::cout << to_write << std::endl; std::cout << std::string(MOVEUP) + std::to_string(lines_since_keyboard) + "F"; std::cout << getKeyboardForPrinting() << std::endl; std::cout << std::string(MOVEUP) + std::to_string(lines_since_keyboard) + "E"; if (guess == solution) { std::cout << "You won in " << i + 1 << " moves!" << std::endl; return; } } else { std::cout << std::string(MOVEUP) + "1F"; std::cout << ERASELINE; std::cout << "Guess a word (" + std::to_string(i + 1) + "/6): " << BOLDRED << "INVALID"; std::cout << std::string(MOVEUP) + "1E"; i--; } }
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle i--; } } std::cout << "You lost!" << std::endl; std::cout << "The correct word was " << solution << std::endl; } void printHelpExit() { std::cout << "Usage: wordle [-h|--help] [-s|--showsolution]" << std::endl; std::cout << "\n"; std::cout << "Option\t\t\tBehavior" << std::endl; std::cout << "------\t\t\t--------" << std::endl; std::cout << "-s, -showsolution\tShow the solution at beginning (debug)" << std::endl; std::cout << "-h, --help\t\tPrint this help text and quit" << std::endl; exit(0); } bool contains(std::vector<char> c, char e) { return find(begin(c), end(c), e) != end(c); }; std::vector<std::string> applyRule(std::vector<std::string> all_words, std::vector<char> s1, std::vector<char> s2, std::vector<char> s3, std::vector<char> s4, std::vector<char> s5) { std::vector<std::string> new_solutions; std::copy_if(all_words.begin(), all_words.end(), back_inserter(new_solutions), [s1, s2, s3, s4, s5](std::string const& x) { return (contains(s1, x[0]) && (contains(s2, x[1])) && (contains(s3, x[2])) && (contains(s4, x[3])) && (contains(s5, x[4]))); }); return new_solutions; } void solver(std::vector<std::string> all_solutions, bool log_s) { std::cout << BOLDCYAN; std::cout << "Welcome to the Wordle solver!!" << std::endl; std::cout << "To use this solver, simply follow the instructions;" << std::endl; std::cout << "Input the word it suggests in your game:" << std::endl; std::cout << "Make sure to give the program the feedback!" << std::endl; std::cout << "'_' = gray tile" << std::endl; std::cout << "'+' = yellow tile" << std::endl; std::cout << "'=' = green tile" << std::endl; std::cout << RESET; std::cout << "\n\n"; std::vector<char> s1, s2, s3, s4, s5; char letters[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle for (char c : letters) { s1.push_back(c); s2.push_back(c); s3.push_back(c); s4.push_back(c); s5.push_back(c); } std::cout << BOLDMAGENTA; for (int i = 0; i < 6; i++) { std::string response, chosen_word; if (i == 0) { chosen_word = "CRATE"; } else { chosen_word = chooseRandom(all_solutions); } while (response.size() != 5) { if (response == "STOP") { return; } else { if (response == "LIST") { // todo, pritn all_solutions } std::cout << "Try the word " + chosen_word + ": "; std::cin >> response; } } for (int j = 0; j < 5; j++) { std::vector<char>* to_change = nullptr; std::vector<char>* all[5] = {&s1, &s2, &s3, &s4, &s5}; if (j == 0) { to_change = &s1; } else if (j == 1) { to_change = &s2; } else if (j == 2) { to_change = &s3; } else if (j == 3) { to_change = &s4; } else if (j == 4) { to_change = &s5; } char resp_c = response[j]; char word_c = chosen_word[j]; if (resp_c == '=') { to_change->clear(); to_change->push_back(word_c); } else if (resp_c == '-') { to_change->erase(remove(to_change->begin(), to_change->end(), word_c), to_change->end()); for (std::vector<char>* v : all) { if (v == to_change) { continue; }
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle v->erase(remove(v->begin(), v->end(), word_c), v->end()); } } else if (resp_c == '+') { (*to_change).erase(remove(to_change->begin(), to_change->end(), word_c), to_change->end()); for (std::vector<char>* v : all) { if (v == to_change) { continue; } v->push_back(word_c); std::sort(v->begin(), v->end()); v->erase(unique(v->begin(), v->end()), v->end()); } } else { std::cout << "Invalid input format, exiting." << std::endl; } } if (log_s) { for (char c : s1) { std::cout << c; } std::cout << std::endl; for (char c : s2) { std::cout << c; } std::cout << std::endl; for (char c : s3) { std::cout << c; } std::cout << std::endl; for (char c : s4) { std::cout << c; } std::cout << std::endl; for (char c : s5) { std::cout << c; } std::cout << std::endl; } all_solutions = applyRule(all_solutions, s1, s2, s3, s4, s5); if (all_solutions.size() == 1) { std::cout << "The solution is " << all_solutions[0] << "." << std::endl; return; } } } int main(int argc, const char* argv[]) { srand(time(0)); bool show_sol = false; bool solver_on = false; bool show_alpha = false; if (argc > 1) { for (int i = 1; i < argc; i++) { std::string arg = argv[i];
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle if (argc > 1) { for (int i = 1; i < argc; i++) { std::string arg = argv[i]; if ((arg == "-h") || (arg == "--help")) { printHelpExit(); } else if ((arg == "-d") || (arg == "--debug")) { std::cout << BOLDBLUE << "DEBUG ON" << RESET << std::endl; show_sol = true; } else if ((arg == "-s") || (arg == "--solver")) { std::cout << BOLDBLUE << "SOLVER ON" << RESET << std::endl; solver_on = true; } else if (arg == "--showalpha") { std::cout << BOLDBLUE << "SHOWING ALPHA" << RESET << std::endl; show_alpha = true; } else { std::cout << "Invalid argument: " << arg << std::endl; printHelpExit(); } } } std::vector<std::string> all_solutions = readSolutions(LENGTH); std::vector<std::string> all_guesses = readGuesses(LENGTH); for (std::string s : all_solutions) { all_guesses.push_back(s); } auto const solution = chooseRandom(all_solutions); if (show_sol == true) { std::cout << BOLDGREEN << solution << RESET << std::endl; } if (solver_on == false) { play(solution, all_guesses); } else { solver(all_solutions, show_alpha); } return 0; } words/guesses.txt download from github words/solutions.txt download from github Answer: Avoid macros Avoid preprocessor macros where possible. They have various issues if you don't use them carefully, and they are rarely needed in C++. To define constants, create static constexpr variables, for example: static constexpr auto RESET = "\033[0m";
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle Keeping track of colors There are several issues with your array KEYBOARDCOLORS[]. First, how many elements does it have? Are you sure you wrote WHITE exactly 26 times? At the very least, specify the size explicitly, like you did for letters[]: std::string KEYBOARDCOLORS[26] = {...}; That way, if you add too many colors, a compile error will occur, but it's still not ideal that you still have to write WHITE 26 times, and if you miss one there will be an empty color string (although at least that won't cause anything to crash). If you use std::vector here, you can initialize all elements to the same value: std::vector<std::string> KEYBOARDCOLORS(26, WHITE); But there are still many issues. You are sometimes comparing colors against each other, but since you store them as strings, it has to do string comparison. That is less efficient than possible. Finally, you are assuming that you can print strings containing ANSI escape codes to change colors. But if you were to port your program to something that uses a different way of changing colors, you could not use strings any more, and you would have to change a lot of code. It helps to add a layer of indirection here. Create an enum class of color names: enum class Color { BLACK, RED, GREEN, ⋮ }; Then you can write: std::vector<Color> KEYBOARDCOLORS(26, Color::WHITE); Comparing enums (which are just integers under the hood) is very efficient on a CPU: if (KEYBOARDCOLORS[keyboard_colors_index] == Color::WHITE) { Then the only remaining issue is converting this enum to an ANSI escape code. I would write a function colorToAnsi() that does this. It could look like: std::string colorToAnsi(Color color) { switch (color) { case Color::BLACK: return "\033[30m"; case Color::RED: return "\033[31m"; ⋮ } } And then do: for (std::size_t i = 0; i < KEYBOARDCOLORS.size(); ++i) { out += colorToAnsi(KEYBOARDCOLORS[i]) + getNthLetter(i); } out += RESET;
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle out += RESET; I also wonder why you added constants for so many colors, when you only use five of them? Consider using a curses library If you want to have a terminal application with colors, and maybe also the ability to clear the screen and draw text at arbitrary positions, consider using a curses library. These provide a platform-independent API to do these things. Use '\n' instead of std::endl Prefer to use '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually unnecessary and might be detrimental for performance. Avoid code duplication Writing the same code over and over is boring, tedious, and it increases the chance that you make a mistake somewhere. So try to find ways to avoid doing that, like with the initialization of KEYBOARDCOLORS[] I mentioned above. Another example of repetition is readSolutions() and readGuesses(). These two functions do exactly the same thing, the only difference is the filename they use. So consider creating one function that takes the filename as a parameter: std::vector<std::string> readFile(const std::string& filename, int length) { ⋮ std::ifstream fin(filename); ⋮ } ⋮ auto all_solutions = readFile("../words/solutions.txt", LENGTH); auto all_sguesses = readFile("../words/guesses.txt", LENGTH); Also, whenever you have a bunch of variables that start with the same name and end in different numbers, you probably should have created an array or vector. So instead of s1, s2, ... write: std::vector<char> s[5]; Or even better, consider that a std::vector<char> is more or less a std::string, and that you want to print the contents of s if log_s == true, so you can simplify things a lot by writing: const std::string letters = "ABCDE..."; std::vector<std::string> s(5, letters); ⋮ for (int j = 0; j < 5; j++) { auto& to_change = s[j]; ⋮ } ⋮ if (log_s) { for (auto& to_show: s) { std::cout << to_show << '\n'; } }
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
c++, game, c++11, wordle Naming things Most things in your code have names that rather clearly indicate what they do or mean. But there are some examples of unnecessarily short variable names, like s and s1…s5. Make sure you give these variables names that are meaningful. Note that it's fine to use i and j for loop indices; this is a very common use so their meaning will be clear to most programmers.
{ "domain": "codereview.stackexchange", "id": 44110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, c++11, wordle", "url": null }
python, python-3.x, bitwise Title: pythonic way to split bytes Question: I have incoming data from an absolute rotary encoder. It is 24 bits wide. 12 bits are the number of turns and 12 bits are the angle. I'm reading the data with an Arduino and sending it to the computer over a serial port. The most natural thing to do would be to combine all of the bits and send it as 3 bytes. Splitting up the 3 bytes into 12 bits/12 bits at the computer in Python 3 feels unpythonic to me. Here is what I have so far: import struct # fake message, H is header last 3 bytes are data msg = b'H\x90\xfc\xf9' header, bytes3 = struct.unpack('>c3s', msg) print('bytes3 ', bytes3) val = int.from_bytes(bytes3, 'big') print('val ', val) print('bin(val) ', bin(val)) upper12 = val >> 12 print('bin(upper12)', bin(upper12)) lower12 = val & 0b000000000000111111111111 print('bin(lower12)', bin(lower12)) which gives console output of bytes3 b'\x90\xfc\xf9' val 9501945 bin(val) 0b100100001111110011111001 bin(upper12) 0b100100001111 bin(lower12) 0b110011111001 This code seems to work fine, but bitshifting (val >> 12) and bitwise anding (val & 0b000...) are a little wonky. Also it feels funny to specify Big Endian twice: first in the struct.unpack format string and second in int.from_bytes. Is there a more elegant way to achieve this? Update: timing I'm still on the fence on which technique is most Pythonic. But I did time 3 techniques: original technique above technique by AlexV with overlapping unsigned 16 bit integers change comms protocol to send a padded 4 byte unsigned integer that struct can convert directly to integer import struct import time import random import timeit def gen_random_msg(nbyte = 3): # make a n byte message with header 'H' prepended data = random.randint(0, 2**12-1) data = data.to_bytes(nbyte, 'big') msg = b'H' + data return msg def original_recipe(): msg = gen_random_msg(3) header, bytes3 = struct.unpack('>c3s', msg) val = int.from_bytes(bytes3, 'big')
{ "domain": "codereview.stackexchange", "id": 44111, "lm_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, bitwise", "url": null }
python, python-3.x, bitwise upper12 = val >> 12 lower12 = val & 4095 # 4095 = 2**12-1 def overlap16bits(): msg = gen_random_msg(3) header, val = struct.unpack('>cH', msg[0:-1]) upper12 = val >> 4 lower12 = struct.unpack('>H', msg[2:])[0] & 0xfff def fourbyte(): msg = gen_random_msg(4) header, val = struct.unpack('>cI', msg) upper12 = val >> 12 lower12 = val & 4095 # 4095 = 2**12-1 niter = int(1e6) t0 = time.time() for i in range(niter): gen_random_msg(3) t1 = time.time() for i in range(niter): gen_random_msg(4) t2 = time.time() for i in range(niter): original_recipe() t3 = time.time() for i in range(niter): overlap16bits() t4 = time.time() for i in range(niter): fourbyte() t5 = time.time() gentime3 = t1-t0 gentime4 = t2-t1 original_time = t3-t2 overlap_time = t4-t3 fourbyte_time = t5-t4 print('gentime3: ', gentime3, '. gentime4: ', gentime4) print ('original recipe: ', original_time - gentime3) print ('overlap 16 bits: ', overlap_time - gentime3) print ('four bytes: ', fourbyte_time - gentime4) this has console output: gentime3: 3.478888988494873 . gentime4: 3.4476888179779053 original recipe: 1.3416340351104736 overlap 16 bits: 1.435237169265747 four bytes: 0.7956202030181885 It takes more time to generate 1M dummy msg than it does to process the bytes. The fastest technique was to change the comms spec and pad the 3 bytes to make a 4 byte unsigned integer. The speed up was good (approx 2x) for "fourbytes", but requires changing the communications specification. At this point I think it comes down to personal preference as to which algorithm is the best. Answer: You could unpack them twice into (overlapping) unsigned shorts of 16bit and shift/mask them accordingly. upper12 = struct.unpack(">H", msg[1:-1])[0] >> 4 lower12 = struct.unpack(">H", msg[2:])[0] & 0xFFF Telling Python to interpret them as short integers helps you to get rid of int.from_bytes.
{ "domain": "codereview.stackexchange", "id": 44111, "lm_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, bitwise", "url": null }
python, set, wordle, jupyter Title: Yet another Wordle Game Question: This Jupyter Notebook code for the Wordle game works. After a lot of fixes, I have it working as it should. The code is a jumbled mess. I am open to any suggestions and/or criticism of my code. I am here to learn and improve my code. Any help would be much appreciated. NLTK needs to be installed to use the code. Link to custom word file to supplement words in NLTK dictionary: custom.txt import time from nltk.corpus import words from nltk.corpus import wordnet import random def Occurences(s, ch): return([i for i, letter in enumerate(s) if letter == ch]) def printTile(tile, guess): for i in range(0,5): color = 44 - tile[i] print(f'\x1b[1;{color};30m {guess[i].upper()} \x1b[0m', end=' ') time.sleep(0.6) print(flush=True) def printKeyboard(tile, guess, dic): print() for key in dic: if dic[key] != 0: dic[key] = -3 for i in range(0,5): if dic[guess[i]] < tile[i]: dic[guess[i]] = tile[i] for key in dic: color = 44 - dic[key] print(f'\x1b[1;{color};30m {key.upper()} \x1b[0m', end=' ') print(flush=True)
{ "domain": "codereview.stackexchange", "id": 44112, "lm_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, set, wordle, jupyter", "url": null }
python, set, wordle, jupyter set_of_words = set(words.words()).union(set(open('custom.txt').read().split())) five_letter_words = [w for w in set_of_words if (len(w) == 5 and w.isalpha())] word = (random.choice(five_letter_words)).lower() #print(word) # for testing #word = 'agora' # for testing guesses = 0 kybd = 'abcdefghijklmnopqrstuvwxyz' dic = {i: 47 for i in kybd} while True: guess = (input('Enter you guess:')).lower() while True: if guess not in five_letter_words or len(guess) != 5: guess = input('Not a 5-letter word!! Guess Again: ') else: break guesses += 1 if guess == word: printTile([2,2,2,2,2], word) print('we have a winner!!!') break wd_dic = {i: 0 for i in sorted(set(word))} for i in wd_dic: wd_dic[i] = Occurences(guess,i) gu_dic = {i: 0 for i in sorted(set(guess))} for i in gu_dic: gu_dic[i] = Occurences(word,i) tile = [0,0,0,0,0] for i in gu_dic: if i in word: lst = gu_dic[i].copy() if set(wd_dic[i]) & set(lst): overlap = list(set(lst).intersection(set(wd_dic[i]))) for k in overlap: tile[k] = 2 wd_dic[i].remove(k) lst.remove(k) for j in lst: if j in wd_dic[i] and word[j] != guess[j]: tile[j] = 2 wd_dic[i].remove(j) elif word[j]==guess[j]: tile[j] = 2 wd_dic[i].remove(j) else: if wd_dic[i]: tile[wd_dic[i][0]] = 1 wd_dic[i].pop(0) gu_dic[i].remove(j) printTile(tile, guess) printKeyboard(tile,guess, dic) if guesses == 6: print(f'You lose!! The word was:') printTile([2,2,2,2,2], word) break
{ "domain": "codereview.stackexchange", "id": 44112, "lm_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, set, wordle, jupyter", "url": null }
python, set, wordle, jupyter Answer: Is it intentional that the keyboard doesn't also show information from previous guesses? In the original game, the point of the keyboard is to remind the user of all the information they have learnt so far. Unused imports You import wordnet, even though you never use it. You should remove unused imports. Why do you need both words.words() and custom.txt? The only point of the nltk dependency in your code is to get a list of words. nltk is a very hefty dependency, and nltk.corpus.words is even installed in a "random" system location (home directory) totally unrelated to the project. Your code would be more portable, and it would be easier for other people to run your code (e.g. for the sake of this code review) if you didn't have a redundant dependency like this. If you really want the nltk words especially, you could just add them all to your custom.txt file. Naming All function names and variable names should be snake_case according to PEP8 and Google's Python Style Guide. So Occurrences should be renamed occurrences, and printTile should be renamed print_tile, etc. Some of your variable names could be more self-explanatory and meaningful, e.g. dic could be called letter_colors so that readers can know at a glance what it stores. wd_dic, gu_dic, tile could also do with more meaningful names. docstrings It would be great practice to document your functions: def occurences(s, ch): r'''Find all indexes where the character appears in the string. >>> occurrences('aisle', 'a') [0] >>> occurrences('ababa', 'b') [1, 3] ''' return [i for i, letter in enumerate(s) if letter == ch]
{ "domain": "codereview.stackexchange", "id": 44112, "lm_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, set, wordle, jupyter", "url": null }
python, set, wordle, jupyter The lines of the docstring starting >>> are called doctests, and are a great way to provide examples in your documentation at the same time as adding tests-for-correctness. Afterwards, run python -m doctest your_code.py to see if the doctests actually do have the expected results. Type Hints You can also use type hints to self-document your code's intended usage. def occurences(s: str, ch: str) -> list[int]: ... Unnecessarily verbose In lines 49 and 52, you have wd_dic = {i: 0 for i in sorted(set(word))} ... gu_dic = {i: 0 for i in sorted(set(guess))} Why are you converting word to a set and sorting it before looping it to make dictionary keys? You don't depend on the order of the dictionary keys at any point. wd_dic = {i: 0 for i in word} ... gu_dic = {i: 0 for i in guess} Is logically equivalent. Immediately after each, you even loop the keys to generate the values: wd_dic = {i: 0 for i in sorted(set(word))} for i in wd_dic: wd_dic[i] = Occurences(guess,i) Just use your dict comprehension to generate the values in the first place: wd_dic = { letter: occurrences(guess, letter) for letter in word }
{ "domain": "codereview.stackexchange", "id": 44112, "lm_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, set, wordle, jupyter", "url": null }
python, set, wordle, jupyter The line 39 while True: loop also exhibits logical redundancy; just lift the condition of the if statement to get a while loop with a single-line loop body. Too much verbosity obscures the purpose of the code. Solution design Nice to have top-level functions first and procedural programming beneath. Top-level items, like those functions, should be separated by two blank lines instead of just one. See the PEP. Start your procedural part with a if __name__ == '__main__' check. Then other developers can include your code as a module, and use its top-level functions, without the import process kickstarting your game. You should notice that you only need one of wd_dic and gu_dic. Because they each individually contain complete information about how the letters of the guess are present in the letters of the word, one alone should be enough to calculate all the green, yellow, and blue tiles. I would delegate the functionality of figuring out correct letters to its own function, instead of spreading it between lines 49-76 in the middle of the game loop logic. def answer(word: str, guess: str) -> list[int]: r'''Return the correctness of each guessed letter, the "tiles". :returns: a mapping of the letters in guess to 0 if the letter is not in the word, 2 if it is in the word and in the right place, 1 otherwise >>> answer('lemon', 'logic') [2, 1, 0, 0, 0] ''' places = { letter: occurrences(word, letter) for letter in guess } result = [] for i, letter in enumerate(guess): if not places[letter]: # no occurrences result.append(0) elif i in places[letter]: result.append(2) else: result.append(1) return result I would probably not use a dictionary at all tbh: return [0 if letter not in word else 1 if word[i] != letter else 2 for i, letter in enumerate(guess)]
{ "domain": "codereview.stackexchange", "id": 44112, "lm_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, set, wordle, jupyter", "url": null }
python, set, wordle, jupyter It was moving the functionality of getting the tiles to its own function that allowed me to see this possible simplification. Functional programming You may want to experiment with making functionally-pure functions instead of I/O modifying ones directly. So instead of def print_tile(tile, guess): for i in range(5): print(guess[i].upper(), end=' ') print(flush=True) ... print_tile(tile, guess) You would have def format_tiles(tiles, guess): return ' '.join(guess[i].upper() for i in range(5)) ... print(format_tiles(tiles, guess), flush=True) The logic appears in pure functions, and the I/O appears in its own section and it just calls those functions. Magic number In a few places you've written range(0,5), len(guess) != 5 etc. You're using 5 as a magic number, which is okay in this case since the code is for wordle specifically, and everyone understands it's a 5-letter-word guessing game, but magic numbers are bad practice in general. Define it in a variable word_length = 5, and use this everywhere else. Your input lists of words do not only contain length-5 words anyway, so changing word_length would let you play wordle in your program with other lengths of words, which could be fun. Functions, to remain pure, should take the word length as an input rather than using the global one, for example: def print_tile(tile, guess): for i in range(len(guess)): print(guess[i].upper(), end=' ') print(flush=True)
{ "domain": "codereview.stackexchange", "id": 44112, "lm_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, set, wordle, jupyter", "url": null }
c++, rcpp Title: Conditional expectations to fill in missing values Question: Given a matrix, which represents a multivariate time series, wherein some observations are missing, I want to calculate the most likely observation, given a covariance matrix. Notation: \$x_{-i}\$ represents some vector with the \$i\$th elements removed. Let \$m\$ be an index of missing observations, \$X\$ is a vector of observations, \$\Omega\$ is a covariance matrix, then \$X_m=X_{-m} \Omega_{-m,-m}^{-1}\Omega_{-m,m}\$ This calculation is repeated for every row. #include <RcppArmadillo.h> using namespace Rcpp; // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] arma::mat runLinearModelOverTimeInPlace(arma::mat returnsMat, arma::mat covMat) { int nrow = returnsMat.n_rows; for (int iRow = 0; iRow < nrow; iRow++){ arma::mat rowMat = returnsMat.row(iRow); arma::uvec missingIndex = find_nonfinite(rowMat); if (missingIndex.n_elem > 0) { arma::uvec notMissingIndex = find_finite(rowMat); arma::mat A = covMat.submat(notMissingIndex, notMissingIndex); arma::mat B = covMat.submat(notMissingIndex, missingIndex); arma::mat beta = arma::solve(A,B); arma::uvec rowIndexVec = arma::linspace<arma::uvec>(iRow, iRow, 1); arma::mat res = returnsMat.submat(rowIndexVec, notMissingIndex) * beta; returnsMat.submat(rowIndexVec, missingIndex) = res; } } return returnsMat; } Here is a test case that runs in R: runLinearModelOverTime = function(returns_with_holes, cov_returns) { N_sample = nrow(returns_with_holes) sapply(seq(1, N_sample), \(i){ res = returns_with_holes[i,] missingIndex = which(is.na(returns_with_holes[i,])) if(length(missingIndex)>0){ beta = solve(cov_returns[-missingIndex, -missingIndex], cov_returns[-missingIndex, missingIndex]) res[missingIndex] <- returns_with_holes[i,-missingIndex] %*% beta res } else { res } }) |> t() }
{ "domain": "codereview.stackexchange", "id": 44113, "lm_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++, rcpp", "url": null }
c++, rcpp set.seed(123) x = matrix(runif(60), nrow = 10) # x_ = x + 1 # x_ = x_ - 1 # all.equal(x, x_) y = cov(x) x[sample(60, 10)] <- NA expectedOutput = runLinearModelOverTime(x,y) actualOutput = runLinearModelOverTimeInPlace(x,y) all.equal(expectedOutput, actualOutput) Answer: Naming things The way you name things can be improved. First, don't add the type of a variable to its name. The type is already known to the compiler in another way, and it's probably clear to the reader of the code as well, so it just adds noise. Second, don't abbreviate things unnecessarily. Instead of cov, write covariance, so I don't have to guess whether it meant something else, like coverage or covalence. The name missingIndex is also confusing; it's not a single index, but rather a set of indices (I assume, because it's stored in a vector). I recommend you always use the plural for something that is a collection of things. So: missingIndices. Avoid overly verbose names. While missingIndices describes itself very well, it's quite long, and I think you can just name it missing; the fact that it's the indices is clear from the context in which it is used. iRow: I would just name this i; i and j are very commonly used names for indices, both in many programming languages and in mathematics. You might want to use i for rows and j for columns, since that's the order in which you pass them to many Armadillo functions. The parameter returnsMat is very misleading, it doesn't return anything. From your description of the problem, it sounds like it should have been named observations instead. This also brings me to the name of the function itself. It mentions InPlace, but since returnsMat is passed by value, it doesn't do anything in-place, instead a copy will have been made and you are modifying the copy before returning it. Keep things simple It took me a while to figure out what this was meant to be: arma::uvec rowIndexVec = arma::linspace<arma::uvec>(iRow, iRow, 1);
{ "domain": "codereview.stackexchange", "id": 44113, "lm_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++, rcpp", "url": null }
c++, rcpp It's just a vector with one element with value iRow. You could have created this much simpler this way: arma::uvec rowIndexVec = {iRow}; This causes a compiler warning about a narrowing conversion because iRow is a signed integer. Make sure it is arma::uword. But you could simplify things further. Consider that you already have rowMat. Instead of calculating returnsMat.submat(...), you can write: arma::mat result = rowMat.cols(notMissingIndex) * beta; Code after the above changes arma::mat runLinearModelOverTime(arma::mat observations, arma::mat covariance) { for (arma::uword i = 0; i < observations.n_rows; ++i) { auto row = observations.row(i); auto missing = find_nonfinite(row); if (missing.empty()) { continue; } auto notMissing = find_finite(row); auto A = covariance.submat(notMissing, notMissing); auto B = covariance.submat(notMissing, missing); auto beta = arma::solve(A, B); row.cols(missing) = row.cols(notMissing) * beta; } return observations; } Possible optimizations Consider that you can have multiple rows that have exactly the same non-finite columns. In that case, beta will have the same value for all those rows. If you have large matrices and a high chance of this happening, then it would make sense to somehow cache previously calculated values of beta.
{ "domain": "codereview.stackexchange", "id": 44113, "lm_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++, rcpp", "url": null }