body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I decided to write my own vector class template for learning purposes. My main goal was a correct interpretation of C++20 standard (<a href="https://wg21.link/n4810" rel="nofollow noreferrer">as of n4810</a>).</p> <p>I took some liberties and decided to use concepts instead of plain typenames for iterators instead of SFINAE. On the other hand, I decided against Empty Base Class optimization of allocator for the sake of simplicity.</p> <p>I think I managed to get most things right. The thing that bothers me the most is exception safety. Most of it is implemented inside <code>Move</code> and <code>Rollback</code> member functions. The standardese there was really hard to parse so you may want to inspect them more closely.</p> <p>In the future I plan to port all named requirements to concepts, if anyone has suggestions which ones can be swapped for concepts that are already in C++20, you're welcome.</p> <p><code>Body is limited to 65536 characters; you entered 66294.</code> Ugh, gotta trim stuff. Removed repeating wording in <code>[vector.modifiers]</code>.</p> <h1>Vector.h</h1> <pre><code>/// \file /// \brief Header file that describes the Vector class template. /// \author Lyberta /// \copyright GNU GPLv3 or any later version. #pragma once #include &lt;memory&gt; #include "Iterator.h" // For iterator concepts namespace ftz::General { /// \brief A vector class template compatible with std::vector. /// \details Vector is a sequence container that stores its elements /// contiguously. /// \tparam T Type of elements in a vector. /// \tparam Allocator Allocator used to manage memory. template &lt;typename T, typename Allocator = std::allocator&lt;T&gt;&gt; class Vector final { public: /// \brief Type of elements in a vector. using value_type = T; /// \brief Type of the allocator used to manage memory. using allocator_type = Allocator; /// \brief Type of pointers used by the allocator. using pointer = typename std::allocator_traits&lt;Allocator&gt;::pointer; /// \brief Type of pointers to const used by the allocator. using const_pointer = typename std::allocator_traits&lt;Allocator&gt;::const_pointer; /// \brief Type of references to elements of a vector. using reference = value_type&amp;; /// \brief Type of references to constant elements of a vector. using const_reference = const value_type&amp;; /// \brief Type used to hold the size of the vector. using size_type = typename std::allocator_traits&lt;Allocator&gt;::size_type; /// \brief Type used to hold the difference between iterators. using difference_type = typename std::allocator_traits&lt;Allocator&gt;::difference_type; /// \brief Forward iterator type. using iterator = pointer; /// \brief Constant forward iterator type. using const_iterator = const_pointer; /// \brief Reverse iterator type. using reverse_iterator = std::reverse_iterator&lt;iterator&gt;; /// \brief Constant reverse iterator type. using const_reverse_iterator = std::reverse_iterator&lt;const_iterator&gt;; /// \brief Default constructor. /// \pre Allocator is Cpp17DefaultConstructible. Vector() noexcept(noexcept(Allocator{})); /// \brief Constructors an empty vector using the specified allocator. /// \param[in] allocator Allocator to copy. explicit Vector(const Allocator&amp; allocator); /// \brief Constructs a vector with the specified amount of default /// inserted elements using the specified allocator. /// \pre [vector.cons] T is Cpp17DefaultInsertable into Vector. /// \param[in] amount Amount of elements to construct. /// \param[in] allocator Allocator to copy. explicit Vector(size_type amount, const Allocator&amp; allocator = Allocator{}); /// \brief Constructs a vector with the specified amount of the given value. /// \pre [sequence.reqmts] T is Cpp17CopyInsertable into Vector. /// \param[in] amount Amount of values to construct. /// \param[in] value Value to fill the vector with. /// \param[in] allocator Allocator to copy. Vector(size_type amount, const T&amp; value, const Allocator&amp; allocator = Allocator{}); /// \brief Constructs a vector from values pointed to by the range [first, /// last). /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible and /// Cpp17MoveInsertable into Vector. /// \tparam I Input iterator type. /// \param[in] first Iterator to the beginning of the range. /// \param[in] last Iterator past the end of the range. /// \param[in] allocator Allocator to copy. template &lt;InputIterator I&gt; Vector(I first, I last, const Allocator&amp; allocator = Allocator{}); /// \brief Constructs a vector from values pointed to by the range [first, /// last). /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible into Vector. /// \tparam I Forward iterator type. /// \param[in] first Iterator to the beginning of the range. /// \param[in] last Iterator past the end of the range. /// \param[in] allocator Allocator to copy. template &lt;ForwardIterator I&gt; Vector(I first, I last, const Allocator&amp; allocator = Allocator{}); /// \brief Copy constructor. /// \pre [container.requirements.general] T is Cpp17CopyInsertable into /// Vector. /// \param[in] other Vector to copy from. Vector(const Vector&amp; other); /// \brief Move constructor. /// \param[in] other Vector to move from. Vector(Vector&amp;&amp; other) noexcept; /// \brief Constructs a vector with the copies of elements from the other /// vector using the specified allocator. /// \pre [container.requirements.general] T is Cpp17CopyInsertable into /// Vector. /// \param[in] other Vector to copy from. /// \param[in] allocator Allocator to copy. Vector(const Vector&amp; other, const Allocator&amp; allocator); /// \brief Constructs a vector by moving elements from the other vector /// using the specified allocator. /// \pre [container.requirements.general] T is Cpp17MoveInsertable into /// Vector. /// \param[in] other Vector to move from. /// \param[in] allocator Allocator to copy. Vector(Vector&amp;&amp; other, const Allocator&amp; new_allocator); /// \brief Constructs a vector from the list of values using the specified /// allocator. /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible into Vector. /// \param[in] values Values to copy. /// \param[in] allocator Allocator to copy. Vector(std::initializer_list&lt;T&gt; values, const Allocator&amp; allocator = Allocator{}); /// \brief Copy assignment operator. /// \pre [container.requirements.general] T is Cpp17CopyInsertable into /// Vector and Cpp17CopyAssignable. /// \param[in] other Vector to copy from. /// \return Reference to this vector. Vector&amp; operator=(const Vector&amp; other); /// \brief Move assignment operator. /// \pre [container.requirements.general] If std::allocator_traits&lt; /// allocator_type&gt;::propagate_on_container_move_assignment::value is false, /// T is Cpp17MoveInsertable into Vector and Cpp17MoveAssignable. /// \param[in,out] other Vector to move from. /// \return Reference to this vector. Vector&amp; operator=(Vector&amp;&amp; other) noexcept( std::allocator_traits&lt;Allocator&gt;:: propagate_on_container_move_assignment::value || std::allocator_traits&lt;Allocator&gt;::is_always_equal::value); /// \brief Assigns a list of values to the vector. /// \pre [sequence.reqmts] T is Cpp17CopyInsertable into Vector and /// Cpp17CopyAssignable. /// \param[in] values Values to assign. /// \return Reference to this vector. Vector&amp; operator=(std::initializer_list&lt;T&gt; values); /// \brief Destructor. ~Vector(); /// \brief Assigns values pointed to by the range [first, last) to the /// vector. /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible, assignable from /// *first and Cpp17MoveInsertable into Vector. /// \tparam I Input iterator type. /// \param[in] first Iterator to the beginning of the range. /// \param[in] last Iterator past the end of the range. template &lt;InputIterator I&gt; void assign(I first, I last); /// \brief Assigns values pointed to by the range [first, last) to the /// vector. /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible into Vector and /// assignable from *first. /// \tparam I Forward iterator type. /// \param[in] first Iterator to the beginning of the range. /// \param[in] last Iterator past the end of the range. template &lt;ForwardIterator I&gt; void assign(I first, I last); /// \brief Assings the specified amount of the given value to the vector. /// \pre [sequence.reqmts] T is Cpp17CopyInsertable into Vector and /// Cpp17CopyAssignable. /// \param[in] amount Amount of values to assign. /// \param[in] value Value to fill the vector with. void assign(size_type amount, const T&amp; value); /// \brief Assigns a list of values to the vector. /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible into Vector and /// assignable from T&amp;. /// \param[in] values Values to assign. void assign(std::initializer_list&lt;T&gt; values); /// \brief Returns the allocator of the vector. /// \return Allocator of the vector. allocator_type get_allocator() const noexcept; // Iterators /// \brief Returns an iterator to the first element in the vector. /// \return Iterator to the first element in the vector. iterator begin() noexcept; /// \brief Returns a constant iterator to the first element in the vector. /// \return Constant iterator to the first element in the vector. const_iterator begin() const noexcept; /// \brief Returns an iterator to the position after the last element in the /// vector. /// \return Iterator to the position after the last element in the vector. iterator end() noexcept; /// \brief Returns a constant iterator to the position after the last /// element in the vector. /// \return Constant iterator to the position after the last element in the /// vector. const_iterator end() const noexcept; /// \brief Returns a reverse iterator to the first element in the reversed /// vector. /// \return Reverse iterator to the first element in the reversed vector. reverse_iterator rbegin() noexcept; /// \brief Returns a constant reverse iterator to the first element in the /// reversed vector. /// \return Constant reverse iterator to the first element in the reversed /// vector. const_reverse_iterator rbegin() const noexcept; /// \brief Returns a reverse iterator to the position after the last element /// in the reversed vector. /// \return Reverse iterator to the position after the last element in the /// reversed vector. reverse_iterator rend() noexcept; /// \brief Returns a constant reverse iterator to the position after the /// last element in the reversed vector. /// \return Constant reverse iterator to the position after the last element /// in the reversed vector. const_reverse_iterator rend() const noexcept; /// \brief Returns a constant iterator to the first element in the vector. /// \return Constant iterator to the first element in the vector. const_iterator cbegin() const noexcept; /// \brief Returns a constant iterator to the position after the last /// element in the vector. /// \return Constant iterator to the position after the last element in the /// vector. const_iterator cend() const noexcept; /// \brief Returns a constant reverse iterator to the first element in the /// reversed vector. /// \return Constant reverse iterator to the first element in the reversed /// vector. const_reverse_iterator crbegin() const noexcept; /// \brief Returns a constant reverse iterator to the position after the /// last element in the reversed vector. /// \return Constant reverse iterator to the position after the last element /// in the reversed vector. const_reverse_iterator crend() const noexcept; // Capacity /// \brief Checks if the vector contains any elements. /// \return True if there are no elements, false otherwise. [[nodiscard]] bool empty() const noexcept; /// \brief Returns the amount of elements in the vector. /// \return Amount of elements in the vector. size_type size() const noexcept; /// \brief Returns the maximum possible size of the vector. /// \return Maximum possible size of the vector. size_type max_size() const noexcept; /// \brief Returns the capacity of the vector. /// \return Capacity of the vector. size_type capacity() const noexcept; /// \brief Changes the amount of elements in the vector. /// \pre [vector.capacity] T is Cpp17MoveInsertable and /// Cpp17DefaultInsertable into Vector. /// \param[in] new_size Amount of elements to contain. /// \throw std::length_error If new size is greater than max_size(). /// \note Exception safety: [vector.capacity] If an exception is thrown /// other than by the move constructor of a non-Cpp17CopyInsertable T there /// are no effects. void resize(size_type new_size); /// \brief Changes the amount of elements in the vector. /// \pre [vector.capacity] T is Cpp17CopyInsertable into Vector. /// \param[in] new_size Amount of elements to contain. /// \param[in] value Value to initialize new elements with. /// \throw std::length_error If new size is greater than max_size(). /// \note Exception safety: [vector.capacity] Requires strong exception /// safety guarantee. void resize(size_type new_size, const T&amp; value); /// \brief Reserves the space for new elements. /// \pre [vector.capacity] T is Cpp17MoveInsertable into Vector. /// \param[in] new_capacity Amount of elements to reserve space for. /// \throw std::length_error If requested capacity is greater than /// max_size(). /// \note Exception safety: [vector.capacity] If an exception is thrown /// other than by the move constructor of a non-Cpp17CopyInsertable type, /// there are no effects. void reserve(size_type new_capacity); /// \brief Requests the removal of unused capacity. /// \pre [vector.capacity] T is Cpp17MoveInsertable into Vector. /// \note Exception safety: If an exception is thrown other than by the move /// constructor of a non-Cpp17CopyInsertable T there are no effects. void shrink_to_fit(); // Element access /// \brief Returns a reference to the element at the specified index. /// \param[in] index Index of the element. /// \return Reference to the element at the specified index. /// \note If the index is greater than or equal to size(), the behavior is /// undefined. reference operator[](size_type index); /// \brief Returns a reference to the constant element at the specified /// index. /// \param[in] index Index of the element. /// \return Reference to the constant element at the specified index. /// \note If the index is greater than or equal to size(), the behavior is /// undefined. const_reference operator[](size_type index) const; /// \brief Returns a reference to the element at the specified index. /// \param[in] index Index of the element. /// \return Reference to the element at the specified index. /// \throw std::out_of_range If the index is greater than or equal to /// size(). reference at(size_type index); /// \brief Returns a reference to the constant element at the specified /// index. /// \param[in] index Index of the element. /// \return Reference to the constant element at the specified index. /// \throw std::out_of_range If the index is greater than or equal to /// size(). const_reference at(size_type index) const; /// \brief Returns a reference to the first element in the vector. /// \return Reference to the first element in the vector. reference front(); /// \brief Returns a reference to the constant first element in the vector. /// \return Reference to the constant first element in the vector. const_reference front() const; /// \brief Returns a reference to the last element in the vector. /// \return Reference to the last element in the vector. reference back(); /// \brief Returns a reference to the constant last element in the vector. /// \return Reference to the constant last element in the vector. const_reference back() const; // Data access /// \brief Returns a pointer to the elements of the vector. /// \return Pointer to the elements of the vector. T* data() noexcept; /// \brief Returns a pointer to the constant elements of the vector. /// \return Pointer to the constant elements of the vector. const T* data() const noexcept; // Modifiers /// \brief Constructs the element in-place with the given arguments at the /// end of the vector. /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible and /// Cpp17MoveInsertable into Vector. /// \tparam Args Types of the arguments to the constructor. /// \param[in,out] args Arguments to construct element with. /// \return Reference to the constructed element. /// \note Exception safety: [vector.modifiers] If an exception is thrown /// other than by the copy constructor, move constructor, assignment /// operator, or move assignment operator of T or by any InputIterator /// operation there are no effects. If an exception is thrown while /// inserting a single element at the end and T is Cpp17CopyInsertable or /// std::is_nothrow_move_constructible_v&lt;T&gt; is true, there are no effects. /// Otherwise, if an exception is thrown by the move constructor of a /// non-Cpp17CopyInsertable T, the effects are unspecified. This overrides /// the strong exception safety guarantee in /// [container.requirements.general]. template &lt;typename... Args&gt; reference emplace_back(Args&amp;&amp;... args); /// \brief Copies the given value to the end of the vector. /// \pre [sequence.reqmts] T is Cpp17CopyInsertable into Vector. /// \param[in] value Value to copy. /// \note Exception safety: [vector.modifiers] SNIP void push_back(const T&amp; value); /// \brief Moves the given value to the end of the vector. /// \pre [sequence.reqmts] T is Cpp17MoveInsertable into Vector. /// \param[in] value Value to move. /// \note Exception safety: [vector.modifiers] SNIP void push_back(T&amp;&amp; value); /// \brief Removes the last element from the vector. /// \throws [vector.modifiers] Nothing unless an exception is thrown by the /// assignment operator or move assignment operator of T. This overrides the /// noexcept guarantee in [container.requirements.general]. void pop_back(); /// \brief Constructs the element in-place with the given arguments before /// the position pointed to by the iterator. /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible and /// Cpp17MoveInsertable into Vector and Cpp17MoveAssignable. /// \tparam Args Types of the arguments to the constructor. /// \param[in] position Iterator pointing to the position of insertion. /// \param[in,out] args Arguments to construct element with. /// \return Iterator pointing to the constructed element. /// \note Exception safety: [vector.modifiers] SNIP template &lt;typename... Args&gt; iterator emplace(const_iterator position, Args&amp;&amp;... args); /// \brief Inserts the given value before the position pointed to by the /// iterator via copying. /// \pre [sequence.reqmts] T is Cpp17CopyInsertable into Vector and /// Cpp17CopyAssignable. /// \param[in] position Iterator pointing to the position of insertion. /// \param[in] value Value to insert. /// \return Iterator pointing to the inserted element. /// \note Exception safety: [vector.modifiers] SNIP iterator insert(const_iterator position, const T&amp; value); /// \brief Inserts the given value before the position pointed to by the /// iterator via moving. /// \pre [sequence.reqmts] T is Cpp17MoveInsertable into Vector and /// Cpp17MoveAssignable. /// \param[in] position Iterator pointing to the position of insertion. /// \param[in] value Value to insert. /// \return Iterator pointing to the inserted element. /// \note Exception safety: [vector.modifiers] SNIP iterator insert(const_iterator position, T&amp;&amp; value); /// \brief Inserts the specified amount of the given value before the /// position pointed to by the iterator. /// \pre [sequence.reqmts] T is Cpp17CopyInsertable into Vector and /// Cpp17CopyAssignable. /// \param[in] position Iterator pointing to the position of insertion. /// \param[in] amount Amount to insert. /// \param[in] value Value to insert. /// \return Iterator pointing to first inserted element or provided iterator /// if no elements were inserted. /// \note Exception safety: [vector.modifiers] SNIP iterator insert(const_iterator position, size_type amount, const T&amp; value); /// \brief Inserts values pointed to by the range [first, last) before the /// position pointed to by the iterator. /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible and /// Cpp17MoveInsertable into Vector, Cpp17MoveConstructible, /// Cpp17MoveAssignable and swappable. /// \tparam I Input iterator type. /// \param[in] position Iterator pointing to the position of insertion. /// \param[in] first Iterator to the beginning of the range. /// \param[in] last Iterator past the end of the range. /// \return Iterator pointing to first inserted element or provided iterator /// if no elements were inserted. /// \note Exception safety: [vector.modifiers] SNIP template &lt;InputIterator I&gt; iterator insert(const_iterator position, I first, I last); /// \brief Inserts values pointed to by the range [first, last) before the /// position pointed to by the iterator. /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible and /// Cpp17MoveInsertable into Vector, Cpp17MoveConstructible, /// Cpp17MoveAssignable and swappable. /// \tparam I Forward iterator type. /// \param[in] position Iterator pointing to the position of insertion. /// \param[in] first Iterator to the beginning of the range. /// \param[in] last Iterator past the end of the range. /// \return Iterator pointing to first inserted element or provided iterator /// if no elements were inserted. /// \note Exception safety: [vector.modifiers] SNIP template &lt;ForwardIterator I&gt; iterator insert(const_iterator position, I first, I last); /// \brief Inserts a list of values before the position pointed to by the /// iterator. /// \pre [sequence.reqmts] T is Cpp17EmplaceConstructible and /// Cpp17MoveInsertable into Vector, Cpp17MoveConstructible, /// Cpp17MoveAssignable and swappable. /// \param[in] position Iterator pointing to the position of insertion. /// \param[in] list List of values to insert. /// \return Iterator pointing to the the first inserted element or provided /// iterator if no elements were inserted. /// \note Exception safety: [vector.modifiers] SNIP iterator insert(const_iterator position, std::initializer_list&lt;T&gt; values); /// \brief Erases the element at the position pointed to by the iterator. /// \pre [sequence.reqmts] T is Cpp17MoveAssignable. /// \param[in] position Iterator pointing to the element to be removed. /// \return Iterator pointing to the position after the removed element. /// \throw [vector.modifiers] Nothing unless an exception is thrown by the /// assignment operator or move assignment operator of T. This overrides the /// noexcept guarantee in [container.requirements.general]. iterator erase(const_iterator position); /// \brief Erases elements pointed to by the range [first, last) in the /// vector. /// \pre [sequence.reqmts] T is Cpp17MoveAssignable. /// \param[in] first Iterator to the beginning of the range. /// \param[in] last Iterator past the end of the range. /// \return Iterator pointing to the position after the last removed /// element. /// \throw [vector.modifiers] Nothing unless an exception is thrown by the /// assignment operator or move assignment operator of T. This overrides the /// noexcept guarantee in [container.requirements.general]. iterator erase(const_iterator first, const_iterator last); /// \brief Exchanges the contents and capacity with another vector. /// \param[in,out] other Vector to swap with. void swap(Vector&amp; other) noexcept( std::allocator_traits&lt;Allocator&gt;::propagate_on_container_swap::value || std::allocator_traits&lt;Allocator&gt;::is_always_equal::value); /// \brief Removes all elements from the vector without affecting capacity. /// \note Exception safety: [container.requirements.general] Requires /// noexcept. void clear() noexcept; private: pointer m_elements; ///&lt; Holds all elements. size_type m_buffer_capacity; ///&lt; Capacity of the vector. size_type m_buffer_size; ///&lt; Amount of constructed elements. Allocator m_allocator; ///&lt; Allocator used to manage memory. /// \brief Returns capacity that will be enough to store given amount of /// elements. /// \param[in] amount Amount of elements that need to be stored. /// \return Capacity that is enough to store given amount of elements. /// \throw std::length_error If amount is greater than the maximum /// allocation size. size_type GetSufficientCapacity(size_type amount) const; /// \brief Allocates the space for the given amount of the elements. /// \param[in] new_capacity Amount of elements to allocate for. /// \warning If the buffer is already allocated, a memory leak will occur. void Allocate(size_type new_capacity); /// \brief Destructs all constructed elements and deallocates the /// buffer. void Deallocate(); /// \brief Constructs a new element at the end of the buffer. /// \tparam Args Types of the arguments to the constructor of the element. /// \param[in, out] args Arguments to the constructor of the element. /// \warning If the buffer is full, the behavior is undefined. template &lt;typename... Args&gt; void Construct(Args&amp;&amp;... args); /// \brief Destroys the element at the end of the buffer. /// \warning If the buffer is empty, the behavior is undefined. void Destroy(); /// \brief Allocates new vector with the exact given capacity and the given /// allocator. /// \param[in] new_capacity Capacity to allocate. /// \param[in] new_allocator Allocator to use. /// \return New vector with the given capacity and allocator. static Vector CreateNewBuffer(size_type new_capacity, const Allocator&amp; new_allocator); /// \brief Moves the elements pointed to by the range [first, last) to the /// end of the given vector. Used during reallocations. /// \param[in] first Iterator to the beginning of the range. /// \param[in] last Iterator past the end of the range. /// \param[in,out] buffer Vector to move elements to. /// \note If the elements have throwing move constructor, this function will /// actually try to copy them. This is used to preserve strong exception /// safety. static void Move(iterator first, iterator last, Vector&amp; buffer); /// \brief Moves all elements to the given vector. Used during /// reallocations. /// \param[in,out] buffer Vector to move elements to. /// \note If the elements have throwing move constructor, this function will /// actually try to copy them. This is used to preserve strong exception /// safety. void MoveAll(Vector&amp; buffer); /// \brief Moves elements pointed to by the range [std::begin(other), last) /// back to this vector. Used to implement strong exception safety /// guarantee. /// \param[in,out] other Vector to move elements from. /// \param[in] last Iterator past the last element to be moved. /// \note This function does nothing if elements were copied. void Rollback(Vector&amp; other, iterator last) noexcept; /// \brief Assumes the state of the given vector. /// \param[in,out] other Vector to assume the state of. void Commit(Vector&amp;&amp; other) noexcept; /// \brief Checks if the given iterator is valid. /// \param[in] it Iterator to check. /// \throw std::out_of_range If iterator is invalid. void ValidateIterator(const_iterator it) const; }; /// \brief Compares two vectors. /// \pre [container.requirements.general] T is Cpp17EqualityComparable. /// \param[in] lhs First vector. /// \param[in] rhs Second vector. /// \return True if vectors are equal, false otherwise. template &lt;typename T, typename Allocator&gt; bool operator==(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs); /// \brief Compares two vectors. /// \pre [container.requirements.general] T is Cpp17EqualityComparable. /// \param[in] lhs First vector. /// \param[in] rhs Second vector. /// \return True if vectors are not equal, false otherwise. template &lt;typename T, typename Allocator&gt; bool operator!=(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs); /// \brief Compares two vectors. /// \pre [container.requirements.general] operator&lt; is defined, producing total /// order. /// \param[in] lhs First vector. /// \param[in] rhs Second vector. /// \return True when first vector is less than the second one, false otherwise. template &lt;typename T, typename Allocator&gt; bool operator&lt;(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs); /// \brief Compares two vectors. /// \pre [container.requirements.general] operator&lt; is defined, producing total /// order. /// \param[in] lhs First vector. /// \param[in] rhs Second vector. /// \return True when first vector is greater than the second one, false /// otherwise. template &lt;typename T, typename Allocator&gt; bool operator&gt;(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs); /// \brief Compares two vectors. /// \pre [container.requirements.general] operator&lt; is defined, producing total /// order. /// \param[in] lhs First vector. /// \param[in] rhs Second vector. /// \return True when first vector is less than or equal to the second one, /// false otherwise. template &lt;typename T, typename Allocator&gt; bool operator&lt;=(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs); /// \brief Compares two vectors. /// \pre [container.requirements.general] operator&lt; is defined, producing total /// order. /// \param[in] lhs First vector. /// \param[in] rhs Second vector. /// \return True when first vector is greater than or equal to the second one, /// false otherwise. template &lt;typename T, typename Allocator&gt; bool operator&gt;=(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs); } #include "Vector.hpp" </code></pre> <h1>Vector.hpp</h1> <pre><code>/// \file /// \brief Internal header file that contains implementation of the Vector class /// template. /// \author Lyberta /// \copyright GNU GPLv3 or any later version. #pragma once namespace ftz::General { template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::Vector() noexcept(noexcept(Allocator{})) : Vector{Allocator{}} { } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::Vector(const Allocator&amp; allocator) : m_elements{nullptr}, m_buffer_capacity{0}, m_buffer_size{0}, m_allocator{allocator} { } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::Vector(size_type amount, const Allocator&amp; allocator) : Vector{allocator} { this-&gt;resize(amount); } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::Vector(size_type amount, const T&amp; value, const Allocator&amp; allocator) : Vector{allocator} { this-&gt;resize(amount, value); } template &lt;typename T, typename Allocator&gt; template &lt;InputIterator I&gt; Vector&lt;T, Allocator&gt;::Vector(I first, I last, const Allocator&amp; allocator) : Vector{allocator} { this-&gt;assign(first, last); } template &lt;typename T, typename Allocator&gt; template &lt;ForwardIterator I&gt; Vector&lt;T, Allocator&gt;::Vector(I first, I last, const Allocator&amp; allocator) : Vector{allocator} { this-&gt;assign(first, last); } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::Vector(const Vector&amp; other) : Vector{other, std::allocator_traits&lt;Allocator&gt;::select_on_container_copy_construction( other.m_allocator)} { } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::Vector(Vector&amp;&amp; other) noexcept : m_elements{other.m_elements}, m_buffer_capacity{other.m_buffer_capacity}, m_buffer_size{other.m_buffer_size}, m_allocator{other.m_allocator} { other.m_elements = nullptr; other.m_buffer_capacity = 0; other.m_buffer_size = 0; } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::Vector(const Vector&amp; other, const Allocator&amp; allocator) : Vector{allocator} { this-&gt;assign(std::begin(other), std::end(other)); } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::Vector(Vector&amp;&amp; other, const Allocator&amp; new_allocator) : Vector{new_allocator} { if (m_allocator == other.m_allocator) { m_elements = other.m_elements; m_buffer_capacity = other.m_buffer_capacity; m_buffer_size = other.m_buffer_size; other.m_elements = nullptr; other.m_buffer_capacity = 0; other.m_buffer_size = 0; return; } this-&gt;Allocate(this-&gt;GetSufficientCapacity(other.m_buffer_size)); std::move(std::begin(other), std::end(other), std::back_inserter(*this)); } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::Vector(std::initializer_list&lt;T&gt; values, const Allocator&amp; allocator) : Vector{allocator} { this-&gt;assign(values); } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;&amp; Vector&lt;T, Allocator&gt;::operator=(const Vector&amp; other) { if (std::allocator_traits&lt;Allocator&gt;:: propagate_on_container_copy_assignment::value == false) { Vector new_buffer{other, m_allocator}; this-&gt;Commit(std::move(new_buffer)); return *this; } Vector new_buffer{other}; this-&gt;Commit(std::move(new_buffer)); return *this; } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;&amp; Vector&lt;T, Allocator&gt;::operator=(Vector&amp;&amp; other) noexcept( std::allocator_traits&lt;Allocator&gt;::propagate_on_container_move_assignment:: value || std::allocator_traits&lt;Allocator&gt;::is_always_equal::value) { if (std::allocator_traits&lt;Allocator&gt;:: propagate_on_container_move_assignment::value == true) { this-&gt;Commit(std::move(other)); return *this; } if (m_allocator == other.m_allocator) { this-&gt;Deallocate(); m_elements = other.m_elements; m_buffer_capacity = other.m_buffer_capacity; m_buffer_size = other.m_buffer_size; // No allocator assignment. other.m_elements = nullptr; other.m_buffer_capacity = 0; other.m_buffer_size = 0; return *this; } Vector new_buffer{this-&gt;GetSufficientCapacity(other.m_buffer_size), m_allocator}; this-&gt;MoveAll(new_buffer); this-&gt;Commit(std::move(new_buffer)); return *this; } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;&amp; Vector&lt;T, Allocator&gt;::operator=( std::initializer_list&lt;T&gt; values) { this-&gt;assign(values); return *this; } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt;::~Vector() { if (m_elements == nullptr) { return; } this-&gt;Deallocate(); } template &lt;typename T, typename Allocator&gt; template &lt;InputIterator I&gt; void Vector&lt;T, Allocator&gt;::assign(I first, I last) { if (m_buffer_size == 0) { try { std::copy(first, last, std::back_inserter(*this)); } catch (...) { this-&gt;clear(); throw; } return; } Vector new_buffer{m_allocator}; this-&gt;Commit(std::move(new_buffer)); } template &lt;typename T, typename Allocator&gt; template &lt;ForwardIterator I&gt; void Vector&lt;T, Allocator&gt;::assign(I first, I last) { if (first == last) { this-&gt;clear(); return; } if (m_buffer_size == 0) { if (m_buffer_capacity == 0) { this-&gt;Allocate(this-&gt;GetSufficientCapacity( std::distance(first, last))); } try { std::copy(first, last, std::back_inserter(*this)); } catch (...) { this-&gt;clear(); throw; } return; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( std::distance(first, last)), m_allocator); std::copy(first, last, std::back_inserter(new_buffer)); this-&gt;Commit(std::move(new_buffer)); } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::assign(size_type amount, const T&amp; value) { if (m_buffer_size == 0) { try { std::fill_n(std::back_inserter(*this), amount, value); } catch (...) { this-&gt;clear(); throw; } return; } Vector new_buffer{amount, value, m_allocator}; this-&gt;Commit(std::move(new_buffer)); } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::assign(std::initializer_list&lt;T&gt; values) { this-&gt;assign(std::begin(values), std::end(values)); } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::allocator_type Vector&lt;T, Allocator&gt;:: get_allocator() const noexcept { return m_allocator; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::begin() noexcept { return m_elements; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_iterator Vector&lt;T, Allocator&gt;::begin() const noexcept { return m_elements; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::end() noexcept { return m_elements + m_buffer_size; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_iterator Vector&lt;T, Allocator&gt;::end() const noexcept { return m_elements + m_buffer_size; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::reverse_iterator Vector&lt;T, Allocator&gt;::rbegin() noexcept { return reverse_iterator{this-&gt;end()}; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_reverse_iterator Vector&lt;T, Allocator&gt;:: rbegin() const noexcept { return const_reverse_iterator{this-&gt;end()}; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::reverse_iterator Vector&lt;T, Allocator&gt;::rend() noexcept { return reverse_iterator{this-&gt;begin()}; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_reverse_iterator Vector&lt;T, Allocator&gt;:: rend() const noexcept { return const_reverse_iterator{this-&gt;begin()}; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_iterator Vector&lt;T, Allocator&gt;::cbegin() const noexcept { return m_elements; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_iterator Vector&lt;T, Allocator&gt;::cend() const noexcept { return m_elements + m_buffer_size; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_reverse_iterator Vector&lt;T, Allocator&gt;:: crbegin() const noexcept { return const_reverse_iterator{this-&gt;end()}; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_reverse_iterator Vector&lt;T, Allocator&gt;:: crend() const noexcept { return const_reverse_iterator{this-&gt;begin()}; } template &lt;typename T, typename Allocator&gt; [[nodiscard]] bool Vector&lt;T, Allocator&gt;::empty() const noexcept { return m_buffer_size == 0; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::size_type Vector&lt;T, Allocator&gt;::size() const noexcept { return m_buffer_size; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::size_type Vector&lt;T, Allocator&gt;::max_size() const noexcept { return std::allocator_traits&lt;Allocator&gt;::max_size(m_allocator); } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::size_type Vector&lt;T, Allocator&gt;::capacity() const noexcept { return m_buffer_capacity; } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::resize(size_type new_size) { if (new_size == m_buffer_size) { return; } if (new_size &lt; m_buffer_size) { while (m_buffer_size != new_size) { this-&gt;pop_back(); } return; } if (m_buffer_capacity == 0) { this-&gt;Allocate(this-&gt;GetSufficientCapacity(new_size)); } if (new_size &lt;= m_buffer_capacity) { size_type amount_to_construct = new_size - m_buffer_size; for (size_type i = 0; i &lt; amount_to_construct; ++i) { this-&gt;Construct(); } return; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity(new_size), m_allocator); this-&gt;MoveAll(new_buffer); try { size_type amount_to_construct = new_size - m_buffer_size; auto old_buffer_size = m_buffer_size; try { for (size_type i = 0; i &lt; amount_to_construct; ++i) { this-&gt;Construct(); } } catch (...) { while (m_buffer_size != old_buffer_size) { this-&gt;Destroy(); } throw; } } catch (...) { this-&gt;Rollback(new_buffer, std::begin(new_buffer) + m_buffer_size); throw; } this-&gt;Commit(std::move(new_buffer)); } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::resize(size_type new_size, const T&amp; value) { if (new_size == m_buffer_size) { return; } if (new_size &lt; m_buffer_size) { while (m_buffer_size != new_size) { this-&gt;pop_back(); } return; } if (m_buffer_capacity == 0) { this-&gt;Allocate(this-&gt;GetSufficientCapacity(new_size)); } if (new_size &lt;= m_buffer_capacity) { size_type amount_to_construct = new_size - m_buffer_size; auto old_buffer_size = m_buffer_size; try { for (size_type i = 0; i &lt; amount_to_construct; ++i) { this-&gt;Construct(value); } } catch (...) { while (m_buffer_size != old_buffer_size) { this-&gt;Destroy(); } throw; } return; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity(new_size), m_allocator); this-&gt;MoveAll(new_buffer); try { size_type amount_to_construct = new_size - m_buffer_size; for (size_type i = 0; i &lt; amount_to_construct; ++i) { new_buffer.Construct(value); } } catch (...) { this-&gt;Rollback(new_buffer, std::begin(new_buffer) + m_buffer_size); throw; } this-&gt;Commit(std::move(new_buffer)); } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::reserve(size_type new_capacity) { if (new_capacity &lt;= m_buffer_capacity) { return; } if (m_buffer_capacity == 0) { this-&gt;Allocate(new_capacity); return; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity(new_capacity), m_allocator); this-&gt;MoveAll(new_buffer); this-&gt;Commit(std::move(new_buffer)); } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::shrink_to_fit() { if (m_buffer_size == m_buffer_capacity) { return; } auto new_buffer = CreateNewBuffer(m_buffer_size, m_allocator); this-&gt;MoveAll(new_buffer); this-&gt;Commit(std::move(new_buffer)); } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::reference Vector&lt;T, Allocator&gt;::operator[]( size_type index) { return m_elements[index]; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_reference Vector&lt;T, Allocator&gt;::operator[]( size_type index) const { return m_elements[index]; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::reference Vector&lt;T, Allocator&gt;::at( size_type index) { if (index &gt;= m_buffer_size) { throw std::out_of_range{"Vector::at: Index is out of range."}; } return m_elements[index]; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_reference Vector&lt;T, Allocator&gt;::at( size_type index) const { if (index &gt;= m_buffer_size) { throw std::out_of_range{"Vector::at: Index is out of range."}; } return m_elements[index]; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::reference Vector&lt;T, Allocator&gt;::front() { return *m_elements; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_reference Vector&lt;T, Allocator&gt;::front() const { return *m_elements; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::reference Vector&lt;T, Allocator&gt;::back() { return *(m_elements + m_buffer_size - 1); } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::const_reference Vector&lt;T, Allocator&gt;::back() const { return *(m_elements + m_buffer_size - 1); } template &lt;typename T, typename Allocator&gt; T* Vector&lt;T, Allocator&gt;::data() noexcept { return std::to_address(m_elements); } template &lt;typename T, typename Allocator&gt; const T* Vector&lt;T, Allocator&gt;::data() const noexcept { return std::to_address(m_elements); } template &lt;typename T, typename Allocator&gt; template &lt;typename... Args&gt; typename Vector&lt;T, Allocator&gt;::reference Vector&lt;T, Allocator&gt;::emplace_back( Args&amp;&amp;... args) { if (m_buffer_capacity == 0) { this-&gt;Allocate(this-&gt;GetSufficientCapacity(1)); } if (m_buffer_size &lt; m_buffer_capacity) { this-&gt;Construct(std::forward&lt;Args&gt;(args)...); return this-&gt;back(); } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( m_buffer_size + 1), m_allocator); this-&gt;MoveAll(new_buffer); try { new_buffer.Construct(std::forward&lt;Args&gt;(args)...); } catch (...) { this-&gt;Rollback(new_buffer, std::end(new_buffer)); throw; } this-&gt;Commit(std::move(new_buffer)); return this-&gt;back(); } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::push_back(const T&amp; value) { if (m_buffer_capacity == 0) { this-&gt;Allocate(this-&gt;GetSufficientCapacity(1)); } if (m_buffer_size &lt; m_buffer_capacity) { this-&gt;Construct(value); return; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( m_buffer_size + 1), m_allocator); this-&gt;MoveAll(new_buffer); try { new_buffer.Construct(value); } catch (...) { this-&gt;Rollback(new_buffer, std::end(new_buffer)); throw; } this-&gt;Commit(std::move(new_buffer)); } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::push_back(T&amp;&amp; value) { if (m_buffer_capacity == 0) { this-&gt;Allocate(this-&gt;GetSufficientCapacity(1)); } if (m_buffer_size &lt; m_buffer_capacity) { this-&gt;Construct(std::move(value)); return; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( m_buffer_size + 1), m_allocator); this-&gt;MoveAll(new_buffer); try { new_buffer.Construct(std::move(value)); } catch (...) { this-&gt;Rollback(new_buffer, std::end(new_buffer)); throw; } this-&gt;Commit(std::move(new_buffer)); } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::pop_back() { if (m_buffer_size == 0) { return; } this-&gt;Destroy(); } template &lt;typename T, typename Allocator&gt; template &lt;typename... Args&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::emplace( const_iterator position, Args&amp;&amp;... args) { this-&gt;ValidateIterator(position); auto pos = const_cast&lt;iterator&gt;(position); if (m_buffer_size &lt; m_buffer_capacity) { if (pos == std::end(*this)) { this-&gt;Construct(std::forward&lt;Args&gt;(args)...); return pos; } this-&gt;Construct(std::move(this-&gt;back())); std::move_backward(pos, std::end(*this) - 1, std::end(*this)); pos = T(std::forward&lt;Args&gt;(args)...); return pos; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( m_buffer_size + 1), m_allocator); Move(std::begin(*this), pos, new_buffer); try { new_buffer.Construct(std::forward&lt;Args&gt;(args)...); } catch (...) { this-&gt;Rollback(new_buffer, std::end(new_buffer)); throw; } Move(pos, std::end(*this), new_buffer); auto offset = pos - std::begin(*this); this-&gt;Commit(std::move(new_buffer)); return std::begin(*this) + offset; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::insert( const_iterator position, const T&amp; value) { this-&gt;ValidateIterator(position); auto pos = const_cast&lt;iterator&gt;(position); if (m_buffer_size &lt; m_buffer_capacity) { if (pos == std::end(*this)) { this-&gt;Construct(value); return pos; } this-&gt;Construct(std::move(this-&gt;back())); std::move_backward(pos, std::end(*this) - 1, std::end(*this)); pos = value; return pos; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( m_buffer_size + 1), m_allocator); Move(std::begin(*this), pos, new_buffer); try { new_buffer.Construct(value); } catch (...) { this-&gt;Rollback(new_buffer, std::end(new_buffer)); throw; } Move(pos, std::end(*this), new_buffer); auto offset = pos - std::begin(*this); this-&gt;Commit(std::move(new_buffer)); return std::begin(*this) + offset; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::insert( const_iterator position, T&amp;&amp; value) { this-&gt;ValidateIterator(position); auto pos = const_cast&lt;iterator&gt;(position); if (m_buffer_size &lt; m_buffer_capacity) { if (pos == std::end(*this)) { this-&gt;Construct(std::move(value)); return pos; } this-&gt;Construct(std::move(this-&gt;back())); std::move_backward(pos, std::end(*this) - 1, std::end(*this)); *pos = std::move(value); return pos; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( m_buffer_size + 1), m_allocator); Move(std::begin(*this), pos, new_buffer); try { new_buffer.Construct(std::move(value)); } catch (...) { this-&gt;Rollback(new_buffer, std::end(new_buffer)); throw; } Move(pos, std::end(*this), new_buffer); auto offset = pos - std::begin(*this); this-&gt;Commit(std::move(new_buffer)); return std::begin(*this) + offset; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::insert( const_iterator position, size_type amount, const T&amp; value) { this-&gt;ValidateIterator(position); auto pos = const_cast&lt;iterator&gt;(position); if (amount == 0) { return pos; } if (m_buffer_size + amount &lt;= capacity) { if (pos == std::end(*this)) { auto old_buffer_size = m_buffer_size; try { for (size_type i = 0; i &lt; amount; ++i) { this-&gt;Construct(value); } } catch (...) { while (m_buffer_size != old_buffer_size) { this-&gt;Destroy(); } throw; } return pos; } auto last_move = std::end(*this); for (auto i = std::end(*this) - amount, end = std::end(*this); i != end; ++i) { this-&gt;Construct(std::move(*i)); } std::move_backward(pos, pos + amount, last_move); std::fill_n(pos, amount, value); return pos; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( m_buffer_size + amount), m_allocator); Move(std::begin(*this), pos, new_buffer); auto offset = pos - std::begin(*this); try { for (size_type i = 0; i &lt; amount; ++i) { new_buffer.Construct(value); } } catch (...) { this-&gt;Rollback(new_buffer, std::begin(new_buffer) + offset); throw; } Move(pos, std::end(*this), new_buffer); this-&gt;Commit(std::move(new_buffer)); return std::begin(*this) + offset; } template &lt;typename T, typename Allocator&gt; template &lt;InputIterator I&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::insert( const_iterator position, I first, I last) { this-&gt;ValidateIterator(position); auto pos = const_cast&lt;iterator&gt;(position); if (first == last) { return pos; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( m_buffer_size + 1), m_allocator); Move(std::begin(*this), pos, new_buffer); auto offset = pos - std::begin(*this); try { while (first != last) { new_buffer.Construct(*first); ++first; } } catch (...) { this-&gt;Rollback(new_buffer, std::begin(new_buffer) + offset); throw; } Move(pos, std::end(*this), new_buffer); this-&gt;Commit(std::move(new_buffer)); return std::begin(*this) + offset; } template &lt;typename T, typename Allocator&gt; template &lt;ForwardIterator I&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::insert( const_iterator position, I first, I last) { this-&gt;ValidateIterator(position); auto pos = const_cast&lt;iterator&gt;(position); if (first == last) { return pos; } auto amount = std::distance(first, last); if (m_buffer_size + amount &lt;= capacity) { if (pos == std::end(*this)) { auto old_buffer_size = m_buffer_size; try { while (first != last) { this-&gt;Construct(*first); ++first; } } catch (...) { while (m_buffer_size != old_buffer_size) { this-&gt;Destroy(); } throw; } return pos; } auto last_move = std::end(*this); for (auto i = std::end(*this) - amount, end = std::end(*this); i != end; ++i) { this-&gt;Construct(std::move(*i)); } std::move_backward(pos, pos + amount, last_move); std::copy(first, last, pos); return pos; } auto new_buffer = CreateNewBuffer(this-&gt;GetSufficientCapacity( m_buffer_size + amount), m_allocator); Move(std::begin(*this), pos, new_buffer); auto offset = pos - std::begin(*this); try { while (first != last) { new_buffer.Construct(*first); ++first; } } catch (...) { this-&gt;Rollback(new_buffer, std::begin(new_buffer) + offset); throw; } Move(pos, std::end(*this), new_buffer); this-&gt;Commit(std::move(new_buffer)); return std::begin(*this) + offset; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::insert( const_iterator position, std::initializer_list&lt;T&gt; values) { return this-&gt;insert(position, std::begin(values), std::end(values)); } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::erase( const_iterator position) { this-&gt;ValidateIterator(position); auto pos = const_cast&lt;iterator&gt;(position); std::move(pos + 1, std::end(*this), pos); this-&gt;Destroy(); return pos; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::iterator Vector&lt;T, Allocator&gt;::erase( const_iterator first, const_iterator last) { this-&gt;ValidateIterator(first); this-&gt;ValidateIterator(last); std::move(const_cast&lt;iterator&gt;(last), std::end(*this), const_cast&lt;iterator&gt;(first)); iterator pos = first; while (first != last) { this-&gt;Destroy(); ++first; } return pos; } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::swap(Vector&amp; other) noexcept( std::allocator_traits&lt;Allocator&gt;::propagate_on_container_swap::value || std::allocator_traits&lt;Allocator&gt;::is_always_equal::value) { using std::swap; swap(m_elements, other.m_elements); std::swap(m_buffer_capacity, other.m_buffer_capacity); std::swap(m_buffer_size, other.m_buffer_size); if (std::allocator_traits&lt;Allocator&gt;::propagate_on_container_swap::value == true) { swap(m_allocator, other.m_allocator); } } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::clear() noexcept { for (auto i = m_elements, end = i + m_buffer_size; i != end; ++i) { try { this-&gt;Destroy(); } catch (...) { } } m_buffer_size = 0; } template &lt;typename T, typename Allocator&gt; typename Vector&lt;T, Allocator&gt;::size_type Vector&lt;T, Allocator&gt;:: GetSufficientCapacity(size_type amount) const { auto max_size = std::allocator_traits&lt;Allocator&gt;::max_size(m_allocator); if (amount &gt; max_size) { throw std::length_error{"Vector::GetSufficientCapacity: " "The requested amount is bigger than the maximum supported by the " "allocator."}; } size_type new_capacity = std::ceil2(amount); if (new_capacity &gt; max_size) { throw std::length_error{"Vector::GetSufficientCapacity: " "The requested amount is bigger than the maximum supported by the " "allocator."}; } return new_capacity; } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::Allocate(size_type new_capacity) { m_elements = std::allocator_traits&lt;Allocator&gt;::allocate(m_allocator, new_capacity); m_buffer_capacity = new_capacity; } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::Deallocate() { this-&gt;clear(); std::allocator_traits&lt;Allocator&gt;::deallocate(m_allocator, m_elements, m_buffer_capacity); m_elements = nullptr; m_buffer_capacity = 0; } template &lt;typename T, typename Allocator&gt; template &lt;typename... Args&gt; void Vector&lt;T, Allocator&gt;::Construct(Args&amp;&amp;... args) { std::allocator_traits&lt;Allocator&gt;::construct(m_allocator, std::to_address(m_elements + m_buffer_size), std::forward&lt;Args&gt;(args)...); ++m_buffer_size; } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::Destroy() { std::allocator_traits&lt;Allocator&gt;::destroy(m_allocator, std::to_address(m_elements + m_buffer_size) - 1); --m_buffer_size; } template &lt;typename T, typename Allocator&gt; Vector&lt;T, Allocator&gt; Vector&lt;T, Allocator&gt;::CreateNewBuffer( size_type new_capacity, const Allocator&amp; new_allocator) { Vector new_buffer{new_allocator}; new_buffer.Allocate(new_capacity); return new_buffer; } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::Move(iterator first, iterator last, Vector&amp; buffer) { if constexpr (std::is_nothrow_move_constructible_v&lt;T&gt; || !std::is_copy_constructible_v&lt;T&gt;) { std::move(first, last, std::back_inserter(buffer)); } else { std::copy(first, last, std::back_inserter(buffer)); } } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::MoveAll(Vector&amp; buffer) { Move(std::begin(*this), std::end(*this), buffer); } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::Rollback(Vector&amp; other, iterator last) noexcept { if constexpr (!std::is_nothrow_move_constructible_v&lt;T&gt; &amp;&amp; std::is_copy_constructible_v&lt;T&gt;) { // The elements were copied during the Move() call so the destructor of // temporary vector will take care of them. return; } else if constexpr (std::is_nothrow_move_assignable_v&lt;T&gt;) { // Just move assign them back. std::move(std::begin(other), last, std::begin(*this)); return; } else if constexpr (std::is_nothrow_move_constructible_v&lt;T&gt;) { // Hard case. Non-noexcept-move-assignable type. But since move ctor is // noexcept, we just destroy and construct them back. auto source = std::begin(other); auto destination = m_elements; while (source != last) { std::allocator_traits&lt;Allocator&gt;::destroy(m_allocator, std::to_address(destination)); std::allocator_traits&lt;Allocator&gt;::construct(m_allocator, std::to_address(destination), std::move(*source)); ++source; ++destination; } return; } else if constexpr (std::is_move_assignable_v&lt;T&gt;) { // Entering "unspecified" territory. We can just try to move assign some // of them back and swallow any exceptions. If an exception is thrown // here, some elements are lost. try { std::move(std::begin(other), last, std::begin(*this)); } catch (...) { } return; } // The type is non-move-assignable and has throwing move ctor. Just give up. // We haven't invalidated any invariants so destructors will do their job. // Just elements that have been moved are lost. Meh. } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::Commit(Vector&amp;&amp; other) noexcept { this-&gt;Deallocate(); m_elements = other.m_elements; m_buffer_capacity = other.m_buffer_capacity; m_buffer_size = other.m_buffer_size; m_allocator = other.m_allocator; other.m_elements = nullptr; other.m_buffer_capacity = 0; other.m_buffer_size = 0; } template &lt;typename T, typename Allocator&gt; void Vector&lt;T, Allocator&gt;::ValidateIterator(const_iterator it) const { if ((it &lt; std::begin(*this)) || it &gt; std::end(*this)) { throw std::out_of_range{"Vector::ValidateIterator: Invalid iterator."}; } } template &lt;typename T, typename Allocator&gt; bool operator==(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs) { return std::equal(std::begin(lhs), std::end(lhs), std::begin(rhs), std::end(rhs)); } template &lt;typename T, typename Allocator&gt; bool operator!=(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs) { return !(lhs == rhs); } template &lt;typename T, typename Allocator&gt; bool operator&lt;(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs) { return std::lexicographical_compare(std::begin(lhs), std::end(lhs), std::begin(rhs), std::end(rhs)); } template &lt;typename T, typename Allocator&gt; bool operator&gt;(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs) { return rhs &lt; lhs; } template &lt;typename T, typename Allocator&gt; bool operator&lt;=(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs) { return !(lhs &gt; rhs); } template &lt;typename T, typename Allocator&gt; bool operator&gt;=(const Vector&lt;T, Allocator&gt;&amp; lhs, const Vector&lt;T, Allocator&gt;&amp; rhs) { return !(lhs &lt; rhs); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T10:52:53.233", "Id": "425955", "Score": "2", "body": "Note that by posting it here, the code is also licensed under CC BY-SA 3.0: https://codereview.stackexchange.com/help/licensing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T11:02:08.657", "Id": "425956", "Score": "1", "body": "Still copyleft - good enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T13:43:09.923", "Id": "426062", "Score": "0", "body": "@L.F. Move-semantics are quite foreign to allocators, which are generally either trivially copyable (and likely empty) or at least extremely cheaply..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T15:31:42.703", "Id": "428171", "Score": "0", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 2 → 1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T17:50:24.847", "Id": "428193", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Well, those bugs were never pointed to in answers so I thought I'd rather fix them before I get an answer pointing to them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T05:44:43.957", "Id": "444951", "Score": "0", "body": "What is that funky \"Javadoc\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-14T02:01:23.703", "Id": "445091", "Score": "1", "body": "@coderodde Are you talking about the Doxygen code? It is a document generator for C++ code." } ]
[ { "body": "<h3>Non-conformance:</h3>\n<ol>\n<li>\n<blockquote>\n<p>[Derivation].4: All types specified in the C++ standard library shall be non-final types unless otherwise specified.</p>\n</blockquote>\n<p><code>std::vector</code> is not an exception, and thus must not be <code>final</code>.</p>\n</li>\n<li><p>You forgot to implement support for hashing by specializing <code>std::hash</code>.</p>\n</li>\n<li><p>You don't add the necessary typedef to sub-namepspace <code>pmr</code> for polymorphic allocator support.</p>\n</li>\n<li><p>You don't implement the ill-fated specialization for <code>bool</code>.</p>\n</li>\n<li><p><code>#pragma once</code> is not strictly conforming C++, though numerous compilers implement it.</p>\n</li>\n</ol>\n<h3>Efficiency:</h3>\n<ol start=\"6\">\n<li><p>It is understandable that you would prefer not using EBO, as many think it clunky. For this reason, C++20 section <a href=\"//eel.is/c++draft/dcl.attr.nouniqueaddr\" rel=\"nofollow noreferrer\">[dcl.attr.nouniqueaddr]</a> introduces the attribute <code>[[no_unique_address]]</code> for member-variables. Use either.</p>\n</li>\n<li><p>You are using a growth-factor of 2. That means you will never re-use any previous allocation when consecutively growing your vector, as all previous allocations together will never suffice. Consider a smaller factor.</p>\n</li>\n<li><p>Yes, you can safely measure the distance between two <em>ForwardIterator</em>s for pre-sizing. An <em>InputIterator</em> might support subtracting to get the difference despite only allowing a single traversal though. If you have the choice, go by available operations, not fully implemented concepts.</p>\n</li>\n</ol>\n<h3>Form:</h3>\n<ol start=\"9\">\n<li><p>Consider using in-class initializers to simplify your ctors.</p>\n</li>\n<li><p><code>this</code> is implicit, always using it is useless clutter.</p>\n</li>\n<li><p>There is no use to special-casing <em>ForwardIterator</em>s if you don't actually treat them differently in your own code. The code you call from there does all that magic on its own.</p>\n</li>\n<li><p>Consider reading up on the copy-and-swap-idiom, for efficient simpler code.</p>\n</li>\n<li><p>Choose the target-ctor a bit more carefully, and you can more frequently have an empty body.</p>\n</li>\n<li><p>The ternary operator is very useful for efficient and more flexible constructor-chaining.</p>\n</li>\n<li><p>Consider using <a href=\"//en.cppreference.com/w/cpp/iterator/make_move_iterator\" rel=\"nofollow noreferrer\"><code>std::make_move_iterator()</code></a> where appropriate.</p>\n</li>\n</ol>\n<pre><code>template &lt;typename T, typename Allocator&gt;\nVector&lt;T, Allocator&gt;::Vector(Vector&amp;&amp; other, const Allocator&amp; new_allocator)\n: Vector{new_allocator == other.m_allocator\n ? Vector{other}\n : Vector{std::make_move_iterator(other.begin()), std::make_move_iterator(other.end()), new_allocator}}\n{}\n</code></pre>\n<ol start=\"16\">\n<li><p>If someone has the effrontery to use an element-type which can throw on destruction, and that happened, all bets are off as far as the standard is concerned. Even if it wasn't, swallowing exceptions generally only makes bugs harder to treat.</p>\n</li>\n<li><p>Explicit comparison against <code>true</code> and <code>false</code> is needless verbosity. If you disagree, why not add a few extra-comparisons? Also, you might fall afoul of subtleties especially if comparing to <code>true</code>.</p>\n</li>\n<li><p>Generally, pre-testing whether something is <em>already</em> null is both verbose and inefficient, as it duplicates work.</p>\n</li>\n<li><p>Try to avoid conditional execution, especially if it is not expected to save more than an insignificant amount and that only in rare cases, inviting branch-misprediction.</p>\n</li>\n<li><p>I would expect use or omission of the two-step for <code>swap</code> to be consistent, at least in a single function.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T00:31:28.917", "Id": "426021", "Score": "0", "body": "9. If I don't explicitly type `type` it always looks like a random non-member function.\n\n10. InputIterator is one pass so you can't preallocate and have to use inefficient algorithm. I split those to have more efficient one for ForwardIterators.\n13. Ternary operator is really hard to read.\n16. `if (foo)` is really hard to read unless it is very explicit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T01:00:42.827", "Id": "426022", "Score": "0", "body": "@Lyberta re 9: It Looks like a random non-member? Well, I don't concurr, but whatever. re 10: As you have the same code for both ctors, you don't take advantage of separating them *there already*. The callee does. re 13: Ehm, no. re 16: \"if the vector is empty is true\" is a very convoluted way to say \"if the vector is empty\". Dito for the moral equivalent in C++. It's somewhat hard to understand how anyone could disagree there. Of course, comparison against `true` is far more error-prone and alien to C and C++ than against `false`, which is also generally bad." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T16:44:49.863", "Id": "220475", "ParentId": "220457", "Score": "8" } }, { "body": "<p>(Note: I am referring to the <a href=\"https://eel.is/c++draft\" rel=\"nofollow noreferrer\">newest draft</a>, so some of the points below may be due to the changes in the standard draft. I will list them for the sake of completeness and also to help you adapt to the newest drafts.)</p>\n\n<p>Here's some more suggestions not covered by Deduplicator's answer:</p>\n\n<h1>Non-conformance</h1>\n\n<ol>\n<li><p>Per <a href=\"http://eel.is/c++draft/vector.syn\" rel=\"nofollow noreferrer\">[vector.syn]</a>, the header <code>&lt;initializer_list&gt;</code> should be included by <code>&lt;vector&gt;</code>. You are using the identifier <code>std::initializer_list</code> without including the appropriate header.</p></li>\n<li><p><code>std::vector</code> is <code>constexpr</code>-friendly in C++20 thanks to allocation/deallocation and construction/destruction being allowed in <code>constexpr</code>.</p></li>\n<li><p>The standard <code>std::vector</code> constructs default allocators with <code>Allocator()</code> instead of <code>Allocator{}</code>. This can cause a difference. See <a href=\"https://stackoverflow.com/q/57972098\">Are there any difference in empty parentheses (<code>T()</code>) and empty braces (<code>T{}</code>) when used as initializers?</a>.</p></li>\n<li><p>The <code>(alloc)</code> constructor is <code>noexcept</code>.</p></li>\n<li><p>Per <a href=\"http://eel.is/c++draft/container.requirements.general#8.sentence-4\" rel=\"nofollow noreferrer\">[container.requirements.general]/8</a>, the move constructor should move construct from the allocator.</p></li>\n<li><p>The <code>assign(inputit, inputit)</code> function doesn't look right. It seems that it clears the vector if <code>size != 0</code>.</p></li>\n</ol>\n\n<h1>Missing functionality</h1>\n\n<ol>\n<li><p>Free function <code>swap</code>.</p></li>\n<li><p>Uniform erasure (<code>erase</code>, <code>erase_if</code>).</p></li>\n<li><p>In C++20, the three-comparison operator <code>&lt;=&gt;</code> is introduced. You may want to change the comparison operators to <code>operator&lt;=&gt;</code>.</p></li>\n</ol>\n\n<h1>Other</h1>\n\n<ol>\n<li><p>The type <code>std::allocator_traits&lt;Allocator&gt;</code> is used numerous times in the class. I suggest introducing a type alias for it. For example:</p>\n\n<pre><code>using A_Tr = std::allocator_traits&lt;Allocator&gt;;\n</code></pre></li>\n<li><p>Since your <code>(it, it)</code> constructor delegates to <code>assign</code> inside, there is no need to provide a separate version for forward iterators.</p></li>\n<li><p>You always call your constructor parameter <code>allocator</code> except for the <code>(vector&amp;&amp;, alloc)</code> version, in which it is <code>new_allocator</code>. It is probably a good idea to keep consistent.</p></li>\n<li><p>I have to say this again: don't use <code>this-&gt;</code> everywhere. It automatically makes me think of dependent base classes and etc. Just remove them.</p></li>\n<li><p>The move constructor can be simplified with some <code>swap_content</code> function.</p></li>\n<li><p>You can avoid writing the template parameters twice by using a trailing return type. For example:</p>\n\n<pre><code>template &lt;typename T, typename A&gt;\nauto Vector&lt;T, A&gt;::operator(std::initializer_list&lt;T&gt; values)\n -&gt; Vector&amp;\n{\n // ...\n}\n</code></pre>\n\n<p>And use <code>auto</code> as appropriate:</p>\n\n<pre><code>template &lt;typename T, typename A&gt;\nauto Vector&lt;T, A&gt;::get_allocator() const noexcept\n{\n return m_allocator;\n}\n</code></pre>\n\n<p>(This one should really be implemented directly in the class.)</p></li>\n<li><p>The <code>assign(In, In)</code> function can be simplified if the <code>(In, In)</code> constructor doesn't depend on it:</p>\n\n<pre><code>template &lt;typename T, typename A&gt;\ntemplate &lt;InputIterator I&gt;\nvoid Vector&lt;T, A&gt;::assign(I first, I last)\n{\n Vector vec(first, last, m_allocator);\n swap(vec);\n}\n</code></pre>\n\n<p>To me, it seems more logical to make the constructor depend on <code>insert</code>.</p>\n\n<p>Similarly, the <code>assign(For, For)</code> function is way too complicated. Let the <code>(For, For)</code> constructor depend on <code>insert</code> instead.</p></li>\n<li><p>The <code>assign(count, value)</code> function should use the <code>(count, value)</code> constructor because the latter does not depend on the former.</p></li>\n<li><p>The <code>c</code> iterator functions can delegate to the other functions.</p></li>\n<li><p>To be honest, my sanity dropped by ~4.2% when I saw the resize functions. Their sheer size makes comprehension difficult. Here's how I'll write the whole function: (just the idea, not tested)</p>\n\n<pre><code>template &lt;typename T, typename A&gt;\nvoid Vector&lt;T, A&gt;::resize(size_type new_size)\n{\n while (size() &gt; new_size) {\n pop_back();\n }\n reserve(new_size);\n while (size() &lt; new_size) {\n emplace_back();\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>template &lt;typename T, typename A&gt;\nvoid Vector&lt;T, A&gt;::resize(size_type new_size, const T&amp; value)\n{\n while (size() &gt; new_size) {\n pop_back();\n }\n if (size() &lt; new_size) {\n insert(end(), new_size - size(), value);\n }\n}\n</code></pre></li>\n<li><p>The <code>push_back</code> function should delegate to <code>emplace_back</code>. Two <code>insert</code> functions should delegate to <code>emplace</code>.</p></li>\n<li><p><code>pop_back</code> has undefined behavior on empty vectors, so there's no need to handle the empty case specially. An assertion will be enough. Likewise, <code>clear()</code> doesn't need to check exceptions.</p></li>\n<li><p>Do you know <code>std::move_if_noexcept</code>? You can simplify <code>Move</code> like this:</p>\n\n<pre><code>template &lt;typename T, typename Allocator&gt;\nvoid Vector&lt;T, Allocator&gt;::Move(iterator first, iterator last, Vector&amp; buffer)\n{\n std::transform(first, last, std::back_inserter(buffer),\n [](auto&amp;&amp; value) -&gt; decltype(auto) { return std::move_if_noexcept(value); });\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T20:08:49.230", "Id": "445072", "Score": "0", "body": "`.resize()` must work even if passed an element of the vector and reallocation is done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-14T01:58:13.053", "Id": "445090", "Score": "0", "body": "@Deduplicator That's logical. I genuinely failed to consider that edge case ... Does the `insert(it, count, value)` version allow `value` to be an element of the vector too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-14T02:25:24.107", "Id": "445092", "Score": "0", "body": "If it's a value instead of an xvalue, it might just be an element, yes. At least none of the emplace-functions must take that into account AFAICR." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T04:47:11.663", "Id": "228942", "ParentId": "220457", "Score": "3" } }, { "body": "<p>First, I would like to mention, that defining the constructors out of class adds a lot of unnecessary clutter in the form of <code>template &lt;typename T, typename Allocator&gt;</code> and <code>Vector&lt;T, Allocator&gt;</code></p>\n\n<p>You should use explicit member initialization rather than repeating yourself in the constructors.</p>\n\n<pre><code>pointer m_elements{nullptr};\nstd::size_t m_buffer_capacity{0};\nstd::size_t m_buffer_size{0};\nAllocator m_allocator{Allocator()};\n</code></pre>\n\n<p>Also note that in that case you explicitly <code>default</code> the default constructor as it will deduce the correct exception specification itself.</p>\n\n<pre><code>Vector() = default;\n\nVector(const Allocator&amp; allocator)\n : m_allocator{allocator}\n{}\n</code></pre>\n\n<p>I am skeptical of your move constructor:</p>\n\n<pre><code>template &lt;typename T, typename Allocator&gt;\nVector&lt;T, Allocator&gt;::Vector(Vector&amp;&amp; other) noexcept\n : m_elements{other.m_elements},\n m_buffer_capacity{other.m_buffer_capacity},\n m_buffer_size{other.m_buffer_size},\n m_allocator{other.m_allocator}\n{\n other.m_elements = nullptr;\n other.m_buffer_capacity = 0;\n other.m_buffer_size = 0;\n}\n</code></pre>\n\n<p><s>For one thing it does unnecessary work, as <code>other</code> is defined as in an unspecified state, so resetting can be skipped.</s> Also you are copying the allocator of <code>other</code>. That should (regardless whether the allocator is movable or not) be</p>\n\n<pre><code>m_allocator{std::move(other.m_allocator)} \n</code></pre>\n\n<p>I have to object to @Deduplicator comment 12. Using the copy and swap idiom requires default construction of the allocator which might or might not be expensive. A fundamental workhorse such as vector can bear that few extra lines. Also note that adding the linebreak before the commata increases alignment and therewith readability:</p>\n\n<pre><code>template &lt;typename T, typename Allocator&gt;\nVector&lt;T, Allocator&gt;::Vector(Vector&amp;&amp; other) noexcept\n : m_elements{other.m_elements}\n , m_buffer_capacity{other.m_buffer_capacity},\n , m_buffer_size{other.m_buffer_size}\n , m_allocator{std::move(other.m_allocator)}\n{\n}\n</code></pre>\n\n<p>The other move constructor also does more than it should. Even worse it is inconsistent as other is in a different state depending on which branch is taken</p>\n\n<pre><code>template &lt;typename T, typename Allocator&gt;\nVector&lt;T, Allocator&gt;::Vector(Vector&amp;&amp; other, const Allocator&amp; new_allocator)\n : Vector{new_allocator}\n{\n if (m_allocator == other.m_allocator)\n {\n m_elements = other.m_elements;\n m_buffer_capacity = other.m_buffer_capacity;\n m_buffer_size = other.m_buffer_size;\n other.m_elements = nullptr;\n other.m_buffer_capacity = 0;\n other.m_buffer_size = 0;\n return;\n }\n Allocate(GetSufficientCapacity(other.m_buffer_size));\n std::move(std::begin(other), std::end(other), std::back_inserter(*this));\n}\n</code></pre>\n\n<p>The first thing is not using the initializer list for the trivial members. Second you are using <code>std::back_inserter</code> which falls back to individual <code>push_back</code>s. Rather you should directly use the <code>begin()</code>/<code>end()</code> methods.</p>\n\n<pre><code>template &lt;typename T, typename Allocator&gt;\nVector&lt;T, Allocator&gt;::Vector(Vector&amp;&amp; other, const Allocator&amp; allocator)\n : m_buffer_capacity{other.m_buffer_capacity},\n , m_buffer_size{other.m_buffer_size}\n , m_allocator{allocator}\n{\n if (m_allocator == other.m_allocator)\n {\n m_elements = other.m_elements;\n } \n else \n {\n Allocate(GetSufficientCapacity(other.m_buffer_size));\n std::move(other.begin(), other.end(), begin());\n }\n}\n</code></pre>\n\n<p><em>EDIT</em></p>\n\n<p>I checked libc++ and they indeed reset the values of the vector:\n<a href=\"https://github.com/llvm-mirror/libcxx/blob/8c84318aad43620024310db6c1fe75c0c1706ead/include/vector#L1279\" rel=\"nofollow noreferrer\">https://github.com/llvm-mirror/libcxx/blob/8c84318aad43620024310db6c1fe75c0c1706ead/include/vector#L1279</a></p>\n\n<p>Note that it still moves the allocator of <code>other</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T21:26:49.383", "Id": "445074", "Score": "1", "body": "Not \"unspecified\" but \"unspecified but valid\". Thus, resetting the source on move-construction is necessary. As an aside, move-assignment also always destroys all the targets elements, even for self-assignment. Regarding your comment to my point 12, copy-and-swap does no default-construction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-14T06:13:52.217", "Id": "445120", "Score": "0", "body": "@Deduplicator: That is factually wrong. The `unspecified but valid` is the phrasing that is done because it must *not* be resetted. The vector vas in a valid state before so no resetting is required. The reason why copy-and-swap is not used universally is that it indeed implies a measurable overhead in default constructing the members before swapping them. Note that in the move constructor after the initializer list of the constructor `m_allocator` is default constructed and then swapped afterwards. In contrast by writing it out `m_allocator` is directly move constructed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-14T08:32:20.750", "Id": "445127", "Score": "1", "body": "@miscco If you don't reset the source, it is left in an invalid state. Any decent compiler should optimize out the overhead caused by default construction + swapping over move + resetting. The `m_allocator` problem can be (and should be) addressed by having a separate `swap_contents` function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-14T18:32:48.840", "Id": "445179", "Score": "0", "body": "@L.F. It is not about what acompiler could do but what it is allowed to do. It is not allowed to remove any observable behavior. So for example if you have an allocator that allocates a certain amount of storage during default construction the compiler cannot simply remove that allocation. This is analogous to the push for `relocatable` wrt move construction + destruction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-14T18:40:29.217", "Id": "445181", "Score": "0", "body": "@miscco Actually, allocating and deallocating is not per se observable behavior. There is even explicit license in the standard to coalesce allocations, as well as to omit allocation + deallocation pairs in many cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-14T19:05:06.680", "Id": "445189", "Score": "0", "body": "Yes, but if you use copy&swap you have to swap the allocated buffer into the other allocator so it cannot be ommited. The whole point is that before you enter the body of the constructor the object is fully initialized and that involves a cost that is not necessary. In many (maybe even most) cases it is totaly worth to simplify the code and get the strong exception guaranty from copy&swap but for something like a vector it is questionable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-15T01:58:19.293", "Id": "445214", "Score": "0", "body": "@miscco The copy and swap idiom does not involve an allocation. Default construction is zero cost in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-15T21:09:01.277", "Id": "445335", "Score": "0", "body": "@L.F. The copy and swap idom requires one temporary. So in this case the cost is equal to the cost of the construction of the allocator object. That might be free but can you guarantee it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-16T10:11:06.900", "Id": "445389", "Score": "0", "body": "I realized that our discussion is getting extensive, so I've created a [chat room](https://chat.stackexchange.com/rooms/98721/discussion-on-the-copy-and-swap-idiom-https-codereview-stackexchange-com-a-228)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T18:59:53.617", "Id": "228990", "ParentId": "220457", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T10:40:58.290", "Id": "220457", "Score": "10", "Tags": [ "c++", "reinventing-the-wheel", "vectors", "c++20" ], "Title": "C++20 standard compatible vector" }
220457
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/median-of-two-sorted-arrays/" rel="nofollow noreferrer">leetcode</a> </p> <blockquote> <p>There are two sorted arrays nums1 and nums2 of size m and n respectively.</p> <p>Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).</p> <p>You may assume nums1 and nums2 cannot be both empty.</p> <p><strong>Example 1:</strong></p> <p>nums1 = [1, 3]</p> <p>nums2 = [2]</p> <p>The median is 2.0</p> <p><strong>Example 2:</strong></p> <p>nums1 = [1, 2]</p> <p>nums2 = [3, 4]</p> <p>The median is (2 + 3)/2 = 2.5</p> </blockquote> <p><strong>My solution</strong></p> <pre><code>/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var findMedianSortedArrays = function(nums1, nums2) { let i1 = i2 = 0; let smallest, valBefore; const pivot = Math.floor((nums1.length + nums2.length) / 2); while (nums1[i1] || nums2[i2]) { smallest = (nums2[i2] === void 0 || nums1[i1] &lt; nums2[i2]) ? nums1[i1++] : nums2[i2++]; if ((nums1.length + nums2.length) % 2) { if (pivot === i1 + i2 - 1) { return smallest; } } else { if (pivot - 1 === i1 + i2 - 1) { valBefore = smallest } if (pivot === i1 + i2 - 1) { return (smallest + valBefore) / 2; } } } }; </code></pre> <p>This is the first idea that I had and it reached 99th percentile. I guess you can't take this evaluation seriously. And I'm sure there's a better solution.</p>
[]
[ { "body": "<p>The 99th percentile is due to the linear nature of your approach. The goal of this exercise is to figure out a logarithmic one.</p>\n\n<p>I don't want to spell out the algorithm entirely. Just a hint to get you started. Take a middle element of <code>nums1</code>. Find its lower bound in <code>nums2</code>; call it <code>i2</code>. In the sorted array the selected element would be at the position <code>nums1.length/2 + i2</code>. I hope the hint is a good enough.</p>\n\n<hr>\n\n<p><code>pivot</code> doesn't look like a good name to me. <code>totalLength</code>, perhaps?</p>\n\n<hr>\n\n<p>The complicated logic inside the loop also hurts the performance. Consider looping until you reach the midpoint:</p>\n\n<pre><code> while (i1 + i2 &lt; pivot)\n</code></pre>\n\n<p>and do the final median finding afterwards.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T16:46:59.670", "Id": "220476", "ParentId": "220458", "Score": "3" } } ]
{ "AcceptedAnswerId": "220476", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T10:59:55.207", "Id": "220458", "Score": "2", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6" ], "Title": "Find Median of Two Sorted Arrays in JS" }
220458
<p>I wrote this method to upload a floor plan image:</p> <pre><code>function upload_image($path, $file) { $errors = []; $ext = pathinfo($file["name"])['extension']; //randomly generate filename to avoid conflicts $filename = uniqid().'.'.$ext; if ($file["size"] &gt; 2000000) { $errors[] = "The image cannot be greater than 2MB"; } if (!in_array($ext, ["jpg", "jpeg", "png"])) { $errors[] = "The image can only be of .jpg, .jpeg or .png format"; } if (empty($errors)) { move_uploaded_file($file["tmp_name"], $path.$filename); } return array( "name" =&gt; $filename, "errors" =&gt; $errors ); } </code></pre> <p><strong>Implementation:</strong></p> <pre><code>if (isset($_POST['create'])) { $image = upload_image(IMG_PATH."/floorplans/", $_FILES['floorplan']); $floorplan = new FloorPlan($_POST['floorplan']); if (empty($image['errors'])) { $floorplan-&gt;image = $image['name']; } else { foreach ($image['errors'] as $error) { $floorplan-&gt;errors[] = $error; } } } </code></pre> <p>I'm very happy with it and everything seems to work fine, but I am just wondering if there is a better/more efficient way to do this.</p>
[]
[ { "body": "<p>There's not a lot of code here, but here's something I noticed.</p>\n\n<pre><code>foreach ($image['errors'] as $error) {\n $floorplan-&gt;errors[] = $error;\n}\n</code></pre>\n\n<p>Since <code>$floorplan-&gt;errors</code> is expecting and array of errors, and <code>$image['errors']</code> is already an array of errors, why iterate through them and assign them to <code>$floorplan-&gt;errors</code> one by one when you can just assign <code>$image['errors']</code> to <code>$floorplan-&gt;errors</code>?</p>\n\n<pre><code>} else {\n $floorplan-&gt;errors = $image['errors'];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T21:57:59.613", "Id": "220530", "ParentId": "220459", "Score": "0" } }, { "body": "<ul>\n<li><p>Rather than generate the full array of elements that <code>pathinfo()</code> generously offers only to access one value, use the <code>PATHINFO_EXTENSION</code> flag/option (the second parameter) to only ask for what you need.</p></li>\n<li><p>For best efficiency, don't perform any unnecessary processes for disquaified incoming data.</p></li>\n<li><p>If you are going to declare <code>errors</code> at the start as an empty array, you won't need to call <code>empty()</code> which checks if the variable does not exist or if it is empty/falsey/null/zeroish. You can more simply use <code>!$errors</code>. Alternatively, don't declare the empty errors array and then use <code>empty</code> to perform the double check.</p></li>\n<li><p>I assume that there is no point to generating a filename for an invalid submission, so I don't think that I'll support passing it with errors.</p></li>\n<li><p>I try to avoid declaring single-use and temporary variable where possible. In this case, I'd avoid temporary variable by always dealing with the array to be returned at the end.</p></li>\n</ul>\n\n<p>How my recommendations boil down...</p>\n\n<pre><code>function upload_image($path, $file) {\n if ($file[\"size\"] &gt; 2000000) {\n $outcome['errors'][] = \"The image cannot be greater than 2MB\";\n }\n\n $ext = strtolower(pathinfo($file[\"name\"], PATHINFO_EXTENSION)); // force lowercase for uniformity\n\n if (!in_array($ext, [\"jpg\", \"jpeg\", \"png\"])) {\n $outcome['errors'][] = \"The image can only be in .jpg, .jpeg or .png format.\";\n }\n\n if (empty($outcome['errors'])) {\n // for the record, randomness does not guarantee uniqueness\n $outcome['name'] = uniqid() . '.' . $ext;\n move_uploaded_file($file[\"tmp_name\"], $path . $outcome['name']);\n }\n\n return $outcome;\n}\n</code></pre>\n\n<p>If you like rabbit holes, here's a good read regarding the security aspects of your task: <a href=\"https://stackoverflow.com/q/6484307/2943403\">https://stackoverflow.com/q/6484307/2943403</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:31:25.827", "Id": "220566", "ParentId": "220459", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T11:12:01.947", "Id": "220459", "Score": "1", "Tags": [ "php" ], "Title": "Simple PHP image upload with error handling" }
220459
<p>I've written a rudimentary parser for <a href="https://en.wikipedia.org/wiki/INI_file" rel="nofollow noreferrer">INI</a> files:</p> <pre><code>{-# LANGUAGE OverloadedStrings #-} import qualified Data.Map as M import Data.Maybe (fromMaybe) import qualified Data.Text as T type Ini = M.Map T.Text Section data Section = Section { name :: T.Text , properties :: M.Map T.Text T.Text } deriving (Show) main :: IO () main = parseIni iniFilePath &gt;&gt;= \ini -&gt; putStrLn $ "Parsed INI: " ++ show ini where iniFilePath = "/home/me/test.ini" parseIni :: FilePath -&gt; IO Ini parseIni iniFilePath = parseToIni . T.pack &lt;$&gt; readFile iniFilePath parseToIni :: T.Text -&gt; Ini parseToIni stringToParse = -- We return the parsed Ini, not the helper values firstOfTriple $ foldr (\line (ini, currentSectionMaybe, lineIndex) -&gt; -- We're at a new section start or the end of the file → add the previous section -- to the parsed Ini value and create a new section if isSectionHeader line || lineIndex &gt;= length lines - 1 then let updatedIni = addSection ini currentSectionMaybe in (updatedIni, Just $ Section (getSectionName line) M.empty, 1 + lineIndex) else (ini, updateSection currentSectionMaybe line, 1 + lineIndex)) (M.empty, Nothing, 0) $ -- Since foldr is right associative we would process the lines starting with the last one, that's -- why we reverse the list of lines reverse lines where lines :: [T.Text] lines = T.splitOn "\n" stringToParse firstOfTriple :: (a, b, c) -&gt; a firstOfTriple (x, _, _) = x parseProperty :: T.Text -&gt; Maybe (T.Text, T.Text) parseProperty line = case T.splitOn "=" line of [name, value] -&gt; Just (T.strip name, T.strip value) _ -&gt; Nothing updateSection :: Maybe Section -&gt; T.Text -&gt; Maybe Section updateSection sectionMaybe line = fmap updateSection' sectionMaybe where updateSection' :: Section -&gt; Section updateSection' section = -- Add the property to the section if the property can be parsed. -- Otherwise, leave the section as it were maybe section (\(propName, value) -&gt; Section (name section) (M.insert propName value (properties section))) (parseProperty line) getSectionName :: T.Text -&gt; T.Text getSectionName line = fromMaybe line headerWithoutBracketsMaybe where headerWithoutBracketsMaybe = T.stripPrefix "[" line &gt;&gt;= T.stripSuffix "]" isSectionHeader :: T.Text -&gt; Bool isSectionHeader line = T.isPrefixOf "[" strippedLine &amp;&amp; T.isSuffixOf "]" strippedLine where strippedLine = T.strip line addSection :: Ini -&gt; Maybe Section -&gt; Ini addSection ini sectionMaybe = maybe ini (\section -&gt; M.insert (name section) section ini) sectionMaybe </code></pre> <p>I'd love to get feedback on how to simplify the code and/or make it more readable.</p> <p>Things I'm aware of and ok with at the moment:</p> <ul> <li>The parser doesn't support comments</li> <li><code>addSection</code> could be eta-reduced</li> <li>I don't use a parsing library like Parsec</li> <li>I don't use lenses</li> </ul>
[]
[ { "body": "<p>Just a few comments – not a full review:</p>\n\n<ol>\n<li><p><code>parseToIni :: T.Text -&gt; Ini</code> indicates that from any random string, <code>parseToIni</code> can produce an <code>Ini</code>. This makes me wonder how it would handle an invalid <code>.ini</code> file, or e.g. the string <code>foo</code>.</p></li>\n<li><p>In <code>updateSection :: Maybe Section -&gt; T.Text -&gt; Maybe Section</code> the <code>Maybe</code>s obfuscate what the function is supposed to do. Can the function produce a <code>Nothing</code> if the first argument is a <code>Just</code>? Better remove the <code>Maybe</code>s and <code>fmap</code> the whole thing if needed. <code>addSection</code> is similar.</p></li>\n<li><p><code>main</code> would IMHO be more readable if it simply used <code>do</code>-notation.</p></li>\n<li><p>In <code>parseToIni</code>, the worker function for <code>foldr</code> is complex enough that it should have a type annotation. It's ok to to simply call inner worker functions <code>f</code> IMHO.</p></li>\n<li><p>I think it's a bit confusing that the section names appear both as the keys of <code>Ini</code> <em>and</em> in <code>Section</code>'s <code>name</code> field. I'd probably remove the <code>name</code> field.</p></li>\n<li><p>A few type synonyms for keys, values, section names etc might help with readability.</p></li>\n<li><p>The order of parameters in <code>addSection</code> and <code>updateSection</code> is a bit unconventional. The usual <code>a -&gt; b -&gt; b</code> ordering is a bit nicer for partial applications.</p></li>\n<li><p>IMHO, <code>maybe</code> (and similar functions like <code>either</code>) don't aid readability. If you don't want to come up with a variable name, try the <code>LambdaCase</code> extension.</p></li>\n<li><p>Try <a href=\"http://hackage.haskell.org/package/text-1.2.3.1/docs/Data-Text-IO.html#v:readFile\" rel=\"nofollow noreferrer\"><code>Data.Text.IO.readFile</code></a>.</p></li>\n<li><p>Instead of <code>getSectionName</code> and <code>isSectionName</code>, have a single function of type <code>Text</code> -> <code>Maybe SectionName</code>.</p></li>\n</ol>\n\n<p>All in all I think your code is pretty readable. It's mostly the types that could be a bit better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T21:07:39.860", "Id": "220674", "ParentId": "220460", "Score": "2" } }, { "body": "<p>I know you said you were fine with not using a parser combinator library like parsec, but I thought you might like to see the how the same thing might look using one, so I wrote an Attoparsec based parser for your data types:</p>\n\n<pre><code>{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule IniParser where\n\nimport Control.Monad ( void )\nimport Data.Attoparsec.Text ( Parser\n , char\n , endOfInput\n , endOfLine\n , many'\n , many1\n , notInClass\n , parseOnly\n , satisfy\n , space\n )\nimport Data.Map.Strict ( Map )\nimport qualified Data.Map.Strict as Map\nimport Data.Text ( Text\n , pack\n )\nimport System.Environment ( getArgs )\n\ntype Ini = Map Text Section\n\ndata Section = Section\n { name :: Text\n , properties :: Map Text Text\n } deriving (Show)\n\nmain :: IO ()\nmain = do\n [path] &lt;- getArgs\n parseIniFile path &gt;&gt;= \\case\n Right ini -&gt; putStrLn $ \"Parsed INI: \" ++ show ini\n Left err -&gt; putStrLn $ \"ERROR parsing ini: \" ++ err\n\nparseIniFile :: FilePath -&gt; IO (Either String Ini)\nparseIniFile iniFilePath = parseIni . pack &lt;$&gt; readFile iniFilePath\n\nparseIni :: Text -&gt; Either String Ini\nparseIni = parseOnly ini\n\nini :: Parser Ini\nini = do\n defaultSection &lt;- lexeme (Section \"\" &lt;$&gt; (Map.fromList &lt;$&gt; many' property))\n namedSections &lt;- lexeme (many' section)\n void $ endOfInput\n let allSections | null (properties defaultSection) = namedSections\n | otherwise = defaultSection:namedSections\n pure . Map.fromList . map (\\section -&gt; (name section, section))\n $ allSections\n\nsection :: Parser Section\nsection = Section &lt;$&gt; sectionName &lt;*&gt; (Map.fromList &lt;$&gt; many' (lexeme property))\n\nsectionName :: Parser Text\nsectionName = char '[' *&gt; sectionNameChars &lt;* char ']' &lt;* endOfLine\n\nsectionNameChars :: Parser Text\nsectionNameChars = pack &lt;$&gt; many' (satisfy $ notInClass \"]\\r\\n\")\n\nproperty :: Parser (Text, Text)\nproperty = (,) &lt;$&gt; propertyName &lt;*&gt; (lexeme (char '=') *&gt; propertyValue)\n\npropertyName :: Parser Text\npropertyName = pack &lt;$&gt; many' (satisfy $ notInClass \"=\\r\\n\\t \")\n\npropertyValue :: Parser Text\npropertyValue = pack &lt;$&gt; many' (satisfy $ notInClass \"\\r\\n\")\n\nlexeme :: Parser a -&gt; Parser a\nlexeme p = whitespace *&gt; p &lt;* whitespace\n\nwhitespace :: Parser String\nwhitespace = many' space\n</code></pre>\n\n<p>I think the main strength of the approach is self pretty self-evident. It eliminates all the multi-line lambdas, the entire foldr, etc. which (at least IMHO) really obscures the essence of what the code is expressing.</p>\n\n<p>Additionally I've restricted the use of qualified imports to a single one usage where I think it makes the code more readable, though your taste may vary.</p>\n\n<p>You can see the whole stack based <a href=\"https://github.com/lgastako/ini-parser\" rel=\"nofollow noreferrer\">project here</a> if you're interested.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T04:57:22.153", "Id": "220694", "ParentId": "220460", "Score": "3" } } ]
{ "AcceptedAnswerId": "220674", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T11:14:10.560", "Id": "220460", "Score": "4", "Tags": [ "parsing", "haskell", "file", "configuration" ], "Title": "Simple INI file parser in Haskell" }
220460
<p>I have created a Sudoku generator in Java. Here I am using a basic solved sudoku as seed and by transposing it and shuffling its row and columns I get a new solved sudoku.</p> <pre><code> //import java.util.Arrays; import java.util.Random; public class SudokuGenerator { private char[][] board = new char[9][9]; private int[] randomizeSudoku = new int[9]; private char[][] transposedSeed = new char[][]{{'8', '2', '7', '1', '5', '4', '3', '9', '6'}, {'9', '6', '5', '3', '2', '7', '1', '4', '8'}, {'3', '4', '1', '6', '8', '9', '7', '5', '2'}, {'5', '9', '3', '4', '6', '8', '2', '7', '1'}, {'4', '7', '2', '5', '1', '3', '6', '8', '9'}, {'6', '1', '8', '9', '7', '2', '4', '3', '5'}, {'7', '8', '6', '2', '3', '5', '9', '1', '4'}, {'1', '5', '4', '7', '9', '6', '8', '2', '3'}, {'2', '3', '9', '8', '4', '1', '5', '6', '7'},}; private char[][] seed = new char[9][9]; private Random random = new Random(); public static void main(String[] args) { SudokuGenerator s = new SudokuGenerator(); int n = 2; s.transpose(); s.shuffle(); s.seedChanger(); while (n &gt; 0) { System.out.println("\n\n------ New Board --------\n"); s.transpose(); s.shuffle(); s.display(); s.seedChanger(); n--; } } private void transpose() { for (int i = 0; i &lt; 9; i++) { for (int j = 0; j &lt; 9; j++) { seed[j][i] = transposedSeed[i][j]; } } } private void seedChanger() { for (int i = 0; i &lt; 9; i++) { System.arraycopy(board[i], 0, transposedSeed[i], 0, board.length); } } private void randomSudokuGenerator() { for (int i = 0; i &lt; randomizeSudoku.length; i++) { randomizeSudoku[i] = 9; } int i = 0; for (; i &lt; randomizeSudoku.length; ++i) { int r = random.nextInt(2); for (int i1 = 0; i1 &lt; i; ++i1) { int x = randomizeSudoku[i1]; if (x == r) { if (i &lt; 3) { r = random.nextInt(3); } else if (i &lt; 6) { r = random.nextInt(3) + 3; } else if (i &lt; 9) { r = random.nextInt(3) + 6; } i1 = -1; } } randomizeSudoku[i] = r; } } private void shuffle() { randomSudokuGenerator(); // System.out.println(Arrays.toString(randomizeSudoku)); for (int x = 0; x &lt; 9; x++) { board[0][x] = seed[randomizeSudoku[0]][x]; board[1][x] = seed[randomizeSudoku[1]][x]; board[2][x] = seed[randomizeSudoku[2]][x]; board[3][x] = seed[randomizeSudoku[3]][x]; board[4][x] = seed[randomizeSudoku[4]][x]; board[5][x] = seed[randomizeSudoku[5]][x]; board[6][x] = seed[randomizeSudoku[6]][x]; board[7][x] = seed[randomizeSudoku[7]][x]; board[8][x] = seed[randomizeSudoku[8]][x]; } for (int x = 0; x &lt; 9; x++) { if (randomizeSudoku[0] == 0) swapping(board, x, 1, 0); if (randomizeSudoku[0] == 1) swapping(board, x, 2, 0); if (randomizeSudoku[0] == 0) swapping(board, x, 5, 4); if (randomizeSudoku[0] == 1) swapping(board, x, 5, 3); if (randomizeSudoku[0] == 2) swapping(board, x, 8, 6); } } private void swapping(char[][] a, int commonIndex, int first, int second) { char swap = a[commonIndex][first]; a[commonIndex][first] = a[commonIndex][second]; board[commonIndex][second] = swap; } private void display() { int i, j; for (i = 0; i &lt;= 8; ++i) { if (i == 0) { System.out.print("\t\t\t_______________________________________\n\t row " + (i + 1) + "\t"); } else { System.out.print("\t\t\t|---|---|---||---|---|---||---|---|---|\n\t row " + (i + 1) + "\t"); } for (j = 0; j &lt;= 8; ++j) { if (j == 3) { System.out.print("|"); } if (j == 6) { System.out.print("|"); } if (j == 8) { System.out.println("| " + board[i][j] + " |"); } else { System.out.print("| " + board[i][j] + " "); } } if (i == 2) { System.out.println("\t\t\t|---|---|---||---|---|---||---|---|---|"); } if (i == 5) { System.out.println("\t\t\t|---|---|---||---|---|---||---|---|---|"); } if (i == 8) { System.out.println("\t\t\t---------------------------------------"); System.out.println("\tcolumns 1 2 3 4 5 6 7 8 9 \n\n\n"); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T18:32:34.767", "Id": "425988", "Score": "0", "body": "Which version of Java are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T19:02:20.987", "Id": "425989", "Score": "0", "body": "Thanks for editing @200_success , I will try to do better next time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T19:03:07.333", "Id": "425990", "Score": "0", "body": "@T145 using java 8, why what happened?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T19:08:06.583", "Id": "425991", "Score": "0", "body": "Nothing. This would run on earlier versions, but knowing the version you're on gives knowledge of what tools can be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T19:13:31.623", "Id": "425992", "Score": "0", "body": "Oh OK, thanks. I glad to know it can be used on older versions, and yes maybe more tools of Java 8 can be used. But I have just started to learn Java, when I made this I just knew this much tools. " } ]
[ { "body": "<p>For this review, I'm operating under the assumption that this was a class assignment / programming challenge and/or has portions copy-pasted / is made by more than one person. The main reason for this is b/c of the excessive inconsistencies w/ formatting. Which is a pretty good segway into:</p>\n\n<p><strong>Formatting</strong></p>\n\n<p>Since you're using Java, I'll briefly touch on OOD (Object Oriented Design). Even though this is a controlled program / script, it would be a good practice to split up your <code>main</code> function into a separate class. This will let you design your Sedoku solver as a separate object. This is pretty important since you use <code>SudokuGenerator</code> in your <code>main</code> function.</p>\n\n<p>On to styling, your <code>for</code> loops have awkwardly inconsistent formatting. You bounce btwn. using <code>++i</code> and <code>i++</code> (I prefer prefix b/c it used to give a performance boost, though now it probably doesn't matter), declaring variables inside and outside the loops, and using <code>i &lt; 9</code> and <code>i &lt;= 8</code>. The principle here is to just one form of logic. So let's start just lightly changing the program using these principles.</p>\n\n<p><strong><code>Main.java</code></strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static void main(String[] args) {\n SudokuGenerator gen = new SudokuGenerator();\n // initial transpose, shuffle &amp; seedChange happens in a constructor\n for (int i = 2; i &gt; 0; --i) {\n System.out.println(\"\\n\\n------ New Board --------\\n\");\n gen.transpose();\n gen.shuffle();\n gen.display();\n gen.seedChanger();\n }\n /*\n int n = 2;\n s.transpose();\n s.shuffle();\n s.seedChanger();\n while (n &gt; 0) {\n System.out.println(\"\\n\\n------ New Board --------\\n\");\n s.transpose();\n s.shuffle();\n s.display();\n s.seedChanger();\n n--;\n }\n */\n }\n</code></pre>\n\n<p>As the comment here says, the initial stuff you did to prepare the generator is now handled in its default constructor. You never edit <code>n</code> in those calls, so just declaring and modifying it in a <code>for</code> loop over a <code>while</code> is best here.</p>\n\n<p><strong>After some modification</strong></p>\n\n<p><strong><code>Main.java</code></strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>package T145.sudokugen;\n\npublic class Main {\n\n static char[][] transposedSeed = new char[][] {\n {'8', '2', '7', '1', '5', '4', '3', '9', '6'},\n {'9', '6', '5', '3', '2', '7', '1', '4', '8'},\n {'3', '4', '1', '6', '8', '9', '7', '5', '2'},\n {'5', '9', '3', '4', '6', '8', '2', '7', '1'},\n {'4', '7', '2', '5', '1', '3', '6', '8', '9'},\n {'6', '1', '8', '9', '7', '2', '4', '3', '5'},\n {'7', '8', '6', '2', '3', '5', '9', '1', '4'},\n {'1', '5', '4', '7', '9', '6', '8', '2', '3'},\n {'2', '3', '9', '8', '4', '1', '5', '6', '7'}\n };\n\n public static void main(String[] args) {\n Sudoku game = new Sudoku(transposedSeed);\n // initial transpose, shuffle &amp; seedChange happens in a constructor\n for (int i = 2; i &gt;= 0; --i) {\n System.out.println(\"\\n\\n------ New Board --------\\n\");\n game.transpose();\n game.shuffle();\n game.printBoard();\n game.seedChanger();\n }\n }\n}\n</code></pre>\n\n<p><strong><code>Sudoku.java</code></strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>package T145.sudokugen;\n\nimport java.util.Random;\n\npublic class Sudoku {\n\n private final char[][] transposedSeed;\n\n private char[][] board = new char[9][9];\n private int[] randomizeSudoku = new int[9];\n private char[][] seed = new char[9][9];\n private Random random = new Random();\n\n public Sudoku(char[][] transposedSeed) {\n this.transposedSeed = transposedSeed;\n\n transpose();\n shuffle();\n seedChanger();\n }\n\n public void transpose() {\n for (short i = 0; i &lt; 9; ++i) {\n for (short j = 0; j &lt; 9; ++j) {\n seed[j][i] = transposedSeed[i][j];\n }\n }\n }\n\n public void seedChanger() {\n for (short i = 0; i &lt; 9; ++i) {\n System.arraycopy(board[i], 0, transposedSeed[i], 0, board.length);\n }\n }\n\n public void randomSudokuGenerator() {\n short i = 0;\n\n for (i = 0; i &lt; randomizeSudoku.length; ++i) {\n randomizeSudoku[i] = 9;\n }\n\n for (i = 0; i &lt; randomizeSudoku.length; ++i) {\n int r = random.nextInt(2);\n\n for (int i1 = 0; i1 &lt; i; ++i1) {\n int x = randomizeSudoku[i1];\n\n if (x == r) {\n if (i &lt; 3) {\n r = random.nextInt(3);\n } else if (i &lt; 6) {\n r = random.nextInt(3) + 3;\n } else if (i &lt; 9) {\n r = random.nextInt(3) + 6;\n }\n\n i1 = -1;\n }\n }\n\n randomizeSudoku[i] = r;\n }\n }\n\n private void swap(char[][] a, int commonIndex, int first, int second) {\n char swap = a[commonIndex][first];\n a[commonIndex][first] = a[commonIndex][second];\n board[commonIndex][second] = swap;\n }\n\n public void shuffle() {\n randomSudokuGenerator();\n\n for (short x = 0; x &lt; 9; ++x) {\n board[0][x] = seed[randomizeSudoku[0]][x];\n board[1][x] = seed[randomizeSudoku[1]][x];\n board[2][x] = seed[randomizeSudoku[2]][x];\n board[3][x] = seed[randomizeSudoku[3]][x];\n board[4][x] = seed[randomizeSudoku[4]][x];\n board[5][x] = seed[randomizeSudoku[5]][x];\n board[6][x] = seed[randomizeSudoku[6]][x];\n board[7][x] = seed[randomizeSudoku[7]][x];\n board[8][x] = seed[randomizeSudoku[8]][x];\n }\n\n for (short x = 0; x &lt; 9; ++x) {\n if (randomizeSudoku[0] == 0) {\n swap(board, x, 1, 0);\n }\n\n if (randomizeSudoku[0] == 1) {\n swap(board, x, 2, 0);\n }\n\n if (randomizeSudoku[0] == 0) {\n swap(board, x, 5, 4);\n }\n\n if (randomizeSudoku[0] == 1) {\n swap(board, x, 5, 3);\n }\n\n if (randomizeSudoku[0] == 2) {\n swap(board, x, 8, 6);\n }\n }\n }\n\n public void printBoard() {\n for (short i = 0; i &lt; 9; ++i) {\n\n if (i == 0) {\n System.out.print(\"\\t\\t\\t_______________________________________\\n\\t row \" + (i + 1) + \"\\t\");\n } else {\n System.out.print(\"\\t\\t\\t|---|---|---||---|---|---||---|---|---|\\n\\t row \" + (i + 1) + \"\\t\");\n }\n\n for (short j = 0; j &lt; 9; ++j) {\n if (j == 3) {\n System.out.print(\"|\");\n }\n\n if (j == 6) {\n System.out.print(\"|\");\n }\n\n if (j == 8) {\n System.out.println(\"| \" + board[i][j] + \" |\");\n } else {\n System.out.print(\"| \" + board[i][j] + \" \");\n }\n }\n\n if (i == 2) {\n System.out.println(\"\\t\\t\\t|---|---|---||---|---|---||---|---|---|\");\n }\n\n if (i == 5) {\n System.out.println(\"\\t\\t\\t|---|---|---||---|---|---||---|---|---|\");\n }\n\n if (i == 8) {\n System.out.println(\"\\t\\t\\t---------------------------------------\");\n System.out.println(\"\\tcolumns 1 2 3 4 5 6 7 8 9 \\n\\n\\n\");\n }\n }\n }\n}\n</code></pre>\n\n<p>A majority of this is just simple re-formatting. You'll notice I use <code>short</code> over <code>int</code> in some cases, and this is just simply b/c <code>short</code>s have less of a memory imprint. It doesn't really matter b/c of just how much memory modern computers have, but I like to produce code that pays attention to the details.</p>\n\n<p>I haven't modified <em>any</em> of your core logic b/c of my initial reasoning. But to point you in the right direction, think about:</p>\n\n<p>1) Where the modulo operator (<code>%</code>) can be used to clean up some operations.</p>\n\n<p>2) Where you can use other <a href=\"https://simplenotions.wordpress.com/2009/05/13/java-standard-data-structures-big-o-notation/\" rel=\"nofollow noreferrer\">data structures to help optimize performance</a>.</p>\n\n<p>3) Where you can use Java 8+ abilities to optimize performance or at least slim down your code w/ equivalent performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T02:09:19.433", "Id": "426026", "Score": "0", "body": "Thanks for reviewing my code sir @T145 I have created this code on my own alone so I take full responsibility that I haven't given a structure to it and didn't use OOPS, I will try to make one code using all this concept because when I made this I didn't knew much about OOPS" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T02:09:53.460", "Id": "426027", "Score": "0", "body": "Thanks for your valuable time and support @T145" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T06:13:10.507", "Id": "426030", "Score": "0", "body": "sir @T145 i further optimized my code a bit and did some of the changes you recommended ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:32:56.240", "Id": "426174", "Score": "0", "body": "s/segway/segue :D" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T19:49:42.710", "Id": "220485", "ParentId": "220461", "Score": "1" } }, { "body": "<p>As recommended in answers , i updated my code a bit and further optimized it and tried to manage the tasks of methods.\nBelow are some changes i made ;</p>\n\n<p>Here , i put the initial transposing and shuffling into the constructor ,</p>\n\n<pre><code>private SudokuGenerator() {\n this.transpose();\n this.shuffle();\n this.seedChanger();\n}\n</code></pre>\n\n<p>Next i created a method generate() that generates the new sudoku ,</p>\n\n<pre><code>private void generate() {\n System.out.println(\"\\n\\n------ New Board --------\\n\");\n for (int i = 0; i &lt; random.nextInt(5); i++) {\n this.transpose();\n this.shuffle();\n this.seedChanger();\n }\n this.display();\n }\n</code></pre>\n\n<p>I optimized one of my method where i changed similar task for all index of array by using for loop ,</p>\n\n<p>old code :</p>\n\n<pre><code> for (short x = 0; x &lt; 9; ++x) {\n board[0][x] = seed[randomizeSudoku[0]][x];\n board[1][x] = seed[randomizeSudoku[1]][x];\n board[2][x] = seed[randomizeSudoku[2]][x];\n board[3][x] = seed[randomizeSudoku[3]][x];\n board[4][x] = seed[randomizeSudoku[4]][x];\n board[5][x] = seed[randomizeSudoku[5]][x];\n board[6][x] = seed[randomizeSudoku[6]][x];\n board[7][x] = seed[randomizeSudoku[7]][x];\n board[8][x] = seed[randomizeSudoku[8]][x];\n }\n</code></pre>\n\n<p>optimized code :</p>\n\n<pre><code>for (int x = 0; x &lt; 9; x++) {\n for (int i = 0; i &lt; 9; i++) {\n board[i][x] = seed[randomizeSudoku[i]][x];\n }\n }\n</code></pre>\n\n<p>And converted all <code>&lt;=8</code> into <code>&lt; 9</code>.</p>\n\n<p>void main now :</p>\n\n<pre><code> public static void main(String[] args) {\n SudokuGenerator s = new SudokuGenerator();\n s.generate();\n }\n</code></pre>\n\n<p>Is this better now ? @T145</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T04:46:48.997", "Id": "426114", "Score": "0", "body": "Try and execute the code as you have it in this post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T05:42:49.827", "Id": "426122", "Score": "0", "body": "you mean my updated code right....? I tried this it works fine. It gives me one new random Sudoku everytime , but I am still creating the object in the psvm of class SudokuGenerator . I know if I make my constructor public I can make an anonymous object in any class and call the method generate() and I can get a random solved Sudoku. @T145" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:45:10.573", "Id": "426178", "Score": "0", "body": "If you were to divide your code into separate classes as I have then this code wouldn't execute. You have your `SudokuGenerator`'s constructor as private, and therefore be inaccessible. Also, your `transposedSeed` shouldn't always be constant in theory, which is another reason to go for an OOD approach. Don't forget to select an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T14:07:16.833", "Id": "426183", "Score": "0", "body": "as I said earlier I know I should make my constructor public, and yes making transposed seed not constant is what I am going to think about, thanks." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T06:27:39.510", "Id": "220502", "ParentId": "220461", "Score": "0" } } ]
{ "AcceptedAnswerId": "220485", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T11:48:42.880", "Id": "220461", "Score": "2", "Tags": [ "java", "sudoku", "shuffle" ], "Title": "Sudoku generator using seed Sudoku" }
220461
<p>I was trying to output F(n) mod m to find the remainder of Fibonacci number, where F(n) could be a very big number:</p> <pre><code># Uses python3 n, m = [int(x) for x in input().split()] def fib(n): a = [0, 1] if (n &lt;=1): return n else: for i in range(1, n): a.append((a[-1] + a[-2])%m) return a[i+1] print (fib(n)) </code></pre> <p>As I typed in <code>239 1000</code>, it returns <code>161</code> as the remainder, which is correct. But with bigger inputs eg. <code>2816213588 239</code>, it seems to exceed time limits, what can I do to improve the code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T18:46:12.323", "Id": "426093", "Score": "1", "body": "Think about using this formulation for F(n) in log time https://codereview.stackexchange.com/questions/51864/calculate-fibonacci-in-olog-n" } ]
[ { "body": "<p>Sorry, I am giving no code (I am on a phone and I don't know Python), but be aware that if <code>m^2</code> is way lower than <code>n</code>, you could use the fact that your function gets periodical with a period maximally <code>m^2</code> (as both <code>a[-1]</code> and <code>a[-2]</code> can gain m different values).</p>\n\n<p>You could test in your <code>for</code> loop if/when you reached your period (if <code>a[-2]==0</code> and <code>a[-1]==1</code>) and if so, variable <code>i</code> would indicate your period. Then you could simply grab <code>a[n%(i-2)]</code> as the answer, if I am not mistaken.</p>\n\n<p>By the way, shouldn't the <code>for</code> loop range begin with 2?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T18:56:01.423", "Id": "426094", "Score": "0", "body": "Interesting point! Out of curiosity, is it known that the repeated pattern does contain the initial values (0, 1) or can we reach another loop ? (like A -> B -> C -> D -> E -> C -> D -> E -> C -> D -> E -> C -> D -> E)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:36:12.263", "Id": "426151", "Score": "0", "body": "The `for` loop range is irrelevant because the loop variable isn't used. `range(1, n)` contains as many elements as `range(2, n+1)`. Note that the sequence returned by `range` does not include the second argument." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T08:11:09.907", "Id": "426247", "Score": "1", "body": "@Josay I am pretty sure such C->D->E->C patterns cannot occur. I think, modulo addition (i.e. in a group) like this should divide the group (`0 .. n-1`) into congruent groups of the same size, each with a period equal to their size. But it is more an intuition now :). I do not remember most of my College Algebra now ... but I am sure Peter Taylor would know better (and I upvoted his answer, as he seems to remember more math than me :))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:54:04.470", "Id": "426261", "Score": "1", "body": "Pavol (cc @Josay), what I remembered was the phrase \"*Pisano period*\", which I used to look up information in Wikipedia and [OEIS](//oeis.org/A001175). L. Edson Jeffery states in OEIS that it does always repeat the initial values, and gives a reference. If I were to try to prove it independently I think I'd tackle it using Binet's formula in a suitable field extension of \\$\\mathbb{Z}/n\\mathbb{Z}\\$." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T04:43:55.527", "Id": "220498", "ParentId": "220466", "Score": "4" } }, { "body": "<p><strong>Code organisation</strong></p>\n\n<p>Le's write your function in such a way that it is easier to test. First step is to provide <code>m</code> as a parameter. Also, we can take this chance to write a proper docstring for the function. We get something like:</p>\n\n<pre><code>def fib(n, m):\n \"\"\"Compute Fibonnaci(n) % m.\"\"\"\n a = [0, 1]\n if (n &lt;=1):\n ret = n\n else:\n for i in range(1, n):\n a.append((a[-1] + a[-2])%m)\n ret = a[i+1]\n # print(ret)\n return ret\n</code></pre>\n\n<p>(The single return and print statements are added to make the next step easier).</p>\n\n<p>Now, we can add tests and add a computation of the time consumed. That benchmark will help ensuring our optimisations actually make things faster:</p>\n\n<pre><code>def test():\n start = time.time()\n assert fib(9, 32) == 2\n assert fib(9, 100) == 34\n assert fib(239, 1000) == 161\n assert fib(239, 100000000) == 88152161\n assert fib(239643, 100) == 62\n assert fib(2396434, 100) == 87\n end = time.time()\n print(end - start)\n</code></pre>\n\n<p><strong>Removing the array based logic</strong></p>\n\n<p>We define an array of value but we never really care about more than 2 values (the values at the end). We could rewrite this using 2 variables (and use the tuple unpacking that Python provides):</p>\n\n<pre><code>def fib(n, m):\n \"\"\"Compute Fibonnaci(n) % m.\"\"\"\n a, b = 0, 1\n if n &lt;= 1:\n ret = n\n else:\n for i in range(1, n):\n a, b = b, (a + b) % m\n ret = b\n print(ret)\n return ret\n</code></pre>\n\n<p>At this stage, the code is twice as fast.</p>\n\n<p><strong>Bug / weird edge case</strong></p>\n\n<p>The logic when <code>n &lt;= 1</code> does not take into account the <code>m</code> argument. This gives a wrong result for the following input:</p>\n\n<pre><code>assert fib(1, 1) == 0\n</code></pre>\n\n<p>This is a pretty degenerate case but it is easy to fix it.</p>\n\n<p>We can do:</p>\n\n<pre><code> ret = n % m\n</code></pre>\n\n<p>And add the following test cases:</p>\n\n<pre><code>assert fib(0, 1) == 0\nassert fib(1, 1) == 0\nassert fib(1, 10) == 1\nassert fib(1, 10) == 1\nassert fib(2, 10) == 1\nassert fib(3, 10) == 2\nassert fib(4, 10) == 3\nassert fib(5, 10) == 5\n</code></pre>\n\n<p>At this stage, we have:</p>\n\n<pre><code>def fib(n, m):\n \"\"\"Compute Fibonnaci(n) % m.\"\"\"\n if n &lt;= 1:\n return n % m\n else:\n a, b = 0, 1\n for i in range(1, n):\n a, b = b, (a + b) % m\n return b\n\ndef test():\n start = time.time()\n assert fib(0, 1) == 0\n assert fib(1, 1) == 0\n assert fib(1, 10) == 1\n assert fib(1, 10) == 1\n assert fib(2, 10) == 1\n assert fib(3, 10) == 2\n assert fib(4, 10) == 3\n assert fib(5, 10) == 5\n assert fib(9, 32) == 2\n assert fib(9, 100) == 34\n assert fib(239, 1000) == 161\n assert fib(239, 100000000) == 88152161\n assert fib(239643, 100) == 62\n assert fib(2396434, 100) == 87\n end = time.time()\n print(end - start)\n\n</code></pre>\n\n<p><strong>Using maths</strong></p>\n\n<p>A different algorithm could be written using mathematical properties. I have yet to find something interesting to provide... </p>\n\n<p><a href=\"https://codereview.stackexchange.com/users/170448/pavol-adam\">Pavol Adams' answer</a> seems to work just fine:</p>\n\n<pre><code>def fib(n, m):\n \"\"\"Compute Fibonnaci(n) % m.\"\"\"\n if n &lt;= 1:\n return n % m\n else:\n beg = (0, 1)\n a, b = beg\n cache = [a, b]\n for i in range(1, n):\n a, b = b, (a + b) % m\n if (a, b) == beg:\n return cache[n % i]\n cache.append(b)\n return b\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T17:59:39.080", "Id": "220520", "ParentId": "220466", "Score": "2" } }, { "body": "<blockquote>\n<pre><code># Uses python3\n</code></pre>\n</blockquote>\n\n<p>I don't see much to argue against documenting this instead with a hashbang:</p>\n\n<pre><code>#!/usr/bin/python3\n</code></pre>\n\n<p>Sure, on Windows that path won't work, but on many other platforms it will.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>n, m = [int(x) for x in input().split()]\n...\nprint (fib(n))\n</code></pre>\n</blockquote>\n\n<p>It is generally considered best practice to use</p>\n\n<pre><code>if __name__ == \"__main__\":\n ...\n</code></pre>\n\n<p>as a guard around \"immediate\" code. This makes the file reusable as a library.</p>\n\n<p>I don't understand the inconsistency in making <code>m</code> a global but <code>n</code> an argument to the function.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def fib(n):\n a = [0, 1]\n if (n &lt;=1):\n return n\n else:\n for i in range(1, n):\n a.append((a[-1] + a[-2])%m)\n return a[i+1]\n</code></pre>\n</blockquote>\n\n<p>There are two PEP8 violations in this code: the missing space after <code>&lt;=</code> on line 3, and the missing space around <code>%</code> on line 7. As a matter of style I would also drop the parentheses around the condition on line 3.</p>\n\n<p>Other answers have addressed saving memory by keeping only the two most recent values, or saving time by exploiting the periodicity modulo <code>m</code>. Depending on your priorities for optimisation and expected values of <code>n</code> and <code>m</code> there are a couple of other things you could consider:</p>\n\n<ul>\n<li>Using the identities <span class=\"math-container\">\\$F(2n) = 2 F(n+1) F(n) - F(n)^2\\$</span> and <span class=\"math-container\">\\$F(2n+1) = F(n+1)^2 + F(n)^2\\$</span> you can calculate <span class=\"math-container\">\\$F(n)\\$</span> in <span class=\"math-container\">\\$O(\\lg n)\\$</span> arithmetic operations. I describe this in much more detail, with SML code, <a href=\"http://cheddarmonk.org/Fibonacci.html\" rel=\"nofollow noreferrer\">on my personal website</a>.</li>\n<li>If you prefer to attack the running time via periodicity (perhaps because <span class=\"math-container\">\\$\\lg n &gt; 6m\\$</span>), there are some tricks you can use to try to optimise it. The <a href=\"https://en.wikipedia.org/wiki/Pisano_period\" rel=\"nofollow noreferrer\">Pisano period</a> is multiplicative, so if you can factor <code>m</code> that can reduce the number of steps you have to take to find the period. And there are number-theoretical theorems you can apply to reduce the search space.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T15:34:26.920", "Id": "220573", "ParentId": "220466", "Score": "3" } } ]
{ "AcceptedAnswerId": "220498", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T14:50:25.223", "Id": "220466", "Score": "3", "Tags": [ "python", "algorithm", "python-3.x", "time-limit-exceeded", "fibonacci-sequence" ], "Title": "Calculate the nth Fibonacci number, mod m" }
220466
<p>I am new to programming in Rust and as an exercise I was making a simple Lottery checker program. It has a simple menu, the user enters a number for the corresponding option such as 'Add a line', 'Check if I am a winner' etc.</p> <p>So all the user needs to do is enter either a number or a 'y' or 'n'. So I created a simple Token to see if they have either entered a number or a char and return a token.</p> <p>This works fine. But as I am on my own I was looking for feedback so that I can improve my skills.</p> <pre class="lang-rust prettyprint-override"><code>use std::io::{self, Write}; #[derive(Debug, PartialEq)] enum Token { Number(i32), Decision(char), // Error(String), } fn get_number(val: &amp;str) -&gt; Option&lt;Token&gt; { if let Some(x) = val.split_whitespace().next() { let y: i32 = match x.parse() { Ok(val) =&gt; val, Err(_error) =&gt; return None, }; Some(Token::Number(y)) } else { None } } fn get_char(val: &amp;str) -&gt; Option&lt;Token&gt; { if let Some(x) = val.split_whitespace().next() { let y: char = match x.parse() { Ok(val) =&gt; val, Err(_error) =&gt; return None, }; Some(Token::Decision(y)) } else { None } } fn get_input(msg: &amp;str, input: &amp;str) -&gt; Option&lt;Token&gt; { print!("{}\n{}", msg, "&gt;&gt; "); io::stdout().flush().unwrap(); let buffer = input; //let mut buffer = String::new(); // while buffer.is_empty() { // io::stdin() // .read_line(&amp;mut buffer) // .expect("GET_INPUT: error reading line."); // buffer = buffer // .trim() // .parse() // .expect("GET_INPUT: error parsing buffer"); // if buffer.is_empty() { // println!("You didn't enter anything.\n{}", &amp;msg) // }; // } if let Some(token) = get_number(&amp;buffer) { if let Token::Number(val) = token { return Some(Token::Number(val)); } } else if let Some(token) = get_char(&amp;buffer) { if let Token::Decision(val) = token { return Some(Token::Decision(val)); } } None } #[cfg(test)] mod tests { use super::*; #[test] fn get_input_test() { let chars1 = "@ n 23"; let chars2 = "34 n 23"; let chars3 = "$ ££$^\"3234y n 23"; let chars4 = ""; let chars5 = " "; assert_eq!(Some(Token::Decision('@')), get_input("", &amp;chars1)); assert_eq!(Some(Token::Number(34)), get_input("", &amp;chars2)); assert_eq!(Some(Token::Decision('$')), get_input("", &amp;chars3)); assert_eq!(None, get_input("", &amp;chars4)); assert_eq!(None, get_input("", &amp;chars5)); } } </code></pre> <p>To get some more fine grain control I understand I will need to use an Iterator, is this correct?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T16:21:07.397", "Id": "425980", "Score": "0", "body": "Please include the necessary code to fully reproduce the program. Fetching `std::io` and `std::io::Write` is needed to compile. The definition of `PROMPT` is also missing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T19:09:55.703", "Id": "426095", "Score": "0", "body": "it spread over several files\\modules what would be best way to upload. either upload the files or just paste all of it with annotations between code blocks. Thank you for your response" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T21:52:33.027", "Id": "426098", "Score": "0", "body": "Like on Stack Overflow, you are expected to include all of the necessary code to reproduce the program. [Here](https://stackoverflow.com/tags/rust/info) are a few more tips on making an MCVE for Rust code. In particular, your code should work on the [Rust Playground](//play.rust-lang.org)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:11:09.293", "Id": "426253", "Score": "0", "body": "I have updated the code so that it will work on Rust playground. I had problems with Rust playground and terminal input, so I took out the iostdin call and simulated the input." } ]
[ { "body": "<p>It's not clear whether you want to support only <code>y</code>, <code>n</code> and numbers as your question states, or any characters besides <code>y</code> &amp; <code>n</code> as your code implies :)</p>\n\n<p>Basically you can divide the problem to two sub problems:</p>\n\n<ol>\n<li>Split the input string to <code>words</code> I'm using the split methods from <code>std</code> but if you have more complex requirements, you can use the <code>regex</code> crate </li>\n<li>Map the <code>words</code> to tokens. A simple equality check (==) or <code>match</code> is enough. There is no need to <code>parse()</code> everything. </li>\n</ol>\n\n<p>As you've not specified what's allowed as a delimiter, I'll assume that it's <code>whitespace</code>. </p>\n\n<pre><code>#[derive(Debug)]\nenum InputToken {\n Number(i64),\n Boolean(bool),\n Error(String),\n}\n\nfn main() {\n let input = \"1 -2 +4 y n &amp; abc\";\n let tokens = input.split_whitespace();\n\n for x in tokens {\n println!(\"{:?}\", parse_token(x));\n }\n}\n\nfn parse_token(input: &amp;str) -&gt; InputToken {\n match input {\n \"y\" =&gt; InputToken::Boolean(true),\n \"n\" =&gt; InputToken::Boolean(false),\n token =&gt; match token.parse::&lt;i64&gt;() {\n Ok(num) =&gt; InputToken::Number(num),\n Err(e) =&gt; InputToken::Error(format!(\"Invalid input token [{}]: {:?}\", token, e))\n }\n}\n</code></pre>\n\n<p>}</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-28T10:55:57.550", "Id": "427594", "Score": "0", "body": "your assumptions are correct :) I don't find learning easy, so purpose of th epost is to get some feedback so I am not learning in a vacuum. Thank you for your post it has been very helpful. I didn't know you could nest matchs" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T06:52:28.193", "Id": "221095", "ParentId": "220471", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T15:45:04.723", "Id": "220471", "Score": "6", "Tags": [ "parsing", "validation", "io", "rust" ], "Title": "Simple function to create Tokens from user input" }
220471
<p>Currently my code is based around mouse events so that it is easier to test but I will be swapping these to touch events once I have had the code reviewed. The idea of the UX is that you need to mousedown for 500ms until you can move the spot (similar to that of iOS when re-arranging apps on the homescreen). Then the spot shows you it's in a movable state then you can drop it.</p> <p>The code works exactly as I want it to but I can't help but think that I have over-engineered it. This is why I have posted for review.</p> <p><a href="https://codepen.io/2ne/pen/eaROQq" rel="nofollow noreferrer">Codepen Link</a></p> <pre><code>const spotState = { moveable: false } const spotEL = document.getElementById('spot'); const statusEL = document.getElementById('status'); spotEL.onmouseenter = function() { statusEL.innerHTML = "Enter"; clearTimeout(spotState.mouseDownTimer); spotState.mouseDownTimer = null; spotState.moveable = false; spotState.moving = false; spotEL.classList.remove('moving'); spotState.clear &amp;&amp; spotState.clear(); } spotEL.onmouseleave = function() { statusEL.innerHTML = "Leave"; clearTimeout(spotState.mouseDownTimer); spotState.mouseDownTimer = null; spotState.moveable = false; spotState.moving = false; spotEL.classList.remove('moving'); spotState.clear &amp;&amp; spotState.clear(); } spotEL.onmousedown = function(event) { spotState.mouseDownTimer = setTimeout(function(){ statusEL.innerHTML = "Down"; spotEL.classList.add('moving'); spotState.moveable = true spotState.mouseDownTimer = null let shiftX = event.clientX - spot.getBoundingClientRect().left; let shiftY = event.clientY - spot.getBoundingClientRect().top; moveAt(event.pageX, event.pageY); function moveAt(pageX, pageY) { if (spotState.moveable || spotState.moving) { spotState.moving = true; spotEL.style.left = pageX - shiftX + 'px'; spotEL.style.top = pageY - shiftY + 'px'; } }; function onMouseMove(event) { statusEL.innerHTML = "Move"; moveAt(event.pageX, event.pageY); }; document.addEventListener('mousemove', onMouseMove); spotState.clear = function() { document.removeEventListener('mousemove', onMouseMove); } }, 350); spotEL.onmouseup = function() { statusEL.innerHTML = "Up"; clearTimeout(spotState.mouseDownTimer); spotEL.classList.remove('moving'); spotEL.onmouseup = null; spotState.moving = false; spotState.moveable = false; spotState.mouseDownTimer = null; spotEL.onmousemove = null; spotState.clear &amp;&amp; spotState.clear(); }; }; spotEL.ondragstart = function() { return false; }; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T16:16:35.930", "Id": "220474", "Score": "1", "Tags": [ "html", "event-handling", "dom", "typescript" ], "Title": "Dragging and dropping a spot using TypeScript" }
220474
<p>After I've now officially announced, that I'm discontinuing my color picker for Windows, I'm about to embark on a journey through Linux development.</p> <hr> <p>I was quite strong in <strong><a href="https://www.embarcadero.com/products/delphi" rel="nofollow noreferrer">Delphi</a></strong> on <em>Windows</em>, and see no valid reason to focus - not that I'm not trying to, in quite many languages - mainly on development in <strong><a href="https://www.lazarus-ide.org/" rel="nofollow noreferrer">Lazarus</a></strong> on <em>Linux</em>, as of now in major version 2.0. Without wanting to pay for an IDE, I just decided to stick with Lazarus.</p> <hr> <p>That's enough for starters. Let's get to my question.</p> <p>I haven't developed in Delphi since version XE6 dated 2014, so I need to refresh my knowledge, and this question is about the very core of the new color picker for Linux. Feel free to add any answer or comment. If I did the smallest error, I need to know. The first class I've written is meant for keeping track of X, Y coordinates (of the mouse cursor), I generalized it.</p> <hr> <pre class="lang-delphi prettyprint-override"><code>unit Coords; {$mode objfpc}{$H+} interface uses Classes; type // Flexible X, Y coordinates object class. TCoords = class(TObject) // these declarations are accessible within this unit only private // this is the variable we are working with FCoords: TPoint; // property for this function is unnecessary, but I like it as it is function IsInitialized: Boolean; // these declarations are visible and accessible to all public // this creates instance of TCoords initialized to PointOutOfReach constructor Create; reintroduce; overload; // this creates instance of TCoords initialized to user given point constructor Create(const ACoords: TPoint); overload; // this creates instance of TCoords initialized to user given coordinates constructor Create(const AX, AY: Integer); overload; // this indicates if instance was initialized or not by the user property Initialized: Boolean read IsInitialized; // this works directly with private FCoords variable storing coordinates property P: TPoint read FCoords write FCoords; // these two are shortcuts for X, Y coordinates' direct access property X: Integer read FCoords.X write FCoords.X; property Y: Integer read FCoords.Y write FCoords.Y; end; implementation var // this gets initialized when loading this unit PointOutOfReach: TPoint; constructor TCoords.Create; begin inherited Create; // since called without argument, we have to ensure, // there are some corner-case coordinates, so that we can // differentiate between a [0:0] and uninitialized state FCoords := PointOutOfReach; end; constructor TCoords.Create(const ACoords: TPoint); begin inherited Create; FCoords := ACoords; end; constructor TCoords.Create(const AX, AY: Integer); begin inherited Create; FCoords := Point(AX, AY); end; function TCoords.IsInitialized: Boolean; begin // this returns True in case FCoords has been initialized // initialized means here for the FCoords point to be different from PointOutOfReach // achieved either by calling `Create(APoint)`, or later overwriting PointOutOfReach Result := FCoords &lt;&gt; PointOutOfReach; end; initialization // initialize PointOutOfReach to "impossible" coordinates when loading unit PointOutOfReach := Point(MAXINT, MAXINT); end. </code></pre> <hr> <h2>Edit</h2> <p>Since there is not yet a review, I could edit, that I've added one useful function:</p> <p>declaration</p> <pre class="lang-delphi prettyprint-override"><code>// this converts the coordinates to string (default delimiter set to colon) function ToString(const Delimiter: string = ':'): string; reintroduce; </code></pre> <p>definition</p> <pre class="lang-delphi prettyprint-override"><code>function TCoords.ToString(const Delimiter: string = ':'): string; begin // setting empty result for debugging purposes solely Result := ''; // this can happen only if constructor TCoords.Create; has been used if not IsInitialized then begin raise Exception.Create('TCoords.ToString: `FCoords: TPoint` member has not yet been initialized'); end; // it does not make sence for the user to input empty delimiter // as that would lead to concatenating XY without any delimiter if Delimiter.IsEmpty then begin raise Exception.Create('TCoords.ToString: `Delimiter: string` argument is empty'); end; // example: X=0, Y=1, Delimiter=' x ' would return '0 x 1' Result := FCoords.X.ToString + Delimiter + FCoords.Y.ToString; end; </code></pre>
[]
[ { "body": "\n\n<blockquote>\n<pre class=\"lang-delphi prettyprint-override\"><code>unit Coords;\n ^\n</code></pre>\n</blockquote>\n\n<p>If you noticed the big letter, let me tell you this was a bad start. I saved the unit file as <code>Coords.pas</code>, which lead to a series of various files' edits. Not recommended. Stick to lower-case:</p>\n\n<pre class=\"lang-delphi prettyprint-override\"><code>unit coords;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-delphi prettyprint-override\"><code>TCoords = class(TObject)\n</code></pre>\n</blockquote>\n\n<p><code>TObject</code> class is implicit, so it may be omitted:</p>\n\n<pre class=\"lang-delphi prettyprint-override\"><code>TCoords = class\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-delphi prettyprint-override\"><code>private\n</code></pre>\n</blockquote>\n\n<p>This protects members on unit scope only. Since I intended to protect members on class scope, I now use:</p>\n\n<pre class=\"lang-delphi prettyprint-override\"><code>strict private\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-delphi prettyprint-override\"><code>function IsInitialized: Boolean;\n</code></pre>\n</blockquote>\n\n<p>This is not only unnecessary but it also clouded my judgment as for not having any <em>getters</em> nor <em>setters</em>, I now have:</p>\n\n<pre class=\"lang-delphi prettyprint-override\"><code>function GetCoordX: Integer;\nfunction GetCoordY: Integer;\nfunction GetPoint: TPoint;\nprocedure SetCoordX(const NewX: Integer);\nprocedure SetCoordY(const NewY: Integer);\nprocedure SetPoint(const NewPoint: TPoint);\n</code></pre>\n\n<p>Definitions can be found at the bottom of this answer.</p>\n\n<hr>\n\n<pre class=\"lang-delphi prettyprint-override\"><code>// ...\n</code></pre>\n\n<p>Excessive commenting I found not helpful, only making a mess.</p>\n\n<hr>\n\n<p>I was not properly checking the input in all cases. This was remedied (I hope). Also, raising exceptions in case of error proved helpful.</p>\n\n<hr>\n\n<p>The <code>initialization</code> section along with the <code>PointOutOfReach</code> variable can be deleted, the more code I have, the less of its usefulness I saw, using structures like this one has proven more helpful:</p>\n\n<pre class=\"lang-delphi prettyprint-override\"><code>if (ACoords.X = MAXINT) or (ACoords.Y = MAXINT) then\nbegin\n raise Exception.Create('TCoords.Create: You cannot initialize `FCoords: TPoint` member to MAXINT coordinates');\nend;\n</code></pre>\n\n<hr>\n\n<h2>Code after review</h2>\n\n<pre class=\"lang-delphi prettyprint-override\"><code>unit coords;\n\n{$mode objfpc}{$H+}\n\ninterface\n\nuses\n Classes, SysUtils;\n\ntype\n TCoords = class\n strict private\n FCoords: TPoint;\n function GetCoordX: Integer;\n function GetCoordY: Integer;\n function GetPoint: TPoint;\n procedure SetCoordX(const NewX: Integer);\n procedure SetCoordY(const NewY: Integer);\n procedure SetPoint(const NewPoint: TPoint);\n public\n constructor Create; reintroduce; overload;\n constructor Create(const ACoords: TPoint); overload;\n constructor Create(const ACoordX, ACoordY: Integer); overload;\n function ToString(const Delimiter: string = ':'): string; reintroduce;\n property X: Integer read GetCoordX write SetCoordX;\n property Y: Integer read GetCoordY write SetCoordY;\n property P: TPoint read GetPoint write SetPoint;\n end;\n\nimplementation\n\nconstructor TCoords.Create;\nbegin\n inherited Create;\n\n FCoords := Point(MAXINT, MAXINT);\nend;\n\nconstructor TCoords.Create(const ACoords: TPoint);\nbegin\n inherited Create;\n\n if (ACoords.X = MAXINT) or (ACoords.Y = MAXINT) then\n begin\n raise Exception.Create('TCoords.Create: You cannot initialize `FCoords: TPoint` member to MAXINT coordinates');\n end;\n\n FCoords := ACoords;\nend;\n\nconstructor TCoords.Create(const ACoordX, ACoordY: Integer);\nbegin\n inherited Create;\n\n if (ACoordX = MAXINT) or (ACoordY = MAXINT) then\n begin\n raise Exception.Create('TCoords.Create: You cannot initialize `FCoords: TPoint` member to MAXINT coordinates');\n end;\n\n FCoords := Point(ACoordX, ACoordY);\nend;\n\nfunction TCoords.GetCoordX: Integer;\nbegin\n if FCoords.X = MAXINT then\n begin\n raise Exception.Create('TCoords.GetCoordX: `FCoords.X: Integer` is equal to MAXINT. It has not been initialized yet');\n end;\n\n Result := FCoords.X;\nend;\n\nfunction TCoords.GetCoordY: Integer;\nbegin\n if FCoords.Y = MAXINT then\n begin\n raise Exception.Create('TCoords.GetCoordY: `FCoords.Y: Integer` is equal to MAXINT. It has not been initialized yet');\n end;\n\n Result := FCoords.Y;\nend;\n\nprocedure TCoords.SetCoordX(const NewX: Integer);\nbegin\n if NewX = MAXINT then\n begin\n raise Exception.Create('TCoords.SetCoordX: `NewX: Integer` value cannot equal MAXINT');\n end;\n\n FCoords.X := NewX;\nend;\n\nprocedure TCoords.SetCoordY(const NewY: Integer);\nbegin\n if NewY = MAXINT then\n begin\n raise Exception.Create('TCoords.SetCoordY: `NewY: Integer` value cannot equal MAXINT');\n end;\n\n FCoords.Y := NewY;\nend;\n\nfunction TCoords.GetPoint: TPoint;\nbegin\n Result := Point(GetCoordX, GetCoordY);\nend;\n\nprocedure TCoords.SetPoint(const NewPoint: TPoint);\nbegin\n SetCoordX(NewPoint.X);\n SetCoordY(NewPoint.Y);\nend;\n\nfunction TCoords.ToString(const Delimiter: string = ':'): string;\nbegin\n if Delimiter.IsEmpty then\n begin\n raise Exception.Create('TCoords.ToString: `Delimiter: string` argument is empty');\n end;\n\n // example: X=0, Y=1, Delimiter=' x ' would return '0 x 1'\n Result := GetCoordX.ToString + Delimiter + GetCoordY.ToString;\nend;\n\nend.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T03:51:46.413", "Id": "220878", "ParentId": "220480", "Score": "1" } } ]
{ "AcceptedAnswerId": "220878", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T17:50:34.663", "Id": "220480", "Score": "2", "Tags": [ "object-oriented", "coordinate-system", "pascal" ], "Title": "X, Y Coordinates class in Lazarus (Delphi-like)" }
220480
<p>It includes LCL which is more or less compatible with Delphi's VCL. Free Pascal is a GPL'ed compiler that runs on Linux, Win32, OS/2, 68K and more. Free Pascal is designed to be able to understand and compile Delphi syntax, which is OOP. Lazarus is the Delphi-like IDE for Free Pascal.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T17:53:10.167", "Id": "220481", "Score": "0", "Tags": null, "Title": null }
220481
Lazarus is a Delphi-compatible cross-platform IDE for Free Pascal.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T17:53:10.167", "Id": "220482", "Score": "0", "Tags": null, "Title": null }
220482
<p>I am working on a application that is made completely in JavaScript (other than the database) and I've created a simple user management system for the application. </p> <p>This user management system creates a query to the database containing the user info (the database contains the user info not the query) based on a few command line arguments, decrypts the data in the database, and then prints the result to the console. </p> <p>I have been programming for 2 years but am self-taught and was looking for some feedback/criticism on my code.</p> <p><strong>Note:</strong> Some of the modules in the Main script are not included but, for the most part, their functions should be intuitive.</p> <p><strong>Edit:</strong> for more information about the <code>DataBase</code> class see <a href="https://codereview.stackexchange.com/questions/220515/node-js-database-class-for-adodb-databases">this</a> question.</p> <p>Here is my code:</p> <h3>Main script:</h3> <pre><code>// this is a instance of a `DataBase` class: const users = require('../../Code/MiddleWare/Database-comms/createUser').users const lookup = require('./lookup') const decryptAll = require('./decrypt') void async function() { if(process.argv[2] === '-e') { console.dir(decryptAll(await lookup('Email', process.argv[3], users, process.argv[4] === '-ex')), {colors: true, depth: Infinity}) } else if(process.argv[2] ? process.argv[2].match(/^\d+$/) : false) { console.dir(decryptAll(await lookup('ID', parseInt(process.argv[2]), users, process.argv[3] === '-ex', false)), {colors: true, depth: Infinity}) } else { console.dir(decryptAll(await lookup('Username', process.argv[2] ? process.argv[2] : '', users, process.argv[3] === '-ex')), {colors: true, depth: Infinity}) } }() </code></pre> <h3>"lookup" module:</h3> <pre><code>module.exports = async function(type, string, users, exact, encrypted = true) { const aes = require('../../Code/MiddleWare/Security/index').encryption.AES const retval = [] await users.query('Users').then((data) =&gt; { for(let i of data) { if(encrypted ? (exact? aes.decrypt(i[type]) === string : aes.decrypt(i[type]).match(string)) : i[type] === string) { retval.push(i) } } }) return retval.length === 0 ? false : retval } </code></pre> <h3>The "decrypt" module:</h3> <pre><code>const decrypt = require('../../Code/MiddleWare/Security/encryption').AES.decrypt module.exports = function(array) { if(!array) { return false } const retval = [] function decryptAll(obj) { return {ID: obj.ID, Username: decrypt(obj.Username), Email: decrypt(obj.Email), Data: decrypt(obj.Data), Password: obj.Password} } for(const i of array) { const item = decryptAll(i) item.Data = JSON.parse(item.Data) retval.push(item) } return retval } </code></pre>
[]
[ { "body": "<h2>Main script</h2>\n\n<ul>\n<li>Consider using the <a href=\"https://www.npmjs.com/package/commander\" rel=\"nofollow noreferrer\"><code>commander</code></a> module. One benefit you get is that it parses arguments for you. Another is that the API that declares the arguments and options autogenerates <code>--help</code> text for you. This way, you avoid having to write all the argument parsing yourself and you get a self-documenting CLI.</li>\n</ul>\n\n<h2>Lookup module</h2>\n\n<ul>\n<li><p>Move that <code>require</code> call outside the function. You only need to import <code>aes</code> once, not on every call to the lookup function.</p></li>\n<li><p>When inside an <code>async</code> function, you can use <code>await</code> to write async operations in a synchronous-looking fashion. When you use <code>await</code>, you can assign the resolved value of an async operation to a variable in the same way you do it with synchronous operation.</p></li>\n<li><p>The code inside the <code>for-of</code> is essentially a filter operation. Consider using <code>array.filter()</code> instead, assuming <code>data</code> is just an array.</p></li>\n<li><p>I also recommend breaking out that nested ternary into nested <code>if</code> statements for readability. You could arrange the conditions so that it's cascading rather than nested.</p></li>\n<li><p>I recommend returning an empty array instead of <code>false</code> when no matches are found. This way, the consuming code won't have to deal with type checking. </p></li>\n</ul>\n\n<h2>Decrypt module</h2>\n\n<ul>\n<li><p>The <code>decryptAll</code> function does not appear to rely on any variables in the scope of the exported function. You can move <code>decryptAll</code> out of that function.</p></li>\n<li><p>That <code>for-of</code> is essentially a mapping function (transforming one array's values into another array of values). Use <code>array.map()</code> instead.</p></li>\n<li><p>Since <code>decryptAll</code> is just mapping select properties into a new object, you can use a combination of destructuring and shorthand properties to simplify it.</p></li>\n</ul>\n\n<hr>\n\n<p>Bottom line, your code could look like this:</p>\n\n<h2>Lookup</h2>\n\n<pre><code>const aes = require('../../Code/MiddleWare/Security/index').encryption.AES\n\nmodule.exports = async function(type, string, users, exact, encrypted = true) {\n return await users.query('Users').filter(i =&gt; {\n\n // Technically, the encrypted block is a nested ternary in the\n // false portion of the first ternary. But written this way, \n // it looks like a flat list.\n return !encrypted ? i[type] === string\n : exact ? aes.decrypt(i[type]) === string\n : aes.decrypt(i[type]).match(string)\n })\n}\n</code></pre>\n\n<h2>Decrypt</h2>\n\n<pre><code>const decrypt = require('../../Code/MiddleWare/Security/encryption').AES.decrypt\n\n// Destructure arguments, then return an object with shorthand properties.\n// Eliminates obj.\nconst decryptAll = ({ ID, Username, Email, Data, Password }) =&gt; {\n return { ID, Username, Email, Data, Password }\n}\n\nmodule.exports = function(array) {\n // We're expecting an array so the check is no longer needed.\n\n const retval = array.map(i =&gt; {\n const item = decryptAll(i)\n const itemWithDecryptedData = { ...item, Data: JSON.parse(item.Data) }\n return itemWithDecryptedData\n })\n\n return retval\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:48:52.440", "Id": "220762", "ParentId": "220483", "Score": "1" } } ]
{ "AcceptedAnswerId": "220762", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T18:49:28.903", "Id": "220483", "Score": "4", "Tags": [ "javascript", "node.js" ], "Title": "Simple Node.js user management system" }
220483
<p>I have network printers which have different attributes (e.g. supported network protocols, languages, status, print modes).</p> <pre><code>public abstract class PrinterAttribute { protected PrinterAttribute(int value, string dsc) { this.Value = value; this.Dsc = dsc; } protected PrinterAttribute(int value, string dsc, Enum type) : this(value, dsc) { this.Type = type; } protected int Value { get; private set; } protected string Dsc { get; private set; } protected Enum Type { get; private set; } } </code></pre> <p>And finally I will have number of classes like <code>NetworkProtocolAttribute</code>, <code>PrinterModeAttribute</code>.</p> <pre><code>public class NetworkProtocolAttribute : PrinterAttribute { public NetworkProtocolAttribute(int value, string dsc) : base(value, dsc) {} public NetworkProtocolAttribute(int value, string dsc, ProtocolType protocolType) : base(value, dsc, protocolType) {} #region 1. way - get desired network protocol from locating it in all possible ones // all possible network protocols that a printer can support private static IList&lt;NetworkProtocolAttribute&gt; allPossibleProtocols; private static IList&lt;NetworkProtocolAttribute&gt; AllPossibleProtocols { get { if(allPossibleProtocols == null) { allPossibleProtocols = new List&lt;NetworkProtocolAttribute&gt;() { new NetworkProtocolAttribute(0, "None"), new NetworkProtocolAttribute(1, "FTP"), new NetworkProtocolAttribute(2, "LPD"), new NetworkProtocolAttribute(4, "TCP"), new NetworkProtocolAttribute(8, "UDP"), new NetworkProtocolAttribute(0x10, "HTTP"), new NetworkProtocolAttribute(0x20, "SMTP"), // simple mail transfer protocol new NetworkProtocolAttribute(0x40, "POP3"), new NetworkProtocolAttribute(0x80, "SNMP"), // simple network management protocol new NetworkProtocolAttribute(0x100, "Telnet"), new NetworkProtocolAttribute(0x200, "Weblink"), new NetworkProtocolAttribute(0x400, "TLS"), new NetworkProtocolAttribute(0x800, "HTTPS") }; } return allPossibleProtocols; } } public static NetworkProtocolAttribute SMTP_FirstWay { get { // don't like it because you locate it by value return AllPossibleProtocols.Single(x =&gt; x.Value == 0x80); } } #endregion #region 2. way - create public static NetworkProtocol for every possible protocol private static NetworkProtocolAttribute smtp; public static NetworkProtocolAttribute SMTP_SecondWay { get { if( smtp == null) { smtp = new NetworkProtocolAttribute(0x80, "SNMP"); } return smtp; } } #endregion #region 3. way - create enum and find it by enum public enum ProtocolType : int { None, FTP, LPD, TCP, UDP, HTTP, SMTP, POP3, SNMP, Telnet, Weblink, TLS, HTTPS } private static IList&lt;NetworkProtocolAttribute&gt; allPossibleProtocols3; protected static IList&lt;NetworkProtocolAttribute&gt; AllPossibleProtocols3 { get { if (allPossibleProtocols3 == null) { allPossibleProtocols3 = new List&lt;NetworkProtocolAttribute&gt;() { new NetworkProtocolAttribute(0, "None", ProtocolType.None), new NetworkProtocolAttribute(1, "FTP", ProtocolType.FTP), new NetworkProtocolAttribute(2, "LPD", ProtocolType.LPD), new NetworkProtocolAttribute(4, "TCP", ProtocolType.TCP), new NetworkProtocolAttribute(8, "UDP", ProtocolType.UDP), new NetworkProtocolAttribute(0x10, "HTTP", ProtocolType.HTTP), new NetworkProtocolAttribute(0x20, "SMTP", ProtocolType.SMTP), new NetworkProtocolAttribute(0x40, "POP3", ProtocolType.POP3), new NetworkProtocolAttribute(0x80, "SNMP", ProtocolType.SNMP), new NetworkProtocolAttribute(0x100, "Telnet", ProtocolType.Telnet), new NetworkProtocolAttribute(0x200, "Weblink", ProtocolType.Weblink), new NetworkProtocolAttribute(0x400, "TLS", ProtocolType.Telnet), new NetworkProtocolAttribute(0x800, "HTTPS", ProtocolType.HTTPS) }; } return allPossibleProtocols3; } } public static NetworkProtocolAttribute GetProtocol_ThirdWay(ProtocolType protocolType) { NetworkProtocolAttribute match = AllPossibleProtocols3.Where(x =&gt; x.Type.Equals(protocolType)).SingleOrDefault(); return match; } #endregion </code></pre> <p>And finally how would one get desired supported protocol by network printer:</p> <pre><code>class Program { static void Main(string[] args) { // 1. way NetworkProtocolAttribute protocol1 = NetworkProtocolAttribute.SMTP_FirstWay; // 2. way NetworkProtocolAttribute protocol2 = NetworkProtocolAttribute.SMTP_SecondWay; // 3. way NetworkProtocolAttribute protocol3 = NetworkProtocolAttribute.GetProtocol_ThirdWay( NetworkProtocolAttribute.ProtocolType.SMTP); Console.ReadKey(); } </code></pre> <p>What I like about 1. and 3. way is that you see a list of all possible protocols. 3. way also has just one method to get protocol, while 2. way has one method for each protocol.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T20:28:33.537", "Id": "426000", "Score": "0", "body": "Why is SMTP called SNMP?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T10:19:13.593", "Id": "426050", "Score": "1", "body": "@200_success those two are two different protocols. SMTP = simple mail transfer protocol and SNMP = simple network managament protocol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T14:20:09.233", "Id": "426070", "Score": "2", "body": "This looks like some kind of custom enum type. What problem are you trying to solve that cannot be addressed by using a simple enum? Also, why is almost everything of interest `protected` instead of `public`?" } ]
[ { "body": "<h3>Custom vs. normal enum</h3>\n\n<p>This looks like some kind of custom enum type, but in its current form it's not very useful:</p>\n\n<ul>\n<li>All properties in <code>PrinterAttribute</code> are <code>protected</code>, which means that only derived classes can access them. That's not very useful for other code.</li>\n<li>A property of type <code>Enum</code> is cumbersome to use because it's too weakly typed. It only tells you that it's an enum, but not which one, so you still don't know which values are valid.</li>\n<li>Enum values can already be given a specific numeric value, so you don't need that <code>Value</code> property.</li>\n<li><code>NetworkProtocolAttribute.FTP == new NetworkProtocolAttribute(1, \"FTP\")</code> fails because they're not the same instance. The same goes for calling <code>Equals</code>. You'll want to implement the relevant operators, as well as override the standard <code>Equals</code> method (and with that, also <code>GetHashCode</code>). Implementing <code>IEquatable&lt;T&gt;</code> is also a good idea.</li>\n</ul>\n\n<p>Have you considered using a normal enum instead?</p>\n\n<pre><code>[Flags] // Indicates that this enum is intended to be used as a bitmask\npublic enum Protocol // No need to specify int as underlying type\n{\n None = 0x00,\n FTP = 0x01,\n LPD = 0x02,\n TCP = 0x04,\n UDP = 0x08,\n HTTP = 0x10,\n SMTP = 0x20,\n // and so on\n}\n\n// Use:\nvar protocol = Protocol.FTP;\nprotocol.ToString(); // -&gt; \"FTP\"\n\nvar protocols = Protocol.FTP | Protocol.UDP;\nprotocols.HasFlag(Protocol.UDP); // -&gt; true\n\nEnum.GetValues(typeof(Protocol)); // -&gt; Protocol[] { None, FTP, LDP, ... }\n</code></pre>\n\n<p>You could add <code>[Description(\"...\")]</code> attributes to these values if you really need to, but the enum names themselves are already descriptive enough. If you're using such descriptions for display purposes then that's better done at the UI layer (due to things like localization).</p>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>Don't use <code>IList&lt;T&gt;</code> for static read-only properties: it allows other code to modify your list. Use <code>IEnumerable&lt;T&gt;</code>, <code>IReadOnlyCollection&lt;T&gt;</code> or <code>IReadOnlyList&lt;T&gt;</code> instead. Additionally, use an actual <code>ReadOnlyCollection&lt;T&gt;</code> (<code>List&lt;T&gt;</code> has a convenient <code>AsReadOnly</code> method for that).</li>\n<li>Properties can be initialized directly: <code>Foo MyProperty { get; } = new Foo();</code>, so you don't need to explicitly define a field and perform a null-check in your getters. That null-check approach isn't thread-safe, bytheway, so if you really do need lazy initialization, use <code>Lazy&lt;T&gt;</code> or <code>LazyInitializer</code> instead.</li>\n<li><code>NetworkProtocolAttribute protocol1 = NetworkProtocolAttribute.SMTP_FirstWay;</code> can be shortened to <code>var protocol1 = NetworkProtocolAttribute.SMTP_FirstWay;</code>. This lets the compiler infer the type, so you don't need to write out types twice if it's already obvious from the right-hand side.</li>\n<li><code>.Where(...).FirstOrDefault()</code> can be simplified to <code>.FirstOrDefault(...)</code>.</li>\n<li>Personally I don't like to use <code>this.</code>. Properties are written in PascalCase, parameters in camelCase, so <code>Value = value;</code> is clear enough for me.</li>\n<li>Properties that are meant to be read-only don't need a setter.</li>\n<li>Just write <code>Description</code> out full - readability is important, especially in the long run, and writing doesn't take that much time with the help of auto-completion tools.</li>\n<li>The names of your classes suggest that they're attributes - special types that are used to attach meta-data to other code. Because you're not inheriting from <code>System.Attribute</code>, that's apparently not what you intended, so you may want to pick different names to avoid confusion.</li>\n</ul>\n\n<p>Finally, with regards to the linear lookups in #1 and #3, you can get rid of those by inverting the relationship between the list and the other properties:</p>\n\n<pre><code>public static NetworkProtocolAttribute FTP { get; } = new NetworkProtocolAttribute(1, \"FTP\");\npublic static NetworkProtocolAttribute LPD { get; } = new NetworkProtocolAttribute(2, \"LPD\");\n// and so on...\n\npublic static IReadOnlyList&lt;NetworkProtocolAttribute&gt; AllProtocols { get; }\n = new List&lt;NetworkProtocolAttribute&gt; {\n FTP,\n LPD,\n // and so on...\n }.AsReadOnly();\n</code></pre>\n\n<p>But again, unless you have some specific requirements, I would just use normal enums.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:05:15.393", "Id": "220552", "ParentId": "220484", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T19:40:02.150", "Id": "220484", "Score": "3", "Tags": [ "c#", "comparative-review", "api", "networking", "enum" ], "Title": "API for multiple printer attributes" }
220484
<p>I'm still pretty new to programming, only been doing it a week. I'm just wondering if I made any glaring mistakes or anything that could be improved code wise?</p> <pre><code>import random the_board = [] players = [{'type': 'player', 'piece': 'X'}, {'type': 'player', 'level': 'smart', 'piece': 'O'}] def print_board(board): for i in range(3): print(board[i * 3] + '|' + board[i * 3 + 1] + '|' + board[i * 3 + 2], end='') print(' ' + str(i * 3) + '|' + str(i * 3 + 1) + '|' + str(i * 3 + 2)) if i &lt; 2: print('-+-+-' + ' ' + '-+-+-') print() def is_win(bo, player): # 0 1 2 # 3 4 5 # 6 7 8 for i in range(3): return (bo[i * 3] == player and bo[i * 3 + 1] == player and bo[i * 3 + 2] == player) or \ (bo[i] == player and bo[i+3] == player and bo[i+6] == player) or \ (i &lt;= 1 and (bo[i*2] == player and bo[4] == player and bo[8-(i*2)] == player)) def check_board(move, player): global the_board board_copy = the_board.copy() board_copy[move] = players[player]['piece'] print('win') return is_win(board_copy, players[player]['piece']) def ai(): global players, the_board possible_moves = [] final_move = None for i in range(9): if the_board[i] == ' ': possible_moves.append(i) if the_board[4] == ' ' and players[1]['level'] == 'smart': the_board[4] = players[1]['piece'] return for i in range(len(possible_moves)): board_copy = the_board.copy() board_copy[possible_moves[i]] = players[1]['piece'] if check_board(possible_moves[i], 1): the_board[possible_moves[i]] = players[1]['piece'] print('win') return elif check_board(possible_moves[i], 0): print('lose') final_move = possible_moves[i] elif players[1]['level'] == 'smart' and final_move is None: if possible_moves[i] in [0, 2, 6, 8]: print('random') final_move = possible_moves[i] else: if final_move is not None: print('other') the_board[final_move] = players[1]['piece'] return print('final') the_board[possible_moves[random.randint(0, len(possible_moves))]] = players[1]['piece'] def input_validation(option_type, options, choice): global the_board if option_type == 'number_range': if not str.isdigit(choice): print('It has to be a number') return False else: choice = int(choice) if choice &lt; options[0] or choice &gt; options[1]: print('You have to choose a number between 0 and 8') return False elif (the_board[choice] == 'X' or the_board[choice] == 'O'): print('There is already a move there, please try again.') return False else: return True if option_type == 'string': for i in range(len(options)): if choice == options[i]: return True else: print('That is not a valid option, your choices are:') for i in range(len(options)): print(options[i]) else: print() return False def player_options(): valid = False global players while not valid: print('Do you want to play the cpu or player?') choice = input() choice = choice.lower() if input_validation('string', ['cpu', 'player'], choice): players[1]['type'] = choice break while not valid and players[1]['type'] == 'cpu': print('Do you want smart or dumb ai?:') choice = input() choice = choice.lower() if input_validation('string', ['smart', 'dumb'], choice): if choice == 'dumb': players[1]['level'] = choice break # while not valid: # print('Player 1, do you want to be X or O?:') # choice = input() # choice = choice.upper() # if input_validation('string', ['X', 'O'], choice): # if choice == 'O': # players[1]['piece'] = choice # break def game(): move = 0 turn = random.choice([True, False]) for i in range(9): the_board.insert(i, ' ') for i in range(9): valid = False print_board(the_board) if is_win(the_board, players[turn]['piece']): print_board(the_board) print('Player ' + players[turn]['piece'] + ' is the winner!') return turn ^= True if turn == 0 or (players[1]['type'] == 'player' and turn == 1): while not valid: move = (input('Turn for ' + players[turn]['piece'] + '. Move on which space?: ')) if input_validation('number_range', [0, 8], move): move = int(move) valid = True the_board[move] = players[turn]['piece'] elif players[1]['type'] == 'cpu' and turn == 1: ai() print_board(the_board) print('It is a tie!') def retry(): valid = False while not valid: print('Do you want to play again with the same settings? Y or N') choice = input() choice = choice.upper() if input_validation('string', ['Y', 'N'], choice): if choice == 'Y': game() else: player_options() game() player_options() game() retry() <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Let's upgrade it point-to-point and get a better code at the end:</p>\n\n<p><strong>0</strong>. I tried to run your program and found several bad user-side behaviors:</p>\n\n<p>U1. MANY unnecessary prints:</p>\n\n<pre><code>Do you want to play the cpu or player?\ncpu\nDo you want smart or dumb ai?:\nsmart\n | | 0|1|2\n-+-+- -+-+-\n | | 3|4|5\n-+-+- -+-+-\n | | 6|7|8\n\n | | 0|1|2\n-+-+- -+-+-\n |O| 3|4|5\n-+-+- -+-+-\n | | 6|7|8\n\nTurn for X. Move on which space?: 4\nThere is already a move there, please try again.\nTurn for X. Move on which space?: 5\n | | 0|1|2\n-+-+- -+-+-\n |O|X 3|4|5\n-+-+- -+-+-\n | | 6|7|8\n\nwin\nwin\nrandom\nwin\nwin\nwin\nwin\nwin\nwin\nwin\nwin\nwin\nwin\nwin\nwin\nother\nO| | 0|1|2\n-+-+- -+-+-\n |O|X 3|4|5\n-+-+- -+-+-\n | | 6|7|8\n\nTurn for X. Move on which space?:\n</code></pre>\n\n<p>Many of them are in <code>ai()</code> function:</p>\n\n<pre><code> for i in range(len(possible_moves)):\n board_copy = the_board.copy()\n board_copy[possible_moves[i]] = players[1]['piece']\n if check_board(possible_moves[i], 1):\n the_board[possible_moves[i]] = players[1]['piece']\n print('win')\n return\n elif check_board(possible_moves[i], 0):\n print('lose')\n final_move = possible_moves[i]\n elif players[1]['level'] == 'smart' and final_move is None:\n if possible_moves[i] in [0, 2, 6, 8]:\n print('random')\n final_move = possible_moves[i]\n</code></pre>\n\n<p>We will remove them. If you want, you can import <code>logging</code> module and log them to debug stream with <code>logging.debug(...)</code>.</p>\n\n<p>U2. You can't just manually quit the game. So let's modify <code>retry</code> function:</p>\n\n<pre><code>def retry():\n valid = False\n while not valid:\n print('Do you want to play again with the same settings? Y or N (Q to exit)')\n choice = input()\n choice = choice.upper()\n if input_validation('string', ['Y', 'N', 'Q'], choice):\n if choice == 'Y':\n game()\n elif choice == 'Q':\n return\n else:\n player_options()\n game()\n</code></pre>\n\n<p>U3. The game randomly crashes and doesn't react to winning positions.</p>\n\n<p>Look at your <code>is_win()</code> code:</p>\n\n<pre><code>def is_win(bo, player):\n # 0 1 2\n # 3 4 5\n # 6 7 8\n\n for i in range(3):\n return (\n</code></pre>\n\n<p><code>return</code> statement immediately exits from the function with a value you wrote to return. So this code will work only for <code>i == 0</code>. If you want to check everything and return if there is True anywhere, you should modify your code like this (and, please, use consistent variables! If you are using <code>board</code>, use it everywhere for boards. Don't use <code>board</code>, <code>bo</code> and smth like <code>b</code> in different places):</p>\n\n<pre><code>def is_win(board, player):\n # 0 1 2\n # 3 4 5\n # 6 7 8\n\n for i in range(3):\n if (\n (board[i * 3] == player and\n board[i * 3 + 1] == player and\n board[i * 3 + 2] == player)\n or\n (board[i] == player and\n board[i+3] == player and\n board[i+6] == player)\n or\n (i &lt;= 1 and\n (board[i*2] == player and\n board[4] == player and\n board[8-(i*2)] == player))\n ):\n return True\n return False\n</code></pre>\n\n<p>Now we are going to the code directly:</p>\n\n<ol>\n<li><p>Avoid global variables! In 99.99% you don't need them and can easily work without them. Global variables can (and often will) lead you to very hard-to-debug errors. We will eliminate global variables by creating <code>TicTac</code> class and converting all functions to class functions (very much code, you will see it later).</p></li>\n<li><p>DRY (Don't Repeat Yourself). Everywhere in your code you have variables like <code>players[1]['piece']</code> and <code>players[1]['level']</code>. You can create new short variable (especially because we created a class) and use it everywhere. If you will change your <code>player</code> structure (for 3rd player, for example), you will not have to change EVERYTHING in your code. We will replace them with <code>self.ai_level</code> and <code>self.ai_X</code></p></li>\n<li><p>In <code>ai()</code> function you have a line:</p></li>\n</ol>\n\n<p><code>self.the_board[possible_moves[random.randint(0, len(possible_moves))]] = self.ai_X</code></p>\n\n<p><code>random.randint</code> can return bounds (e.g. <code>random.randint(0, 5)</code> can return both 0 or 5) so this line sometimes raises an error (when you are trying to get the last element of <code>random.randint</code>). You can define right bound as <code>len(possible_moves) - 1</code> or you can just use <code>random.choice</code>:</p>\n\n<p><code>self.the_board[random.choice(possible_moves)] = self.ai_X</code></p>\n\n<ol start=\"4\">\n<li>Some small improvements like:</li>\n</ol>\n\n<pre><code>for i in range(9):\n self.the_board.insert(i, ' ')\n</code></pre>\n\n<p>to</p>\n\n<p><code>self.the_board = [' '] * 9</code></p>\n\n<p>and like it.</p>\n\n<p>So we have a final code. Honestly, it is better to re-write the whole game from scratch but you will realize it only some years later :) This code still not ideal and has many places to improve but it is better than it was.</p>\n\n<pre><code>import random\n\nclass TicTac(object):\n def __init__(self):\n self.the_board = [' '] * 9\n self.players = [\n {'type': 'player', 'piece': 'X'},\n {'type': 'player', 'level': 'smart', 'piece': 'O'}\n ]\n self.ai_level = None\n self.ai_X = None\n\n def print_board(self, board):\n for i in range(3):\n print(board[i * 3] + '|' + board[i * 3 + 1] + '|' + board[i * 3 + 2], end='')\n print(' ' + str(i * 3) + '|' + str(i * 3 + 1) + '|' + str(i * 3 + 2))\n if i &lt; 2:\n print('-+-+-' + ' ' + '-+-+-')\n print()\n\n def is_win(self, board, player):\n # 0 1 2\n # 3 4 5\n # 6 7 8\n\n for i in range(3):\n if (\n (board[i * 3] == player and\n board[i * 3 + 1] == player and\n board[i * 3 + 2] == player)\n or\n (board[i] == player and\n board[i+3] == player and\n board[i+6] == player)\n or\n (i &lt;= 1 and\n (board[i*2] == player and\n board[4] == player and\n board[8-(i*2)] == player))\n ):\n return True\n return False\n\n def check_board(self, move, player):\n board_copy = self.the_board.copy()\n board_copy[move] = self.players[player]['piece']\n return self.is_win(board_copy, self.players[player]['piece'])\n\n def ai(self):\n possible_moves = []\n final_move = None\n\n for i in range(9):\n if self.the_board[i] == ' ':\n possible_moves.append(i)\n\n if self.the_board[4] == ' ' and self.ai_level == 'smart':\n self.the_board[4] = self.ai_X\n return\n\n for i in range(len(possible_moves)):\n board_copy = the_board.copy()\n board_copy[possible_moves[i]] = self.ai_X\n if self.check_board(possible_moves[i], 1):\n self.the_board[possible_moves[i]] = self.ai_X\n return\n elif self.check_board(possible_moves[i], 0):\n final_move = possible_moves[i]\n elif self.ai_level == 'smart' and final_move is None:\n if possible_moves[i] in [0, 2, 6, 8]:\n final_move = possible_moves[i]\n else:\n if final_move is not None:\n self.the_board[final_move] = self.ai_X\n return\n self.the_board[random.choice(possible_moves)] = self.ai_X\n\n def input_validation(self, option_type, options, choice):\n if option_type == 'number_range':\n if not str.isdigit(choice):\n print('It has to be a number')\n return False\n else:\n choice = int(choice)\n if choice &lt; options[0] or choice &gt; options[1]:\n print('You have to choose a number between 0 and 8')\n return False\n elif (self.the_board[choice] == 'X' or self.the_board[choice] == 'O'):\n print('There is already a move there, please try again.')\n return False\n else:\n return True\n\n if option_type == 'string':\n for i in range(len(options)):\n if choice == options[i]:\n return True\n else:\n print('That is not a valid option, your choices are:')\n for i in range(len(options)):\n print(options[i])\n else:\n print()\n return False\n\n def player_options(self):\n valid = False\n\n while not valid:\n print('Do you want to play the cpu or player?')\n choice = input()\n choice = choice.lower()\n if self.input_validation('string', ['cpu', 'player'], choice):\n self.players[1]['type'] = choice\n break\n\n while not valid and self.players[1]['type'] == 'cpu':\n self.ai_X = self.players[1]['piece']\n print('Do you want smart or dumb ai?:')\n choice = input()\n choice = choice.lower()\n if self.input_validation('string', ['smart', 'dumb'], choice):\n if choice == 'dumb':\n self.players[1]['level'] = choice\n self.ai_level = choice\n break\n\n def game(self):\n move = 0\n turn = random.choice([True, False])\n\n for i in range(9):\n valid = False\n\n self.print_board(self.the_board)\n if is_win(self.the_board, self.players[0]['piece']) or \\\n is_win(self.the_board, self.players[1]['piece']):\n self.print_board(self.the_board)\n print('Player ' + self.players[turn]['piece'] + ' is the winner!')\n return\n\n turn ^= True\n\n if turn == 0 or (self.players[1]['type'] == 'player' and turn == 1):\n while not valid:\n move = (input('Turn for ' + self.players[turn]['piece'] + '. Move on which space?: '))\n if self.input_validation('number_range', [0, 8], move):\n move = int(move)\n valid = True\n self.the_board[move] = self.players[turn]['piece']\n elif self.players[1]['type'] == 'cpu' and turn == 1:\n self.ai()\n print('It is a tie!')\n\n def retry(self):\n valid = False\n while not valid:\n print('Do you want to play again with the same settings? Y or N (Q to exit)')\n choice = input()\n choice = choice.upper()\n if input_validation('string', ['Y', 'N', 'Q'], choice):\n if choice == 'Y':\n self.game()\n elif choice == 'Q':\n return\n else:\n self.player_options()\n self.game()\n\ngame = TicTac()\ngame.player_options()\ngame.game()\ngame.retry()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:35:50.770", "Id": "220642", "ParentId": "220488", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T21:15:14.110", "Id": "220488", "Score": "2", "Tags": [ "python", "beginner", "tic-tac-toe" ], "Title": "First proper program, Tic Tac Toe" }
220488
<p>There a various examples in UIKit where a class has a property and a corresponding method to set the property along with an <code>animated</code> property.</p> <p>Examples include the <code>progress</code> and <code>setProgress(_:animated:)</code> of <code>UIProgressView</code> or the <code>isEditing</code> and <code>setEditing(_:animated:)</code> of <code>UITableView</code>.</p> <p>In Objective-C you implement this by overriding the plain property setter to call the additional setter with the additional parameter:</p> <pre><code>- (void)setEditing:(BOOL)editing { [self setEditing:editing animated:NO]; } - (void)setEditing:(BOOL)editing animated:(BOOL)animated { _editing = editing // set the instance variable // The rest of the code } </code></pre> <p>The question is about doing this in Swift. The best I can come up requires using a private backing variable for the public computed property in addition to the corresponding animated setter.</p> <pre><code>private var _editing: Bool public var isEditing: Bool { get { return _editing } set { setEditing(newValue, animated: false) } } public func setEditing(_ editing: Bool, animated: Bool) { _editing = editing // The rest of the code } </code></pre> <p>Is there a better way to implement this pattern in Swift without the need to wrap a private property with a computed property à la Objective-C?</p>
[]
[ { "body": "<p>The alternative is: </p>\n\n<pre><code>public var isEditing: Bool {\n didSet {\n // do whatever you need when the property changes, e.g.\n updateView()\n }\n}\n\n// wrap the changing of `isEditing` in some animation\n\nfunc setEditing(_ editing: Bool, animated: Bool) {\n if animated {\n someAnimation {\n isEditing = editing\n }\n } else {\n isEditing = editing\n }\n}\n</code></pre>\n\n<p>This basically separates the “do what I need when <code>isEditing</code> changes” from the “by the way, animate that” and it eliminates a private backing stored property.</p>\n\n<p>There are cases where you need to do the “exposed computed property with a private backing stored property” approach, but I generally avoid that pattern where I can.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T19:58:13.047", "Id": "426373", "Score": "0", "body": "This is a nice approach for simple view changes and simple animations. I have a case where I'm implementing a custom view wrapping a collection view. My little animatable property does some complicated updates to the collection view's layout, toggles some cell selections, adjusts the content offset, etc. The `animated` property is passed to many of the collection view methods at each step. I do not believe my specific use can be neatly adjusted to this suggested answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T20:28:41.250", "Id": "426376", "Score": "0", "body": "If that’s what’s actually going on in your situation, then your approach is perfectly good, IMHO. The above is for those simpler scenarios." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T19:38:45.570", "Id": "220671", "ParentId": "220489", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T21:19:28.397", "Id": "220489", "Score": "3", "Tags": [ "swift" ], "Title": "Implementation of a property and a corresponding animated setter" }
220489
<p>In this <a href="https://leetcode.com/problems/longest-palindromic-substring/" rel="nofollow noreferrer">LeetCode problem</a>, Longest Palindromic Substring, it is listed under Dynamic Programming for Google interview preparation. My understanding of dynamic programming is roughly "recursion + memoization + guessing." In the Python solution to this answer below it is not clear to me where the dynamic programming is if it exists at all. This is <a href="https://leetcode.com/problems/longest-palindromic-substring/solution/" rel="nofollow noreferrer">Approach 4</a> under solutions (translated from Java to Python). Approach 3 references dynamic programming but no solution is given. </p> <p>Is there any dynamic programming going on here? Or is this just a solution to solve the problem in O(1) space, where the dynamic programming solution requires O(n^2) space? </p> <p>This algorithm technically has a time complexity of O(n^2) right? Is this the best we could reasonably be expected to do in an interview?</p> <pre><code>class Solution: def longestPalindrome(self, s): res = "" for i in range(len(s)): # odd case, like "aba" tmp = self.helper(s, i, i) if len(tmp) &gt; len(res): res = tmp # even case, like "abba" tmp = self.helper(s, i, i+1) if len(tmp) &gt; len(res): res = tmp return res # get the longest palindrome, l, r are the middle indexes # from inner to outer def helper(self, s, l, r): while l &gt;= 0 and r &lt; len(s) and s[l] == s[r]: l -= 1; r += 1 return s[l+1:r] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T16:29:46.023", "Id": "426203", "Score": "0", "body": "Which website should this be included on?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-30T17:15:31.170", "Id": "470140", "Score": "0", "body": "I suggest [cs.SE](https://cs.stackexchange.com/search?q=lps)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T21:23:15.003", "Id": "220490", "Score": "3", "Tags": [ "python", "interview-questions", "palindrome", "dynamic-programming" ], "Title": "Longest Palindrome Substring: Where is the dynamic programming?" }
220490
<p>Please feel free to review my countdown numbers game solver. Posted here too for people working on the same problem. For clarity the print statement "Eval..." means the program has used BODMAS on an entire mathematical statement (e.g: 1*3+10 = 31)</p> <p>"Running total" means the program recalculates the total after each move (e.g: 1*3+10 = 13 because 1*3 = 3, 3+10 = 13)</p> <pre><code>import re def unpack(method): string = method special = ["*","+","-","/"] list_sum = [] list_special = [] numbers = (re.findall(r"[\w']+", string)) for char in string: if char in special: list_special.append(char) for index in range (len(numbers)-1): to_eval = numbers[index] + list_special[index] + numbers[index+1] list_sum.append(f'{to_eval} = {eval(to_eval)}') numbers[index+1] = str(eval(to_eval)) return list_sum def evaluate (method,running_sum): global clear_status if eval(method) == target: if method not in list_methods: list_methods.append(method) print (f'Eval: {method}') clear_status = True return True if running_sum == target: if method not in list_methods: list_methods.append(method) print (f'Running sum: {unpack(method)}') clear_status = True return True clear_status = False return False def new_total (total,item,operation): if operation == "+": return total + item if operation == "-": return total - item if operation == "*": return total * item if operation == "/" and item != 0: return total / item return "" def solve (array,total=0,method="",list_method=[]): if len(array) == 0: return for (index,item) in enumerate(array): #Set methods and totals to "": add_method, sub_method, mul_method, div_method = "", "", "", "" add_total, sub_total, mul_total, div_total = 0, 0, 0,0 #Assign methods and totals to a list: methods = [add_method, sub_method, mul_method, div_method] totals = [add_total, sub_total, mul_total, div_total] str_func = ["+", "-", "*", "/"] #Create new array remaining = array[:index] + array[index+1:] #Sets new totals and new "methods" for index_1 in range (len(methods)): if method =="": if str_func[index_1] != "/" and str_func[index_1] != "*" and str_func[index_1] != "-": methods[index_1] = str(array[index]) totals[index_1] = new_total(total, item, str_func[index_1]) else: methods[index_1] = method + str_func[index_1] + str(array[index]) totals[index_1] = new_total(total, item, str_func[index_1]) #Evaluates each total and method for index_2 in range (len(methods)): try: if evaluate(methods[index_2], totals[index_2]): if clear_status == True: methods[index_2]="" totals[index_2]=0 return except Exception as e: pass #Recursively calculates next move for index_3 in range (len(methods)): try: solve(remaining, total= totals[index_3],method= methods[index_3]) except Exception as e: pass str_array = input("Please enter the starting numbers, separated by commas: ") array = array=[int(item.strip()) for item in str_array.split(",")] target = int(input("Please enter a target value: ")) print (f'Solutions for {array} to reach {target}') list_methods = [] solve(array) if list_methods == []: print ("Unsolvable countdown problem") to_close = input("Press any key to exit...") </code></pre>
[]
[ { "body": "<ul>\n<li><strong>Docstrings</strong>: You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every method/class/module you write. This will help any documentation indentify what your code is supposed to do.</li>\n<li><strong>solve()</strong>: My biggest problem with this method was the beginning. You create eight different variables for your methods and total, then put them into a list. Instead of having these eight one time use variables, just set the default values inside the list. Since you don't work with any of the eight variables after putting them into the list, they are obsolete, so can be removed.</li>\n<li><strong>Variable/Parameter/Method Spacing</strong>: There shouldn't be spaces between the method name and the opening parentheses.</li>\n<li><strong>Parameter Reassignment</strong>: In <code>unpack</code> you have a passed parameter <code>method</code>. You then reassign that parameter to a variable <code>string</code>. This is very unnecessary. You have simply have the parameter <code>string</code>, so you're working directly with what is passed, instead of taking the time and trouble to reassign to a variable.</li>\n<li><strong>Use of <code>global</code></strong>: It's not recommended to use <code>global</code> variables in python, or any language. <a href=\"https://stackoverflow.com/a/19158418/8968906\">This StackOverflow answer</a> provides more insight.</li>\n<li><strong>Boolean Comparison</strong>: Instead of checking <code>if variable == True</code>, you can simply check the variable itself, like so: <code>if variable:</code>.</li>\n<li><strong>Unused Exceptions (<code>as e</code>)</strong>: If you don't intend to work with an exception that you catch, it is unnecessary to have the extra code <code>as e</code>, since that will be a variable you never use. You can simply remove that code.</li>\n<li><strong>Unused Parameters</strong>: In <code>solve</code>, you never use the <code>list_method=[]</code> that is passed. You should remove any parameters you don't use, you risk adding complexity and reducing readability.</li>\n<li><strong>Constants Naming</strong>: Any constants in your code should be UPPERCASE, so make it clear to anyone reading your code, including yourself, that they are constant variables.</li>\n<li><strong><code>in list</code> vs <code>in [...]</code></strong>: You create a list of operators for the sole purpose of checking if an operator is in that list of operators. This is unnecessary. You can simplify your code by creating an anonymous list to check containment. This reduces the amount of variables in your code, increasing readability and reducing complexity.</li>\n<li><strong>if name == main guard</strong>: Any code that isn't contained in a method or class should be contained in a <a href=\"https://stackoverflow.com/a/419185/8968906\"><code>if __name__ == '__main__'</code></a> guard. This will prevent any of that code from being executed if you decide to import the file, for other uses.</li>\n<li><strong><code>_</code> for unused variables</strong>: Your last line of code is a variable that allows the user to exit when they want, by pressing any key. You create a variable for this purpose alone. Since you never use this variable, and it's only used to exit the program, you can use a <a href=\"https://hackernoon.com/understanding-the-underscore-of-python-309d1a029edc\" rel=\"nofollow noreferrer\"><code>_</code></a>, to make it clear that that variable is to be, essentially, ignored.</li>\n</ul>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring:\nExplanation of your code goes here\n\"\"\"\n\nimport re\n\ndef unpack(string):\n \"\"\" Unpacks the passed `string` \"\"\"\n list_sum = []\n list_special = []\n numbers = (re.findall(r\"[\\w']+\", string))\n for char in string:\n if char in [\"*\", \"+\", \"-\", \"/\"]:\n list_special.append(char)\n\n for index in range(len(numbers) - 1):\n to_eval = numbers[index] + list_special[index] + numbers[index + 1]\n list_sum.append(f'{to_eval} = {eval(to_eval)}')\n numbers[index + 1] = str(eval(to_eval))\n\n return list_sum\n\ndef evaluate(method, running_sum):\n \"\"\" Evaluates the passed `method` \"\"\"\n if eval(method) == TARGET:\n if method not in LIST_METHODS:\n LIST_METHODS.append(method)\n print(f'Eval: {method}')\n clear_status = True\n return True\n if running_sum == TARGET:\n if method not in LIST_METHODS:\n LIST_METHODS.append(method)\n print(f'Running sum: {unpack(method)}')\n clear_status = True\n return True\n clear_status = False\n return False\n\ndef new_total(total, item, operation):\n \"\"\" Determines the operator and returns the new total \"\"\"\n if operation == \"+\":\n return total + item\n if operation == \"-\":\n return total - item\n if operation == \"*\":\n return total * item\n if operation == \"/\" and item != 0:\n return total / item\n return \"\"\n\ndef solve(array, total=0, method=\"\"):\n \"\"\" Solves the passed numbers and target \"\"\"\n if not array:\n return\n\n for index, item in enumerate(array):\n\n #Assign methods and totals to a list:\n methods = [\"\", \"\", \"\", \"\"]\n totals = [0, 0, 0, 0]\n str_func = [\"+\", \"-\", \"*\", \"/\"]\n\n #Create new array\n remaining = array[:index] + array[index+1:]\n\n #Sets new totals and new \"methods\"\n for index_1 in range(len(methods)):\n if method == \"\":\n if str_func[index_1] != \"/\" and str_func[index_1] != \"*\" and str_func[index_1] != \"-\":\n methods[index_1] = str(array[index])\n totals[index_1] = new_total(total, item, str_func[index_1])\n else:\n methods[index_1] = method + str_func[index_1] + str(array[index])\n totals[index_1] = new_total(total, item, str_func[index_1])\n\n #Evaluates each total and method\n for index_2, value_2 in enumerate(methods):\n try:\n if evaluate(value_2, totals[index_2]):\n if clear_status:\n methods[index_2] = \"\"\n totals[index_2] = 0\n return\n except Exception:\n pass\n\n #Recursively calculates next move\n for index_3, value_3 in enumerate(methods):\n try:\n solve(remaining, total=totals[index_3], method=value_3)\n except Exception:\n pass\n\nif __name__ == '__main__':\n clear_status = None\n STR_ARRAY = input(\"Please enter the starting numbers, separated by commas: \")\n ARRAY = ARRAY = [int(item.strip()) for item in STR_ARRAY.split(\",\")]\n TARGET = int(input(\"Please enter a target value: \"))\n print(f'Solutions for {ARRAY} to reach {TARGET}')\n LIST_METHODS = []\n solve(ARRAY)\n if LIST_METHODS == []:\n print(\"Unsolvable countdown problem\")\n _ = input(\"Press any key to exit...\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T03:46:28.013", "Id": "225500", "ParentId": "220492", "Score": "3" } } ]
{ "AcceptedAnswerId": "225500", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T23:00:15.317", "Id": "220492", "Score": "3", "Tags": [ "python" ], "Title": "A countdown numbers game solver" }
220492
<p>This question is the follow-up to <a href="https://codereview.stackexchange.com/questions/220167/population-dynamic-simulation-on-biological-information-maintenance">this previous question</a>.</p> <h2>Background</h2> <blockquote> <p>Using this simulation I investigate a system in which enzymes proliferate in cells. During the replications of enzymes, parasites can come to be due to mutation. They can drive the system into extinction. I'm interested in where in the parameter space coexistence is possible.</p> </blockquote> <p>I have made the <a href="https://codereview.stackexchange.com/a/220177/200600">changes advised by HoboProber</a>. Namely correction of style and implementing the model relying on Numpy. So now the system is a 2-dimensional array. Cells are the columns of the array. The values of the first row are the numbers of enzymes and the values of the second row are the numbers of parasites.</p> <h2>My request</h2> <p>The speed of this newer implementation is much better than that of the previous one. But as I would like to increase <code>population_size</code> and <code>gen_max</code> every bit of performance improvement counts.</p> <p>So far I examined the system in more detail with population sizes ranging from 100 to 1000 cells and with the maximal number of generations being 10000. The amount of increase in population size depends on performance, a million cells would be a perfectly reasonable assumption concerning the modelled system. The maximal number of generations should be 20-30000.</p> <ul> <li>Primarily, does the code make use of vectorization and Numpy as effectively as it can?</li> <li>Which potential efficiency improvements I missed? For example calculating something multiple times instead of assigning it to a variable or making (explicit and/or implicit) array copies unnecessarily many times.</li> <li>Is there a better way performance-wise to write data to file?</li> </ul> <h2>The code</h2> <pre class="lang-py prettyprint-override"><code>""" Collect data on an enzyme-parasite system explicitly assuming compartmentalization. Functions --------- simulation() Simulate mentioned system. write_out_file() Write data to csv output file. """ import csv import time import numpy as np def simulation(population_size, cell_size, replication_rate_p, mutation_rate, gen_max): """ Simulate an enzyme-parasite system explicitly assuming compartmentalization. Parameters ---------- population_size : int The number of cells. cell_size : int The maximal number of replicators of cells at which cell division takes place. replication_rate_p : float The fitness (replication rate) of the parasites relative to the fitness (replication rate) of the enzymes. Example ------- $ replication_rate_p = 2 This means that the parasites' fitness is twice as that of the enzymes. mutation_rate : float The probability of mutation during a replication event. gen_max : int The maximal number of generations. A generation corresponds to one outer while cycle. If the system extincts, the number of generations doesn't reach gen_max. Yield ------- generator object Contains data on the simulated system. """ def population_stats(population): """ Calculate statistics of the system. Parameter --------- population : ndarray The system itself. Return ------- tuple Contains statistics of the simulated system. """ gyak_sums = population.sum(axis=1) gyak_means = population.mean(axis=1) gyak_variances = population.var(axis=1) gyak_percentiles_25 = np.percentile(population, 25, axis=1) gyak_medians = np.median(population, axis=1) gyak_percentiles_75 = np.percentile(population, 75, axis=1) fitness_list = population[0, :]/population.sum(axis=0) return ( gyak_sums[0], gyak_sums[1], (population[0, :] &gt; 1).sum(), gyak_means[0], gyak_variances[0], gyak_percentiles_25[0], gyak_medians[0], gyak_percentiles_75[0], gyak_means[1], gyak_variances[1], gyak_percentiles_25[1], gyak_medians[1], gyak_percentiles_75[1], fitness_list.mean(), fitness_list.var(), np.percentile(fitness_list, 25), np.median(fitness_list), np.percentile(fitness_list, 75) ) # Creating the system with the starting state being # half full cells containing only enzymes. population = np.zeros((2, population_size), dtype=np.int32) population[0, :] = cell_size//2 gen = 0 yield (gen, *population_stats(population), population_size, cell_size, mutation_rate, replication_rate_p, "aft") print(f"N = {population_size}, rMax = {cell_size}, " f"aP = {replication_rate_p}, U = {mutation_rate}", file=DEAD_OR_ALIVE) while (population.size &gt; 0) &amp; (gen &lt; gen_max): gen += 1 # Replicator proliferation until cell_size in each cell. mask = (population.sum(axis=0) &lt; cell_size).nonzero() while mask[0].size &gt; 0: # Calculating probabilites of choosing a parasite to replication. repl_probs_p = population[:, mask].copy() repl_probs_p.view(np.float32)[1, :] *= replication_rate_p repl_probs_p = repl_probs_p[1, :]/repl_probs_p.sum(axis=0) # Determining if an enzyme or a parasite replicates, # and if an enzyme replicates, will it mutate to a parasite. # (Outcome can differ among cells. Parasites don't mutate.) repl_choices = np.random.random_sample(repl_probs_p.shape) mut_choices = np.random.random_sample(repl_probs_p.shape) lucky_replicators = np.zeros(repl_probs_p.shape, dtype=np.int32) lucky_replicators[ (repl_choices &lt; repl_probs_p) | (mut_choices &lt; mutation_rate) ] = 1 population[lucky_replicators, mask] += 1 mask = (population.sum(axis=0) &lt; cell_size).nonzero() if gen % 100 == 0: yield (gen, *population_stats(population), population_size, cell_size, mutation_rate, replication_rate_p, "bef") # Each cell divides. new_population = np.random.binomial(population, 0.5) population -= new_population # Discarding dead cells. population = np.concatenate((population[:, (population[0, :] &gt; 1).nonzero()[0]], new_population[:, (new_population[0, :] &gt; 1).nonzero()[0]]), axis=1) # Choosing survivor cells according to their fitnesses # if there are more viable cells than population_size. # Hence population_size or less cells move on to the next generation. if population.shape[1] &gt; population_size: fitness_list = population[0, :]/population.sum(axis=0) fitness_list = fitness_list/fitness_list.sum() population = population[:, np.random.choice(population.shape[1], population_size, replace=False, p=fitness_list)] elif population.size == 0: for i in range(2): yield (gen+i, *(0, 0)*9, population_size, cell_size, mutation_rate, replication_rate_p, "aft") print(f"{gen} generations are done.") print("Cells are extinct.", file=DEAD_OR_ALIVE) if (gen % 100 == 0) &amp; (population.size &gt; 0): yield (gen, *population_stats(population), population_size, cell_size, mutation_rate, replication_rate_p, "aft") if (gen % 1000 == 0) &amp; (population.size &gt; 0): print(f"{gen} generations are done.") print("Simulation ended successfully.\n", file=DEAD_OR_ALIVE) def write_out_file(result, local_time, n_run): """ Write data to csv output file. Parameters ---------- result : list of generator object(s) Contains data on the simulated system. n_run : int The number of consecutive runs. """ with open("output_data_" + local_time + ".csv", "w", newline="") as out_file: out_file.write( "gen;" "eSzamSum;pSzamSum;alive;" "eSzamAtl;eSzamVar;eSzamAKv;eSzamMed;eSzamFKv;" "pSzamAtl;pSzamVar;pSzamAKv;pSzamMed;pSzamFKv;" "fitAtl;fitVar;fitAKv;fitMed;fitFKv;" "N;rMax;U;aP;boaSplit\n" ) out_file = csv.writer(out_file, delimiter=";") counter = 0 for i in result: out_file.writerows(i) counter += 1 print(counter, "/", n_run, "\n") LOCAL_TIME = time.strftime("%m_%d_%H_%M_%S_%Y", time.localtime(time.time())) DEAD_OR_ALIVE = open("output_data_" + LOCAL_TIME + ".txt", "w") RESULT = [simulation(1000, 200, 1.5, 0.0, 10000)] #RESULT.append(simulation(1000, 200, 1.5, 1.0, 10000)) N_RUN = 1 write_out_file(RESULT, LOCAL_TIME, N_RUN) DEAD_OR_ALIVE.close() # Normally I call the functions from another script, # these last 4 lines are meant to be just an example. </code></pre> <h3>line_profiling</h3> <pre class="lang-none prettyprint-override"><code>Timer unit: 1e-07 s Total time: 161.05 s File: simulation.py Function: simulation at line 16 Line # Hits Time Per Hit % Time Line Contents ============================================================== 16 17 def simulation(population_size, cell_size, replication_rate_p, mutation_rate, gen_max): 18 """ 19 Simulate an enzyme-parasite system explicitly assuming compartmentalization. 20 21 Parameters 22 ---------- 23 population_size : int 24 The number of cells. 25 26 cell_size : int 27 The maximal number of replicators of cells at which cell division takes place. 28 29 replication_rate_p : float 30 The fitness (replication rate) of the parasites 31 relative to the fitness (replication rate) of the enzymes. 32 Example 33 ------- 34 $ replication_rate_p = 2 35 This means that the parasites' fitness is twice as that of the enzymes. 36 37 mutation_rate : float 38 The probability of mutation during a replication event. 39 40 gen_max : int 41 The maximal number of generations. 42 A generation corresponds to one outer while cycle. 43 If the system extincts, the number of generations doesn't reach gen_max. 44 45 Yield 46 ------- 47 generator object 48 Contains data on the simulated system. 49 """ 50 51 1 56.0 56.0 0.0 def population_stats(population): 52 """ 53 Calculate statistics of the system. 54 55 Parameter 56 --------- 57 population : ndarray 58 The system itself. 59 60 Return 61 ------- 62 tuple 63 Contains statistics of the simulated system. 64 """ 65 gyak_sums = population.sum(axis=1) 66 gyak_means = population.mean(axis=1) 67 gyak_variances = population.var(axis=1) 68 gyak_percentiles_25 = np.percentile(population, 25, axis=1) 69 gyak_medians = np.median(population, axis=1) 70 gyak_percentiles_75 = np.percentile(population, 75, axis=1) 71 fitness_list = population[0, :]/population.sum(axis=0) 72 return ( 73 gyak_sums[0], gyak_sums[1], (population[0, :] &gt; 1).sum(), 74 gyak_means[0], gyak_variances[0], 75 gyak_percentiles_25[0], gyak_medians[0], gyak_percentiles_75[0], 76 gyak_means[1], gyak_variances[1], 77 gyak_percentiles_25[1], gyak_medians[1], gyak_percentiles_75[1], 78 fitness_list.mean(), fitness_list.var(), 79 np.percentile(fitness_list, 25), 80 np.median(fitness_list), 81 np.percentile(fitness_list, 75) 82 ) 83 84 # Creating the system with the starting state being 85 # half full cells containing only enzymes. 86 1 68.0 68.0 0.0 population = np.zeros((2, population_size), dtype=np.int32) 87 1 53.0 53.0 0.0 population[0, :] = cell_size//2 88 1 9.0 9.0 0.0 gen = 0 89 1 14828.0 14828.0 0.0 yield (gen, *population_stats(population), population_size, 90 1 24.0 24.0 0.0 cell_size, mutation_rate, replication_rate_p, "aft") 91 1 49.0 49.0 0.0 print(f"N = {population_size}, rMax = {cell_size}, " 92 f"aP = {replication_rate_p}, U = {mutation_rate}", 93 1 113.0 113.0 0.0 file=DEAD_OR_ALIVE) 94 95 10001 140323.0 14.0 0.0 while (population.size &gt; 0) &amp; (gen &lt; gen_max): 96 10000 123102.0 12.3 0.0 gen += 1 97 98 # Replicator proliferation until cell_size in each cell. 99 10000 3333616.0 333.4 0.2 mask = (population.sum(axis=0) &lt; cell_size).nonzero() 100 1238245 20308315.0 16.4 1.3 while mask[0].size &gt; 0: 101 # Calculating probabilites of choosing a parasite to replication. 102 1228245 239761224.0 195.2 14.9 repl_probs_p = population[:, mask].copy() 103 1228245 83589799.0 68.1 5.2 repl_probs_p.view(np.float32)[1, :] *= replication_rate_p 104 1228245 158300271.0 128.9 9.8 repl_probs_p = repl_probs_p[1, :]/repl_probs_p.sum(axis=0) 105 # Determining if an enzyme or a parasite replicates, 106 # and if an enzyme replicates, will it mutate to a parasite. 107 # (Outcome can differ among cells. Parasites don't mutate.) 108 1228245 132808465.0 108.1 8.2 repl_choices = np.random.random_sample(repl_probs_p.shape) 109 1228245 117430558.0 95.6 7.3 mut_choices = np.random.random_sample(repl_probs_p.shape) 110 1228245 35120008.0 28.6 2.2 lucky_replicators = np.zeros(repl_probs_p.shape, dtype=np.int32) 111 lucky_replicators[ 112 (repl_choices &lt; repl_probs_p) | (mut_choices &lt; mutation_rate) 113 1228245 76236137.0 62.1 4.7 ] = 1 114 1228245 301823109.0 245.7 18.7 population[lucky_replicators, mask] += 1 115 1228245 357660422.0 291.2 22.2 mask = (population.sum(axis=0) &lt; cell_size).nonzero() 116 117 10000 143547.0 14.4 0.0 if gen % 100 == 0: 118 100 1350075.0 13500.8 0.1 yield (gen, *population_stats(population), population_size, 119 100 2544.0 25.4 0.0 cell_size, mutation_rate, replication_rate_p, "bef") 120 121 # Each cell divides. 122 10000 17525435.0 1752.5 1.1 new_population = np.random.binomial(population, 0.5) 123 10000 1087713.0 108.8 0.1 population -= new_population 124 125 # Discarding dead cells. 126 10000 2526633.0 252.7 0.2 population = np.concatenate((population[:, (population[0, :] &gt; 1).nonzero()[0]], 127 10000 1979199.0 197.9 0.1 new_population[:, (new_population[0, :] &gt; 1).nonzero()[0]]), 128 10000 1003433.0 100.3 0.1 axis=1) 129 130 # Choosing survivor cells according to their fitnesses 131 # if there are more viable cells than population_size. 132 # Hence population_size or less cells move on to the next generation. 133 10000 184360.0 18.4 0.0 if population.shape[1] &gt; population_size: 134 10000 5107803.0 510.8 0.3 fitness_list = population[0, :]/population.sum(axis=0) 135 10000 1244299.0 124.4 0.1 fitness_list = fitness_list/fitness_list.sum() 136 10000 213078.0 21.3 0.0 population = population[:, np.random.choice(population.shape[1], 137 10000 110896.0 11.1 0.0 population_size, 138 10000 111486.0 11.1 0.0 replace=False, 139 10000 49497963.0 4949.8 3.1 p=fitness_list)] 140 elif population.size == 0: 141 for i in range(2): 142 yield (gen+i, *(0, 0)*9, population_size, 143 cell_size, mutation_rate, replication_rate_p, "aft") 144 print(f"{gen} generations are done.") 145 print("Cells are extinct.", file=DEAD_OR_ALIVE) 146 147 10000 260742.0 26.1 0.0 if (gen % 100 == 0) &amp; (population.size &gt; 0): 148 100 1332898.0 13329.0 0.1 yield (gen, *population_stats(population), population_size, 149 100 2553.0 25.5 0.0 cell_size, mutation_rate, replication_rate_p, "aft") 150 151 10000 147525.0 14.8 0.0 if (gen % 1000 == 0) &amp; (population.size &gt; 0): 152 10 21265.0 2126.5 0.0 print(f"{gen} generations are done.") 153 154 1 226.0 226.0 0.0 print("Simulation ended successfully.\n", file=DEAD_OR_ALIVE) </code></pre> <h3>cProfiling sample</h3> <pre class="lang-none prettyprint-override"><code>Fri Nov 29 04:53:01 2019 cprofiling 16375164 function calls (16361694 primitive calls) in 135.937 seconds Ordered by: internal time, cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 202 72.331 0.358 135.766 0.672 simulation.py:17(simulation) 2529183 27.246 0.000 27.246 0.000 {method 'reduce' of 'numpy.ufunc' objects} 2456168 20.346 0.000 20.346 0.000 {method 'random_sample' of 'numpy.random.mtrand.RandomState' objects} 10000 2.575 0.000 4.456 0.000 {method 'choice' of 'numpy.random.mtrand.RandomState' objects} 1258084 2.326 0.000 2.326 0.000 {method 'nonzero' of 'numpy.ndarray' objects} 1228747 2.139 0.000 2.139 0.000 {method 'copy' of 'numpy.ndarray' objects} 2486771 2.043 0.000 29.905 0.000 {method 'sum' of 'numpy.ndarray' objects} 1228085 1.420 0.000 1.420 0.000 {built-in method numpy.zeros} 10000 1.354 0.000 1.683 0.000 {method 'binomial' of 'numpy.random.mtrand.RandomState' objects} 1228088/1228087 0.899 0.000 0.899 0.000 {method 'view' of 'numpy.ndarray' objects} 2486771 0.783 0.000 27.862 0.000 _methods.py:36(_sum) 31404 0.585 0.000 0.585 0.000 {method 'argsort' of 'numpy.ndarray' objects} 31404 0.413 0.000 1.081 0.000 arraysetops.py:297(_unique1d) 31404 0.262 0.000 0.262 0.000 {method 'cumsum' of 'numpy.ndarray' objects} 134267/124016 0.162 0.000 2.224 0.000 {built-in method numpy.core._multiarray_umath.implement_array_function} 40804 0.103 0.000 0.334 0.000 fromnumeric.py:73(_wrapreduction) 31404 0.064 0.000 1.193 0.000 arraysetops.py:151(unique) 32007 0.039 0.000 0.039 0.000 {method 'flatten' of 'numpy.ndarray' objects} 31404 0.034 0.000 0.329 0.000 fromnumeric.py:2358(cumsum) 20000 0.032 0.000 0.092 0.000 {method 'all' of 'numpy.generic' objects} 31405 0.031 0.000 0.031 0.000 {built-in method numpy.empty} 804 0.027 0.000 0.111 0.000 function_base.py:3853(_quantile_ureduce_func) 31404 0.027 0.000 0.382 0.000 &lt;__array_function__ internals&gt;:2(cumsum) 31404 0.027 0.000 1.256 0.000 &lt;__array_function__ internals&gt;:2(unique) 68944 0.027 0.000 0.027 0.000 {built-in method numpy.array} 667 0.025 0.000 0.025 0.000 {built-in method nt.stat} 33012 0.025 0.000 0.303 0.000 fromnumeric.py:55(_wrapfunc) 67140 0.025 0.000 0.025 0.000 {built-in method builtins.getattr} 20000 0.024 0.000 0.029 0.000 getlimits.py:365(__new__) 40804 0.021 0.000 0.021 0.000 fromnumeric.py:74(&lt;dictcomp&gt;) 20000 0.021 0.000 0.189 0.000 fromnumeric.py:2277(all) 24824 0.020 0.000 0.030 0.000 numerictypes.py:293(issubclass_) 67230 0.020 0.000 0.045 0.000 _asarray.py:88(asanyarray) 20000 0.019 0.000 0.243 0.000 &lt;__array_function__ internals&gt;:2(all) 12412 0.019 0.000 0.050 0.000 numerictypes.py:365(issubdtype) 9045 0.017 0.000 0.025 0.000 numeric.py:1273(normalize_axis_tuple) 139 0.016 0.000 0.021 0.000 &lt;frozen importlib._bootstrap_external&gt;:914(get_data) 31404 0.016 0.000 0.021 0.000 arraysetops.py:138(_unpack_tuple) 10000 0.015 0.000 0.116 0.000 fromnumeric.py:2792(prod) 19 0.015 0.001 0.017 0.001 {built-in method _imp.create_dynamic} 317 0.014 0.000 0.014 0.000 {built-in method builtins.compile} 4221 0.014 0.000 0.043 0.000 numeric.py:1336(moveaxis) 139 0.014 0.000 0.014 0.000 {built-in method marshal.loads} 11207 0.012 0.000 0.064 0.000 &lt;__array_function__ internals&gt;:2(concatenate) 39330 0.011 0.000 0.011 0.000 {built-in method builtins.issubclass} 10000 0.011 0.000 0.139 0.000 &lt;__array_function__ internals&gt;:2(prod) 11608 0.011 0.000 0.011 0.000 {built-in method numpy.core._multiarray_umath.count_nonzero} 11608 0.010 0.000 0.037 0.000 &lt;__array_function__ internals&gt;:2(count_nonzero) 402 0.010 0.000 0.023 0.000 _methods.py:167(_var) 10804 0.010 0.000 0.093 0.000 &lt;__array_function__ internals&gt;:2(any) 1206 0.010 0.000 0.010 0.000 {method 'partition' of 'numpy.ndarray' objects} 10804 0.009 0.000 0.074 0.000 fromnumeric.py:2189(any) 62590/62386 0.008 0.000 0.008 0.000 {built-in method builtins.len} 40846 0.007 0.000 0.007 0.000 {method 'items' of 'dict' objects} 20000 0.007 0.000 0.059 0.000 _methods.py:47(_all) 804 0.006 0.000 0.017 0.000 _methods.py:134(_mean) 1608 0.006 0.000 0.006 0.000 {method 'take' of 'numpy.ndarray' objects} 11608 0.006 0.000 0.017 0.000 numeric.py:409(count_nonzero) 31404 0.006 0.000 0.006 0.000 fromnumeric.py:2354(_cumsum_dispatcher) 1206 0.006 0.000 0.145 0.000 function_base.py:3359(_ureduce) 21762 0.005 0.000 0.005 0.000 {method 'get' of 'dict' objects} 31404 0.005 0.000 0.005 0.000 arraysetops.py:146(_unique_dispatcher) 139 0.005 0.000 0.005 0.000 {method 'read' of '_io.FileIO' objects} 342/339 0.004 0.000 0.006 0.000 {built-in method builtins.__build_class__} 201 0.004 0.000 0.211 0.001 simulation.py:51(population_stats) 804 0.004 0.000 0.133 0.000 function_base.py:3569(percentile) 1 0.004 0.004 135.770 135.770 {method 'writerows' of '_csv.writer' objects} 20000 0.004 0.000 0.004 0.000 fromnumeric.py:2273(_all_dispatcher) 804 0.004 0.000 0.009 0.000 function_base.py:3840(_quantile_is_valid) 402 0.004 0.000 0.025 0.000 function_base.py:3508(_median) 13 0.003 0.000 0.003 0.000 {built-in method builtins.print} 642 0.003 0.000 0.003 0.000 {method 'sub' of 're.Pattern' objects} 9045 0.003 0.000 0.005 0.000 numeric.py:1323(&lt;listcomp&gt;) 4221 0.003 0.000 0.049 0.000 &lt;__array_function__ internals&gt;:2(moveaxis) 16 0.003 0.000 0.003 0.000 {built-in method nt.listdir} 322 0.002 0.000 0.029 0.000 &lt;frozen importlib._bootstrap_external&gt;:1356(find_spec) 11207 0.002 0.000 0.002 0.000 multiarray.py:145(concatenate) 10000 0.002 0.000 0.002 0.000 fromnumeric.py:2787(_prod_dispatcher) 4221 0.002 0.000 0.002 0.000 {method 'transpose' of 'numpy.ndarray' objects} 4222 0.002 0.000 0.002 0.000 {built-in method builtins.sorted} 9045 0.002 0.000 0.002 0.000 {built-in method numpy.core._multiarray_umath.normalize_axis_index} 11608 0.002 0.000 0.002 0.000 numeric.py:405(_count_nonzero_dispatcher) 1206 0.002 0.000 0.002 0.000 _methods.py:50(_count_reduce_items) 10804 0.002 0.000 0.002 0.000 fromnumeric.py:2185(_any_dispatcher) 101/33 0.002 0.000 0.004 0.000 sre_parse.py:469(_parse) 201 0.002 0.000 0.005 0.000 utils.py:1142(_median_nancheck) 321 0.002 0.000 0.002 0.000 {method 'findall' of 're.Pattern' objects} 9499 0.001 0.000 0.001 0.000 {built-in method builtins.isinstance} 19/14 0.001 0.000 0.011 0.001 {built-in method _imp.exec_dynamic} 469/1 0.001 0.000 135.938 135.938 {built-in method builtins.exec} 1608 0.001 0.000 0.009 0.000 fromnumeric.py:97(take) 614 0.001 0.000 0.002 0.000 _inspect.py:67(getargs) 1608 0.001 0.000 0.012 0.000 &lt;__array_function__ internals&gt;:2(take) 3189 0.001 0.000 0.001 0.000 {built-in method builtins.hasattr} 139 0.001 0.000 0.043 0.000 &lt;frozen importlib._bootstrap_external&gt;:793(get_code) 804 0.001 0.000 0.119 0.000 function_base.py:3828(_quantile_unchecked) 182/2 0.001 0.000 0.165 0.083 &lt;frozen importlib._bootstrap&gt;:978(_find_and_load) 4221 0.001 0.000 0.001 0.000 numeric.py:1399(&lt;listcomp&gt;) 4226 0.001 0.000 0.001 0.000 {method 'insert' of 'list' objects} 287 0.001 0.000 0.004 0.000 overrides.py:72(verify_matching_signatures) 317 0.001 0.000 0.029 0.000 overrides.py:154(decorator) 1555 0.001 0.000 0.003 0.000 &lt;frozen importlib._bootstrap_external&gt;:56(_path_join) 179 0.001 0.000 0.034 0.000 &lt;frozen importlib._bootstrap&gt;:882(_find_spec) 339 0.001 0.000 0.002 0.000 functools.py:37(update_wrapper) 190/31 0.001 0.000 0.003 0.000 sre_compile.py:71(_compile) 9045 0.001 0.000 0.001 0.000 {built-in method _operator.index} 77 0.001 0.000 0.001 0.000 sre_compile.py:276(_optimize_charset) 1555 0.001 0.000 0.001 0.000 &lt;frozen importlib._bootstrap_external&gt;:58(&lt;listcomp&gt;) 402 0.001 0.000 0.007 0.000 fromnumeric.py:3153(mean) 804 0.001 0.000 0.001 0.000 {method 'astype' of 'numpy.ndarray' objects} 278 0.001 0.000 0.002 0.000 &lt;frozen importlib._bootstrap_external&gt;:271(cache_from_source) 481 0.001 0.000 0.002 0.000 &lt;frozen importlib._bootstrap&gt;:157(_get_module_lock) 16 0.001 0.000 0.002 0.000 &lt;frozen importlib._bootstrap_external&gt;:1190(_path_hooks) 321 0.001 0.000 0.007 0.000 textwrap.py:414(dedent) 2 0.001 0.000 0.001 0.000 {built-in method _ctypes.LoadLibrary} 756 0.001 0.000 0.001 0.000 {method 'format' of 'str' objects} 481 0.001 0.000 0.001 0.000 &lt;frozen importlib._bootstrap&gt;:78(acquire) 804 0.001 0.000 0.135 0.000 &lt;__array_function__ internals&gt;:2(percentile) 366 0.001 0.000 0.001 0.000 {built-in method _thread.allocate_lock} 1608 0.001 0.000 0.001 0.000 {method 'squeeze' of 'numpy.ndarray' objects} 162 0.001 0.000 0.032 0.000 &lt;frozen importlib._bootstrap_external&gt;:1240(_get_spec) 175 0.001 0.000 0.003 0.000 &lt;frozen importlib._bootstrap&gt;:504(_init_module_attrs) 175/2 0.001 0.000 0.164 0.082 &lt;frozen importlib._bootstrap&gt;:663(_load_unlocked) 882/71 0.001 0.000 0.146 0.002 &lt;frozen importlib._bootstrap&gt;:1009(_handle_fromlist) 618 0.001 0.000 0.003 0.000 _inspect.py:98(getargspec) 481 0.001 0.000 0.001 0.000 &lt;frozen importlib._bootstrap&gt;:103(release) 17 0.001 0.000 0.001 0.000 {built-in method _imp.create_builtin} 634 0.001 0.000 0.001 0.000 {built-in method __new__ of type object at 0x00007FFFE42159A0} 455 0.001 0.000 0.010 0.000 re.py:271(_compile) 278 0.001 0.000 0.001 0.000 &lt;frozen importlib._bootstrap_external&gt;:62(_path_split) 402 0.001 0.000 0.006 0.000 fromnumeric.py:657(partition) 4221 0.001 0.000 0.001 0.000 numeric.py:1332(_moveaxis_dispatcher) 182/2 0.001 0.000 0.165 0.083 &lt;frozen importlib._bootstrap&gt;:948(_find_and_load_unlocked) 12 0.001 0.000 0.001 0.000 __init__.py:316(namedtuple) 2064 0.001 0.000 0.001 0.000 {method 'join' of 'str' objects} </code></pre> <p>Of course any advice is highly appreciated!=)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T22:59:41.203", "Id": "437864", "Score": "1", "body": "If performance is a really big concern you might want to use Pytorch or Tensorflow, not for the machine learning part, but for the usage of CUDA accelerated tensors." } ]
[ { "body": "<h2>Tuple returns</h2>\n\n<pre><code> \"\"\"\n Return\n -------\n tuple\n Contains statistics of the simulated system.\n \"\"\"\n ...\n return (\n gyak_sums[0], gyak_sums[1], (population[0, :] &gt; 1).sum(),\n gyak_means[0], gyak_variances[0],\n gyak_percentiles_25[0], gyak_medians[0], gyak_percentiles_75[0],\n gyak_means[1], gyak_variances[1],\n gyak_percentiles_25[1], gyak_medians[1], gyak_percentiles_75[1],\n fitness_list.mean(), fitness_list.var(),\n np.percentile(fitness_list, 25),\n np.median(fitness_list),\n np.percentile(fitness_list, 75)\n )\n</code></pre>\n\n<p>First of all - if you're going to bother documenting the function, it would be important to describe every one of these values. However, the easier and significantly more maintainable thing to do is return an object of some kind; pick your flavour - a plain-old class, a data class, a named tuple, what-have-you. These would all allow for you to return one thing whose members are self-documenting, instead of requiring magical knowledge of position to access them.</p>\n\n<h2>Logical, not bit-wise, operators</h2>\n\n<pre><code>while (population.size &gt; 0) &amp; (gen &lt; gen_max):\n</code></pre>\n\n<p>The only time I've seen syntax like this in Python is for SQLAlchemy, which does some dirty tricks to produce SQL from vaguely boolean-smelling expressions. However, it's much more likely that you actually mean:</p>\n\n<pre><code>while population.size &gt; 0 and gen &lt; gen_max:\n</code></pre>\n\n<p>since <code>and</code> is logical and <code>&amp;</code> is bit-wise. It's also worth noting that you should Loop Like a Native, and instead of incrementing <code>gen</code> manually, do</p>\n\n<pre><code>for gen in range(gen_max):\n if population_size &lt;= 0:\n break\n</code></pre>\n\n<h2>Type hints</h2>\n\n<p>This is somewhat of an educated guess, but</p>\n\n<pre><code>def write_out_file(result, local_time, n_run):\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def write_out_file(result: List[Iterable[int]], local_time: datetime, n_run: int):\n</code></pre>\n\n<p>It looks (though it is missing from the documentation) that <code>local_time</code> is actually passed in as a string, but it shouldn't be. Stringification should in this case be left to the function itself.</p>\n\n<h2>Global code</h2>\n\n<p>This stuff:</p>\n\n<pre><code>LOCAL_TIME = time.strftime(\"%m_%d_%H_%M_%S_%Y\", time.localtime(time.time()))\nDEAD_OR_ALIVE = open(\"output_data_\" + LOCAL_TIME + \".txt\", \"w\")\nRESULT = [simulation(1000, 200, 1.5, 0.0, 10000)]\n#RESULT.append(simulation(1000, 200, 1.5, 1.0, 10000))\nN_RUN = 1\nwrite_out_file(RESULT, LOCAL_TIME, N_RUN)\nDEAD_OR_ALIVE.close()\n</code></pre>\n\n<p>has a few problems:</p>\n\n<ul>\n<li>That code blob should be in a <code>main</code> function</li>\n<li>Once that happens, you can de-capitalize those variable names.</li>\n<li><code>DEAD_OR_ALIVE</code> should be put into a <code>with</code> block</li>\n</ul>\n\n<h2>Use enumerate</h2>\n\n<p>This:</p>\n\n<pre><code> counter = 0\n for i in result:\n out_file.writerows(i)\n counter += 1\n print(counter, \"/\", n_run, \"\\n\")\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>for counter, i in enumerate(result):\n out_file.writerows(i)\n print(f'{counter}/{n_run}')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T04:04:25.177", "Id": "238919", "ParentId": "220493", "Score": "3" } } ]
{ "AcceptedAnswerId": "238919", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T23:52:34.990", "Id": "220493", "Score": "13", "Tags": [ "python", "performance", "python-3.x", "numpy", "simulation" ], "Title": "Population dynamic simulation on biological information maintenance 2" }
220493
<p>I have written a script that: </p> <ol> <li>connects to an IIS server</li> <li>stops a website</li> <li>copies its files to a backup folder (on the remote machine)</li> <li>copies files from my local machine to replace the ones on the remote IIS server</li> <li>then relaunches IIS. </li> </ol> <p>The script works, but I would love to make it cleaner (I pieced this together). Any suggestions?</p> <pre><code>@echo off C:\Users\me\Documents\PSTools\PsExec \\10.45.12.12 -u "mydomain\myuser" -p "mypwd" %windir%\system32\inetsrv\appcmd stop sites "test.mysite.com" sleep 5 for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" set "YY=%dt:~2,2%" &amp; set "YYYY=%dt:~0,4%" &amp; set "MM=%dt:~4,2%" &amp; set "DD=%dt:~6,2%" set "HH=%dt:~8,2%" &amp; set "Min=%dt:~10,2%" &amp; set "Sec=%dt:~12,2%" set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%" NET USE \\10.45.12.12 /u:mydomain\myuser "mypwd" rem moves files and directories then del source robocopy /e /move \\10.45.12.12\C$\inetpub\wwwroot\test.mysite.com \\10.45.12.12\C$\Users\me\Desktop\OLD_web_builds\test.mysite\%fullstamp% rem copy vs published files to remote server. exclude the UL_LK folder robocopy C:\Users\me\Desktop\_REPOS\invwebops\InvWebOps\bin\Release\netcoreapp2.2\publish \\10.45.12.12\C$\inetpub\wwwroot\test.mysite.com /e /XD "C:\Users\me\Desktop\_REPOS\invwebops\InvWebOps\bin\Release\netcoreapp2.2\publish\wwwroot\UL_LK" rem restart test.mysite C:\Users\me\Documents\PSTools\PsExec \\10.45.12.12 -u "mydomain\myuser" -p "mypwd" %windir%\system32\inetsrv\appcmd start sites "test.mysite.com" set /p DUMMY=Hit ENTER to continue... </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T00:51:28.170", "Id": "220494", "Score": "1", "Tags": [ "batch" ], "Title": "Copies local files to remote IIS server" }
220494
<p>So I want ask if I'm doing it right way.</p> <p>Im still learning..</p> <p>I want check textarea duplicates and alert if duplicate and remove it.</p> <pre><code>$(document).ready(function(){ $('#lol').keypress(function(){ var data = $('#lol').val().split('\n'); var result = data.filter((word, i, arr) =&gt; arr.indexOf(word) === i); $('#lol').val(result.join('\n')); data.unique(); }); }); (function() { "use strict"; Array.prototype.unique = function unique() { var self = this; return self.filter(function(a) { var that = this; // console.log(that); if(!that[a]) { return that[a] = true; } else { alert("duplicate"); return that[a] = false; } }, {}); } })(); </code></pre>
[]
[ { "body": "<h2>Take care extending built in objects</h2>\n<ul>\n<li><p>Extending the prototype of builtin objects should be done with care. The best way is via <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow noreferrer\">Object.defineProperty</a> and first check if something has not already done so. (See 2nd rewrite)</p>\n</li>\n<li><p>Why create two copies of <code>this</code>.. <code>self</code> and <code>that</code>. Why not just use <code>this</code> and create a map object with a meaningful name. (see 2nd rewrite)</p>\n</li>\n<li><p>Don't add functionality outside the role of the function. <code>Array.unique</code> Defiantly should not be calling an alert (in fact you can not trust alerts (clients can turn them off) so you should never use them)</p>\n</li>\n<li><p>You have actually repeated the process of removing duplicates in the <code>keypress</code> handler. You could just have checked if the length of <code>data</code> and <code>result</code> are different and alerted the client from that. (see 1st rewrite)</p>\n</li>\n</ul>\n<h2>Rewrites</h2>\n<p>First quick rewrite showing you don't need <code>Array.unique</code></p>\n<pre><code>$(document).ready(function(){\n const lol = $('#lol');\n lol.keypress(function(){\n const data = lol.val().split('\\n');\n const result = data.filter((word, i, arr) =&gt; arr.indexOf(word) === i);\n lol.val(result.join('\\n'));\n result.length !== data.length &amp;&amp; (alert(&quot;duplicate&quot;));\n });\n});\n</code></pre>\n<p>The second rewrite showing a safe way to add to inbuilt prototypes.</p>\n<p><strong>Note</strong> that the options <code>configurable</code>, <code>enumerable</code>, <code>writable</code> are set to false. Particularly you <strong>MUST</strong> set <code>enumerable</code> to be <code>false</code> or you could end up with all sorts of bugs appearing in existing code.</p>\n<p>You should also learn to not use jQuery. It has had its day and will just set you back as it shelters you from learning modern JS and DOM interfaces.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\nlol.focus();\nlol.addEventListener(\"keyup\", event =&gt; {\n const data = lol.value.split(\"\\n\");\n const result = data.unique();\n info.textContent = result.length !== data.length ? \"Duplicate removed\" : \"\";\n lol.value = result.join('\\n'); \n});\n\nif (!Array.prototype.unique) {\n Object.defineProperty(Array.prototype, \"unique\", {\n configurable: false, // these 3 properties default to false so not needed\n enumerable: false, // But have added them just to show their availability.\n writable: false, \n value: function() { \n const existing = {};\n return this.filter(a =&gt; existing[a] = !existing[a] ? true : false);\n }\n });\n} else {\n throw new Error(\"Array.prototype.unique already defined.\");\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;textarea id=\"lol\"&gt;&lt;/textarea&gt;\n&lt;div id=\"info\" style=\"color:red\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:19:54.977", "Id": "220641", "ParentId": "220495", "Score": "0" } } ]
{ "AcceptedAnswerId": "220641", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T01:05:31.730", "Id": "220495", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Alert about duplicates and remove them" }
220495
<p>I'm trying to write a triple buffer that's wait free for a update + render loop after being bitten by lock starvation one too many times (on a different project, using a library).</p> <p>For reference, a triple buffer is effectively a single producer, single consumer channel, that allows for the producer to update the buffer while the consumer can always get the most recently updated buffer. Since the renderer only needs the most recent state to extrapolate a (soon to be) future state and the simulation could update many times in between, this fits. Since simulation data tends to update EVERYTHING as well as being kind of arbitrary, I wanted the write and read to be entirely unrestricted in what could be done to the buffers. Since I had to deal with starving rendering threads in the last assignment, I decided to make it lock free, then stumbled on what I think is wait free as well (it's effectively a single <code>fetch_nand</code> statement).</p> <p>Here's the code (same as on <a href="https://github.com/AlterionX/totality-rs/tree/master/totality-sync" rel="nofollow noreferrer">GitHub</a>):</p> <pre class="lang-rust prettyprint-override"><code>use std::{ cell::UnsafeCell, fmt::Debug, sync::{ atomic::{AtomicBool, AtomicUsize}, Arc, }, }; use cb::utils::CachePadded; #[allow(unused_imports)] use log::{debug, error, info, trace, warn}; pub fn buffer&lt;T: Clone&gt;(src: T) -&gt; (ReadingView&lt;T&gt;, EditingView&lt;T&gt;) { TripleBuffer::alloc(src) } #[derive(Debug)] struct TripleBufferIndices { snatched_read: CachePadded&lt;usize&gt;, // unique packed_vals: CachePadded&lt;AtomicUsize&gt;, // shared stale: CachePadded&lt;AtomicBool&gt;, // shared edit_rw: CachePadded&lt;(usize, usize)&gt;, // unique } impl TripleBufferIndices { #[inline] fn pack(v0: usize, v1: usize) -&gt; usize { (0b0 &lt;&lt; 4) + (v0 &lt;&lt; 2) + ((!v1) &amp; 0b11) } #[inline] fn unpack(packed: usize) -&gt; (usize, usize) { let should_negate = ((packed &gt;&gt; 4) &amp; 0b1) != 0; let most_recent = (if should_negate { !packed } else { packed } &gt;&gt; 2) &amp; 0b11; let next_write = !packed &amp; 0b11; (most_recent, next_write) } fn snatch(&amp;mut self) { let mask = (0b1 &lt;&lt; 4) + (0b11 &lt;&lt; 2) + match *self.snatched_read { 0 =&gt; 0b00, 1 =&gt; 0b01, 2 =&gt; 0b10, _ =&gt; panic!("We done goofed!"), }; let old_snatched = self.snatched_read; if !self.stale.swap(true, std::sync::atomic::Ordering::Acquire) { *self.snatched_read = Self::unpack( self.packed_vals .fetch_nand(mask, std::sync::atomic::Ordering::AcqRel), ) .0; trace!( "Snatching indices {:?} and returning indices {:?}.", old_snatched, self.snatched_read ); } } fn advance(&amp;mut self) { let next_write = Self::unpack(self.packed_vals.swap( Self::pack(self.edit_rw.1, self.edit_rw.1), std::sync::atomic::Ordering::AcqRel, )) .1; self.stale.swap(false, std::sync::atomic::Ordering::Release); trace!( "Advancing indices from {:?} to {:?}.", self.edit_rw.1, next_write ); self.edit_rw.0 = self.edit_rw.1; self.edit_rw.1 = next_write; } } impl Default for TripleBufferIndices { fn default() -&gt; Self { Self { snatched_read: CachePadded::new(0), packed_vals: CachePadded::new(AtomicUsize::new(Self::pack(0, 2))), stale: CachePadded::new(AtomicBool::new(true)), edit_rw: CachePadded::new((1, 2)), } } } struct TripleBuffer&lt;T: Clone&gt; { ii: UnsafeCell&lt;TripleBufferIndices&gt;, backing_mem: *const [UnsafeCell&lt;CachePadded&lt;T&gt;&gt;; 3], tt: [*mut T; 3], } impl&lt;T: Clone&gt; TripleBuffer&lt;T&gt; { pub fn alloc(src: T) -&gt; (ReadingView&lt;T&gt;, EditingView&lt;T&gt;) { let backing_mem = Box::into_raw(Box::new([ UnsafeCell::new(CachePadded::new(src.clone())), UnsafeCell::new(CachePadded::new(src.clone())), UnsafeCell::new(CachePadded::new(src)), ])); let mut tt: [*mut T; 3] = unsafe { std::mem::uninitialized() }; unsafe { for i in 0..3 { tt[i] = &amp;mut **(*backing_mem)[i].get(); } } let arc = Arc::new(Self { ii: UnsafeCell::new(TripleBufferIndices::default()), backing_mem, tt, }); (ReadingView(arc.clone()), EditingView(arc)) } fn snatch(&amp;self) { let ii = self.ii.get(); unsafe { (*ii).snatch() }; } fn advance(&amp;self) { let ii = self.ii.get(); unsafe { (*ii).advance() }; } fn rr(&amp;self) -&gt; *const T { let ii = self.ii.get(); self.tt[unsafe { *(*ii).snatched_read }] } fn er(&amp;self) -&gt; *const T { let ii = self.ii.get(); self.tt[unsafe { (*ii).edit_rw.0 }] } fn ew(&amp;self) -&gt; *mut T { let ii = self.ii.get(); self.tt[unsafe { (*ii).edit_rw.1 }] } } impl&lt;T: Clone&gt; Drop for TripleBuffer&lt;T&gt; { fn drop(&amp;mut self) { unsafe { Box::from_raw(self.backing_mem as *mut [CachePadded&lt;T&gt;; 3]); }; } } pub struct RWPair&lt;R, W&gt; { r: R, w: W, } pub enum Reading&lt;T: Clone&gt; { ReadingView(ReadingView&lt;T&gt;), Reader(Reader&lt;T&gt;), } pub struct ReadingView&lt;T: Clone&gt;(Arc&lt;TripleBuffer&lt;T&gt;&gt;); impl&lt;T: Clone&gt; ReadingView&lt;T&gt; { pub fn read(self) -&gt; Reader&lt;T&gt; { Reader::from_view(self) } } unsafe impl&lt;T: Clone&gt; Send for ReadingView&lt;T&gt; {} pub struct Reader&lt;T: Clone&gt; { origin: ReadingView&lt;T&gt;, locker: *const T, } impl&lt;T: Clone&gt; Reader&lt;T&gt; { pub fn from_view(rv: ReadingView&lt;T&gt;) -&gt; Reader&lt;T&gt; { rv.0.snatch(); Self { locker: rv.0.rr(), origin: rv, } } pub fn r&lt;'a&gt;(&amp;'a self) -&gt; &amp;'a T { unsafe { &amp;*self.locker } } pub fn release(self) -&gt; ReadingView&lt;T&gt; { self.origin } } pub enum Editing&lt;T: Clone&gt; { EditingView(EditingView&lt;T&gt;), Editor(Editor&lt;T&gt;), } pub struct EditingView&lt;T: Clone&gt;(Arc&lt;TripleBuffer&lt;T&gt;&gt;); impl&lt;T: Clone&gt; EditingView&lt;T&gt; { pub fn edit(self) -&gt; Editor&lt;T&gt; { Editor::from_view(self) } } unsafe impl&lt;T: Clone&gt; Send for EditingView&lt;T&gt; {} pub struct Editor&lt;T: Clone&gt; { origin: EditingView&lt;T&gt;, rw_lock: RWPair&lt;*const T, *mut T&gt;, } impl&lt;T: Clone&gt; Editor&lt;T&gt; { fn from_view(ev: EditingView&lt;T&gt;) -&gt; Editor&lt;T&gt; { Editor { rw_lock: RWPair { r: ev.0.er(), w: ev.0.ew(), }, origin: ev, } } pub fn r&lt;'a&gt;(&amp;'a self) -&gt; &amp;'a T { unsafe { &amp;*self.rw_lock.r } } pub fn w&lt;'a&gt;(&amp;'a self) -&gt; &amp;'a mut T { unsafe { &amp;mut *self.rw_lock.w } } pub fn release(self) -&gt; EditingView&lt;T&gt; { self.origin.0.advance(); self.origin } } </code></pre> <p>And you can run it like this:</p> <pre class="lang-rust prettyprint-override"><code>fn sort_of_a_test() { let (rv, ev) = tb::buffer([0u8; 1_000]); let e_th = std::thread::spawn(move || { let mut ev = Some(ev); let mut e = None; for _ in 0..255 { e.replace(ev.take().unwrap().edit()); // do some editing let e_int = e.as_ref().unwrap(); for (rv, ev) in e_int.r().iter().zip(e_int.w().iter_mut()) { *ev = *rv + 1; } ev.replace(e.take().unwrap().release()); } }); let r_th = std::thread::spawn(move || { let mut rv = Some(rv); let mut r = None; let mut scratch = 0; loop { r.replace(rv.take().unwrap().read()); // do some reading for v in r.as_ref().unwrap().r().iter() { scratch = *v; } rv.replace(r.take().unwrap().release()); if scratch == 255 { break; } } }); e_th.join().expect("Failed to join editing thread."); r_th.join().expect("Failed to join reading thread."); } </code></pre> <p>EDIT: As a side note, I would like to avoid the Option swap there, if possible.</p> <p>EDIT 2: Forgot to mention, <code>cb</code> is the <code>crossbeam</code> crate.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-20T08:13:02.677", "Id": "502944", "Score": "0", "body": "Didn't fully read your code, but I've experimented with multiple triple-buffer designs, and settled on an array of three `UnsafeCell<T>` and a single atomic byte as state (probably simpler than your design). I found a mature crate implementing this scheme at https://github.com/HadrienG2/triple-buffer, and multiple people have independently discovered equivalent formulations: https://github.com/Ralith/oddio/blob/main/src/swap.rs and https://github.com/nyanpasu64/spectro2/blob/master/flip-cell/src/lib.rs." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T02:30:07.277", "Id": "220496", "Score": "4", "Tags": [ "performance", "thread-safety", "rust" ], "Title": "Wait free triple buffer primitive" }
220496
<p>Given a set of <span class="math-container">\$k\$</span> <span class="math-container">\$n\$</span>-vectors <span class="math-container">\$\vec{x_1}, \dots, \vec{x_k}\$</span>, <a href="https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process" rel="nofollow noreferrer">Gram-Schmidt process</a> computes a basis <span class="math-container">\$\vec{y_1}, \dots, \vec{y_m}\$</span> (<span class="math-container">\$m \leq k\$</span>) the vectors of which span the same space as <span class="math-container">\$\vec{x_1}, \dots, \vec{x_k}\$</span> but are mutually orthogonal: the inner product <span class="math-container">\$\vec{y_i}\cdot\vec{y_j} = 0\$</span> for all <span class="math-container">\$i \neq j\$</span>. <span class="math-container">$$ \vec{x} \cdot \vec{y} = \sum_{r = 1}^n x_r y_r. $$</span></p> <p>Below is my code:</p> <p><strong><code>net.coderodde.math.Additive</code></strong></p> <pre><code>package net.coderodde.math; /** * This interface defines the API for adding the two elements. * * @param &lt;I1&gt; the type of the left operand. * @param &lt;I2&gt; the type of the right operand. * @param &lt;O&gt; the sum type. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public interface Additive&lt;I1, I2, O&gt; { /** * This method adds {@code a} and {@code b} and returns the sum. * * @param a the first element. * @param b the second element. * @return the sum of the two given numbers. */ public O add(I1 a, I2 b); } </code></pre> <p><strong><code>net.coderodde.math.Demo</code></strong></p> <pre><code>package net.coderodde.math; import net.coderodde.math.impl.ComplexVectorProductByScalar; import net.coderodde.math.impl.ComplexNumber; import net.coderodde.math.impl.ComplexVectorAdditive; import net.coderodde.math.impl.ComplexVectorDivisible; import net.coderodde.math.impl.ComplexVectorInnerProduct; import net.coderodde.math.impl.ComplexVectorNegative; import net.coderodde.math.impl.RealVectorAdditive; import net.coderodde.math.impl.RealVectorDivisible; import net.coderodde.math.impl.RealVectorInnerProduct; import net.coderodde.math.impl.RealVectorNegative; import net.coderodde.math.impl.RealVectorProductByScalar; /** * This class runs a simple demo for the Gram-Schmidt process. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ final class Demo { public static void main(String[] args) { Vector&lt;Double&gt; x1 = new Vector&lt;&gt;(1., -1., 1., -1.); Vector&lt;Double&gt; x2 = new Vector&lt;&gt;(5., 1., 1., 1.); Vector&lt;Double&gt; x3 = new Vector&lt;&gt;(-3., -3., 1., -3.); Vector&lt;Double&gt;[] orthogonalBasis1 = new GramSchmidtProcess&lt;&gt;(new RealVectorInnerProduct(), new RealVectorDivisible(), new RealVectorProductByScalar(), new RealVectorAdditive(), new RealVectorNegative()) .process(x1, x2, x3); for (Vector&lt;Double&gt; vector : orthogonalBasis1) { System.out.println(vector); } System.out.println("Orthogonal: " + isOrthogonal(orthogonalBasis1[0], orthogonalBasis1[1], 0.00001)); System.out.println("------"); // [(1, -2), (3, 4)] = [1 - 2i, 3 + 4i] Vector&lt;ComplexNumber&gt; c1 = new Vector&lt;&gt;(new ComplexNumber(1, -2), new ComplexNumber(3, 4)); // [(0, -3), (1, 1)] = [-3i, 1 + i] Vector&lt;ComplexNumber&gt; c2 = new Vector&lt;&gt;(new ComplexNumber(0, -3), new ComplexNumber(1, 1)); Vector&lt;ComplexNumber&gt;[] orthogonalBasis2 = new GramSchmidtProcess&lt;&gt;(new ComplexVectorInnerProduct(), new ComplexVectorDivisible(), new ComplexVectorProductByScalar(), new ComplexVectorAdditive(), new ComplexVectorNegative()) .process(c1, c2); for (Vector&lt;ComplexNumber&gt; c : orthogonalBasis2) { System.out.println(c); } System.out.println("Orthogonal: " + isOrthogonalComplex(orthogonalBasis2[0], orthogonalBasis2[1], 0.00001)); } public static &lt;E, IP&gt; boolean basisIsOrthogonal(Vector&lt;Double&gt;[] basis, double epsilon) { for (int i = 1; i &lt; basis.length; i++) { Vector&lt;Double&gt; target = basis[i]; for (int j = 0; j &lt; i; j++) { Vector&lt;Double&gt; current = basis[j]; if (!isOrthogonal(target, current, epsilon)) { return false; } } } return true; } public static boolean basisIsOrthogonalComplex( Vector&lt;ComplexNumber&gt;[] basis, double epsilon) { for (int i = 1; i &lt; basis.length; i++) { Vector&lt;ComplexNumber&gt; target = basis[i]; for (int j = 0; j &lt; i; j++) { Vector&lt;ComplexNumber&gt; current = basis[j]; if (!isOrthogonalComplex(target, current, epsilon)) { return false; } } } return true; } private static boolean isOrthogonal(Vector&lt;Double&gt; a, Vector&lt;Double&gt; b, double epsilon) { double sum = 0.0; for (int i = 0; i &lt; a.getNumberOfDimensions(); i++) { sum += a.get(i) * b.get(i); } return sum &lt; epsilon; } private static boolean isOrthogonalComplex(Vector&lt;ComplexNumber&gt; a, Vector&lt;ComplexNumber&gt; b, double epsilon) { ComplexNumber sum = new ComplexNumber(0, 0); for (int i = 0; i &lt; a.getNumberOfDimensions(); i++) { ComplexNumber product = a.get(i).multiply(b.get(i)); sum = sum.add(product); } return Math.abs(sum.getRealPart()) &lt; epsilon &amp;&amp; Math.abs(sum.getImaginaryPart()) &lt; epsilon; } } </code></pre> <p><strong><code>net.coderodde.math.Divisible</code></strong></p> <pre><code>package net.coderodde.math; /** * This interface defines the API for division operator. * * @param &lt;D1&gt; the type of the divident. * @param &lt;D2&gt; the type of the divisor. * @param &lt;F&gt; the fraction type. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public interface Divisible&lt;D1, D2, F&gt; { /** * Divides {@code a} by {@code b} and returns the result. * * @param divident the object being divided. * @param divisor the divisor. * @return the result of dividing {@code divident} by {@code divisor}. */ public F divide(D1 divident, D2 divisor); } </code></pre> <p><strong><code>net.coderodde.math.GramSchmidtProcess</code></strong></p> <pre><code>package net.coderodde.math; import java.util.Arrays; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * This class implements the method for running * &lt;a href=""&gt;https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process&lt;/a&gt; * over a given independent basis of a linear space. * * @param &lt;VCT&gt; the vertex component type. * @param &lt;IPT&gt; the inner product type. * @param &lt;FT&gt; the division result type. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public class GramSchmidtProcess&lt;VCT, IPT, FT&gt; { /** * This object is responsible for computing the inner product of two * vectors. */ private InnerProduct&lt;VCT, VCT, IPT&gt; innerProduct; /** * This object is responsible for computing division. */ private Divisible&lt;IPT, IPT, FT&gt; divisible; /** * This object is responsible for computing products (multiplication). */ private Product&lt;FT, Vector&lt;VCT&gt;, Vector&lt;VCT&gt;&gt; product; /** * This object is responsible for computing addition. */ private Additive&lt;Vector&lt;VCT&gt;, Vector&lt;VCT&gt;, Vector&lt;VCT&gt;&gt; additive; /** * This object is responsible for computing negative elements. */ private Negative&lt;Vector&lt;VCT&gt;, Vector&lt;VCT&gt;&gt; negative; /** * Constructs the object with the method for running Gram-Schmidt process * over given basis. * * @param innerProduct the object for computing inner products. * @param divisible the object for performing division. * @param product the object for performing multiplication. * @param additive the object for performing addition. * @param negative the object for computing inverses. */ public GramSchmidtProcess(InnerProduct&lt;VCT, VCT, IPT&gt; innerProduct, Divisible&lt;IPT, IPT, FT&gt; divisible, Product&lt;FT, Vector&lt;VCT&gt;, Vector&lt;VCT&gt;&gt; product, Additive&lt;Vector&lt;VCT&gt;, Vector&lt;VCT&gt;, Vector&lt;VCT&gt;&gt; additive, Negative&lt;Vector&lt;VCT&gt;, Vector&lt;VCT&gt;&gt; negative) { this.innerProduct = Objects.requireNonNull( innerProduct, "The input InnerProduct is null."); this.negative = Objects.requireNonNull(negative, "The input Negative is null."); this.product = Objects.requireNonNull(product, "The input Product is null."); this.divisible = Objects.requireNonNull(divisible, "The input Divisible is null."); this.additive = Objects.requireNonNull(additive, "The input Additive is null."); } /** * Performs the Gram-Schmidt process upon {@code basis}. * * @param basis the basis to process. * @return the orthogonal basis. */ public Vector&lt;VCT&gt;[] process(Vector&lt;VCT&gt;... basis) { // Validate the input basis: checkBasis(basis); // Deal with the very first base element: Vector&lt;VCT&gt;[] orthogonalBasis = new Vector[basis.length]; orthogonalBasis[0] = (Vector&lt;VCT&gt;) new Vector(basis[0]); // The actual process: for (int i = 1; i &lt; basis.length; i++) { // Copy-construct 'x' from 'basis[i]': Vector&lt;VCT&gt; x = new Vector&lt;&gt;(basis[i]); // For each basis element before 'x', do: for (int j = 0; j &lt; i; j++) { // Take the inner product of the divident: IPT innerProductDivident = this.innerProduct.innerProductOf(x, orthogonalBasis[j]); // Take the inner product of the divisor: IPT innerProductDivisor = this.innerProduct.innerProductOf(orthogonalBasis[j], orthogonalBasis[j]); // Divide the divident by divisor: FT fraction = divisible.divide(innerProductDivident, innerProductDivisor); // Multiply the above by the current basis: Vector&lt;VCT&gt; term = product.multiply(fraction, basis[j]); // Negate the above: term = negative.negate(term); // Add the above to 'x'. Effectively, it subtracts 'term' from // 'x' since we have negated 'term': x = additive.add(x, term); } orthogonalBasis[i] = x; } // Remove the duplicates and return whatever is left: return removeDuplicates(orthogonalBasis); } /** * This method validates the input data sent to the Gram-Schmidt process * implementation above. * * @param &lt;E&gt; the element component type. * @param basisCandidate the basis candidate. * @throws IllegalArgumentException if the candidate is not valid. */ private static &lt;E&gt; void checkBasis(Vector&lt;E&gt;[] basisCandidate) { // Check not null: Objects.requireNonNull(basisCandidate, "The input basis is null."); // Check is not empty: if (basisCandidate.length == 0) { throw new IllegalArgumentException("No vectors given."); } int expectedDimensions = basisCandidate[0].getNumberOfDimensions(); // Each element in the basis candidate must have the same // dimensionality: if (expectedDimensions == 0) { throw new IllegalArgumentException( "The element at index 0 has no components."); } for (int i = 1; i &lt; basisCandidate.length; i++) { if (basisCandidate[i].getNumberOfDimensions() == 0) { // Oops. An empty element: throw new IllegalArgumentException( "The element at index " + i + " has no components."); } if (expectedDimensions != basisCandidate[i].getNumberOfDimensions()) { // Oops. Not all basis elements are of the same equal // dimensionality: throw new IllegalArgumentException( "Element dimension mismatch: expected " + expectedDimensions + " but was " + basisCandidate[i].getNumberOfDimensions() + " at index " + i + "."); } } } private static &lt;E&gt; Vector&lt;E&gt;[] removeDuplicates(Vector&lt;E&gt;[] basis) { Set&lt;Vector&lt;E&gt;&gt; set = new HashSet&lt;&gt;(Arrays.asList(basis)); Vector&lt;E&gt;[] vectors = new Vector[set.size()]; return set.toArray(vectors); } } </code></pre> <p><strong><code>net.coderodde.math.InnerProduct</code></strong></p> <pre><code>package net.coderodde.math; /** * This interface defines the API for inner product over given vector component * type. * * @param &lt;VCT1&gt; the left vector type. * @param &lt;VCT2&gt; the right vector type. * @param &lt;IPT&gt; the inner product value type. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public interface InnerProduct&lt;VCT1, VCT2, IPT&gt; { /** * Computes the inner product of the two given vectors. * * @param a the first vector. * @param b the second vector. * @return the inner product */ public IPT innerProductOf(Vector&lt;VCT1&gt; a, Vector&lt;VCT2&gt; b); } </code></pre> <p><strong><code>net.coderodde.math.Negative</code></strong></p> <pre><code> package net.coderodde.math; /** * This interface defines the API for computing negative of given values. * * @param &lt;I&gt; the input type. * @param &lt;O&gt; the output type. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public interface Negative&lt;I, O&gt; { /** * Returns the negative of {@code element}. The negative of {@code a} is * {@code -a} such that {@code a + (-a) = O}, where {@code O} is the zero * element. * * @param element the element to negate. * @return the negative of {@code element}. */ public O negate(I element); } </code></pre> <p><strong><code>net.coderodde.math.Product</code></strong></p> <pre><code>package net.coderodde.math; /** * This interface defines the API for multiplication (product). * * @param &lt;E1&gt; the type of the left element to multiply. * @param &lt;E2&gt; the type of the right element to multiply. * @param &lt;O&gt; the product result type. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public interface Product&lt;E1, E2, O&gt; { /** * Returns the product of {@code a} and {@code b}. * * @param a the first element. * @param b the second element. * @return the product of the two input elements. */ public O multiply(E1 a, E2 b); } </code></pre> <p><strong><code>net.coderodde.math.Vector</code></strong></p> <pre><code>package net.coderodde.math; import java.util.Arrays; import java.util.Objects; /** * This class implements a vector/element in a {@code n}-dimensional space. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public final class Vector&lt;E&gt; { /** * The actual vector contents. */ private final E[] components; /** * Constructs the vector from the given data. * * @param components the vector data. */ public Vector(E... components) { Objects.requireNonNull(components, "The input vector is null."); this.components = Arrays.copyOf(components, components.length); } /** * Copy-constructs this vector. * * @param vector the vector to copy. */ public Vector(Vector&lt;E&gt; vector) { this.components = Arrays.copyOf(vector.components, vector.components.length); } /** * Returns the {@code index}th component of this vector. * * @param index the component index. * @return the value of the {@code index}th component. */ public E get(int index) { return components[index]; } /** * Sets the value of the {@code index}th vector component to the given * value. * * @param index the index of the target vector component. * @param value the value to set. */ public void set(int index, E value) { components[index] = value; } /** * Returns the number of components in this vector. * * @return the number of components in this vector. */ public int getNumberOfDimensions() { return components.length; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder("&lt;"); String separator = ""; for (E component : components) { stringBuilder.append(separator); separator = ", "; stringBuilder.append(component); } return stringBuilder.append("&gt;").toString(); } @Override public int hashCode() { return Arrays.hashCode(components); } @Override public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (!o.getClass().equals(this.getClass())) { return false; } Vector&lt;E&gt; other = (Vector&lt;E&gt;) o; return Arrays.equals(components, other.components); } } </code></pre> <p><strong><code>net.coderodde.math.impl.ComplexNumber</code></strong></p> <pre><code>package net.coderodde.math.impl; /** * This class implements a complex number. The complex number consists of a real * part and an imaginary part. The imaginary part is a real number equipped with * the imaginary unit {@code i}, for which {@code i^2 = -1}. This class is * immutable. * * @author Rodion "rodde" Efremov * @version 1.6 (May 18, 2019) */ public final class ComplexNumber { /** * The real number. */ private final double realPart; /** * The imaginary number. */ private final double imaginaryPart; /** * Constructs a new complex number. * * @param realPart the real part of the newly constructed complex * number. * @param imaginaryPart the imaginary part of the newly constructed complex * number. */ public ComplexNumber(final double realPart, final double imaginaryPart) { checkNotNan(realPart); checkNotNan(imaginaryPart); checkNotInfinite(realPart); checkNotInfinite(imaginaryPart); this.realPart = realPart; this.imaginaryPart = imaginaryPart; } /** * Returns the real part of this complex number. * * @return the real part of this complex number. */ public double getRealPart() { return realPart; } /** * Returns the imaginary part of this complex number. * * @return the imaginary part of this complex number. */ public double getImaginaryPart() { return imaginaryPart; } /** * Returns the complex number that is equal to the sum of this complex * number and the {@code other} complex number. * * @param other the complex number to add. * @return the sum of this and {@code other} complex number. */ public ComplexNumber add(ComplexNumber other) { return new ComplexNumber(realPart + other.realPart, imaginaryPart + other.imaginaryPart); } /** * Returns the negative of this complex number. * * @return the negative of this complex number. */ public ComplexNumber negate() { return new ComplexNumber(-realPart, -imaginaryPart); } /** * Returns the complex number representing the product of the two input * complex numbers. * * @param a the first complex number. * @param b the second complex number. * @return the product of {@code a} and {@code b}. */ public ComplexNumber multiply(ComplexNumber complexNumber) { double a = realPart; double b = imaginaryPart; double c = complexNumber.realPart; double d = complexNumber.imaginaryPart; double resultRealPart = a * c - b * d; double resultImaginaryPart = a * d + b * c; return new ComplexNumber(resultRealPart, resultImaginaryPart); } /** * Returns a simple textual representation of this complex number. * * @return the textual representation of this complex number. */ @Override public String toString() { if (realPart == 0.0 &amp;&amp; imaginaryPart == 0.0) { return "0.0"; } if (realPart == 0.0) { return imaginaryPart + "i"; } if (imaginaryPart == 0.0) { return Double.toString(realPart); } if (imaginaryPart &lt; 0.0) { return realPart + " - " + Math.abs(imaginaryPart) + "i"; } return realPart + " + " + imaginaryPart + "i"; } /** * Checks that the input {@code double} value is not {@code NaN}. * * @param d the value to check. * @throws IllegalArgumentException in case {@code d} is {@code NaN}. */ private void checkNotNan(double d) { if (Double.isNaN(d)) { throw new IllegalArgumentException("NaN"); } } /** * Checks that the input {@code double} value is finite. * * @param d the value to check. * @throws IllegalArgumentException in case {@code d} is not finite. */ private void checkNotInfinite(double d) { if (Double.isInfinite(d)) { throw new IllegalArgumentException("Infinite"); } } } </code></pre> <p><strong><code>net.coderodde.math.impl.ComplexVectorAdditive</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.Additive; import net.coderodde.math.Vector; /** * This class implements the addition operation over complex vectors. * * @author Rodion "rodde" Efremov * @version 1.6:P (May 18, 2019) */ public final class ComplexVectorAdditive implements Additive&lt;Vector&lt;ComplexNumber&gt;, Vector&lt;ComplexNumber&gt;, Vector&lt;ComplexNumber&gt;&gt; { /** * Adds the complex vectors {@code a} and {@code b} and returns the * component-wise copy of the object. Both input complex vectors remain * intact. * * @param a the left summation operand. * @param b the right summation operand. * @return the sum vector. */ @Override public Vector&lt;ComplexNumber&gt; add(Vector&lt;ComplexNumber&gt; a, Vector&lt;ComplexNumber&gt; b) { ComplexNumber[] complexNumbers = new ComplexNumber[a.getNumberOfDimensions()]; for (int i = 0; i &lt; a.getNumberOfDimensions(); i++) { complexNumbers[i] = a.get(i).add(b.get(i)); } return new Vector&lt;&gt;(complexNumbers); } } </code></pre> <p><strong><code>net.coderodde.math.impl.ComplexVectorDivisible</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.Divisible; /** * This class implements the division operator over complex numbers. * * @author Rodion "rodde" Efremov * @version 1.6 (May 18, 2019) */ public final class ComplexVectorDivisible implements Divisible&lt;ComplexNumber, ComplexNumber, ComplexNumber&gt; { /** * Divides the complex {@code divident} by the complex {@code divisor} and * returns the fraction. Both the input complex numbers remain intact. * * @param divident the complex divident. * @param divisor the complex divisor. * @return the fraction after dividing the divident by the divisor. */ @Override public ComplexNumber divide(ComplexNumber divident, ComplexNumber divisor) { // TODO: could do Karatsuba multiplication here, I guess. double a = divident.getRealPart(); double b = divident.getImaginaryPart(); double c = divisor.getRealPart(); double d = divisor.getImaginaryPart(); double resultRealPart = (a * c + b * d) / (c * c + d * d); double resultImaginaryPart = (b * c - a * d) / (c * c + d * d); return new ComplexNumber(resultRealPart, resultImaginaryPart); } } </code></pre> <p><strong><code>net.coderodde.math.impl.ComplexVectorInnerProduct</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.InnerProduct; import net.coderodde.math.Vector; /** * This class implements computing inner product over complex vectors. * * @author Rodion "rodde" Efremov * @version 1.6 (May 18, 2019) */ public final class ComplexVectorInnerProduct implements InnerProduct&lt;ComplexNumber, ComplexNumber, ComplexNumber&gt; { /** * Computes the inner product of {@code a} and {@code b} and returns it to * the caller. * * @param a the first operand. * @param b the second operand. * @return the inner product. */ @Override public ComplexNumber innerProductOf(Vector&lt;ComplexNumber&gt; a,//1 -2i Vector&lt;ComplexNumber&gt; b) {//1 -2i ComplexNumber innerProduct = new ComplexNumber(0.0, 0.0); for (int i = 0; i &lt; a.getNumberOfDimensions(); i++) { ComplexNumber complexNumber1 = a.get(i); ComplexNumber complexNumber2 = b.get(i); ComplexNumber product = complexNumber1.multiply(complexNumber2); innerProduct = innerProduct.add(product); } return innerProduct; } } </code></pre> <p><strong><code>net.coderodde.math.impl.ComplexVectorNegative</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.Negative; import net.coderodde.math.Vector; /** * This class implements the negation operation over complex numbers. * * @author Rodino "rodde" Efremov * @version 1.6 (May 18, 2019) */ public final class ComplexVectorNegative implements Negative&lt;Vector&lt;ComplexNumber&gt;, Vector&lt;ComplexNumber&gt;&gt; { /** * Negates every component in {@code element} and returns the resulting * vector. The input vector remains intact. * * @param element the element to negate. * @return the element with all the components negated compared to the * input vector. */ @Override public Vector&lt;ComplexNumber&gt; negate(Vector&lt;ComplexNumber&gt; element) { Vector&lt;ComplexNumber&gt; result = new Vector&lt;&gt;(element); for (int i = 0; i &lt; element.getNumberOfDimensions(); i++) { result.set(i, result.get(i).negate()); } return result; } } </code></pre> <p><strong><code>net.coderodde.math.impl.ComplexVectorProductByScalar</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.Product; import net.coderodde.math.Vector; /** * This class implements multiplying complex vectors by a complex scalar. * * @author Rodion "rodde" Efremov * @version 1.6 (May 18, 2019) */ public final class ComplexVectorProductByScalar implements Product&lt;ComplexNumber, Vector&lt;ComplexNumber&gt;, Vector&lt;ComplexNumber&gt;&gt;{ /** * Multiplies the complex vector by the given complex scalar and returns the * result. All the input objects remain intact. * * @param scalar the scalar to multiply by. * @param vector the complex vector to multiply. * @return the {@code vector} multiplied by {@code scalar}. */ @Override public Vector&lt;ComplexNumber&gt; multiply(ComplexNumber scalar, Vector&lt;ComplexNumber&gt; vector) { Vector&lt;ComplexNumber&gt; ret = new Vector&lt;&gt;(vector); for (int i = 0; i &lt; vector.getNumberOfDimensions(); i++) { ret.set(i, ret.get(i).multiply(scalar)); } return ret; } } </code></pre> <p><strong><code>net.coderodde.math.impl.RealVectorAdditive</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.Additive; import net.coderodde.math.Vector; /** * This class implements addition over {@code double}-valued vectors of an * Euclidean space. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public final class RealVectorAdditive implements Additive&lt;Vector&lt;Double&gt;, Vector&lt;Double&gt;, Vector&lt;Double&gt;&gt; { /** * Adds component-wise the contents in {@code a} and {@code b} and returns * the sum. Both input vectors remain intact. * * @param a the first operand. * @param b the second operand. * @return the sum of the two input operands. */ @Override public Vector&lt;Double&gt; add(Vector&lt;Double&gt; a, Vector&lt;Double&gt; b) { Vector&lt;Double&gt; result = new Vector&lt;&gt;(a); for (int i = 0; i &lt; a.getNumberOfDimensions(); i++) { result.set(i, result.get(i) + b.get(i)); } return result; } } </code></pre> <p><strong><code>net.coderodde.math.impl.RealVectorDivisible</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.Divisible; /** * This class implements the division of {@code double} values. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public final class RealVectorDivisible implements Divisible&lt;Double, Double, Double&gt; { /** * Returns the fraction of {@code divident} and {@code divisor}. * * @param divident the divident {@code double} value. * @param divisor the divisor {@code double} value. * @return the fraction. */ @Override public Double divide(Double divident, Double divisor) { return divident / divisor; } } </code></pre> <p><strong><code>net.coderodde.math.impl.RealVectorInnerProduct</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.InnerProduct; import net.coderodde.math.Vector; /** * This class is responsible for computing inner products over real-valued * vectors. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public final class RealVectorInnerProduct implements InnerProduct&lt;Double, Double, Double&gt; { /** * Computes and returns the inner product of the vectors {@code a} and * {@code b}. * * @param a the left operand vector. * @param b the right operand vector. * @return the inner product of the vectors {@code a} and {@code b}. */ @Override public Double innerProductOf(Vector&lt;Double&gt; a, Vector&lt;Double&gt; b) { double innerProduct = 0.0; for (int i = 0; i &lt; a.getNumberOfDimensions(); i++) { innerProduct += a.get(i) * b.get(i); } return innerProduct; } } </code></pre> <p><strong><code>net.coderodde.math.impl.RealVectorNegative</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.Negative; import net.coderodde.math.Vector; /** * This class implements negation operation over real vectors. * * @author Rodion "rodde" Efremov * @version 1.6 (May 17, 2019) */ public final class RealVectorNegative implements Negative&lt;Vector&lt;Double&gt;, Vector&lt;Double&gt;&gt; { /** * Negates the input {@code double} vector. The input vector remains intact. * * @param a the {@code double} vector to negate. * @return the negative of {@code a}. */ @Override public Vector&lt;Double&gt; negate(Vector&lt;Double&gt; a) { Vector&lt;Double&gt; result = new Vector&lt;&gt;(a); for (int i = 0; i &lt; result.getNumberOfDimensions(); i++) { result.set(i, -result.get(i)); } return result; } } </code></pre> <p><strong><code>net.coderodde.math.impl.RealVectorProductByScalar</code></strong></p> <pre><code>package net.coderodde.math.impl; import net.coderodde.math.Product; import net.coderodde.math.Vector; /** * This class implements the operation of multiplying a vector by a scalar. * * @author Rodion "rodde" Efremov * @version 1.6 (May 18, 2019) */ public final class RealVectorProductByScalar implements Product&lt;Double, Vector&lt;Double&gt;, Vector&lt;Double&gt;&gt; { /** * This method multiplies the input vector {@code vector} component-wise by * the {@code double} scalar and returns the result. The input vector * remains intact. * * @param scalar the scalar. * @param vector the vector to multiply by the scalar. * @return the input vector multiplied by the input scalar. */ @Override public Vector&lt;Double&gt; multiply(Double scalar, Vector&lt;Double&gt; vector) { Vector&lt;Double&gt; x = new Vector&lt;&gt;(vector); for (int i = 0; i &lt; vector.getNumberOfDimensions(); i++) { x.set(i, x.get(i) * scalar); } return x; } } </code></pre> <p><strong><code>net.coderodde.math.GramSchmidtProcessTest</code></strong></p> <pre><code>package net.coderodde.math; import net.coderodde.math.impl.RealVectorAdditive; import net.coderodde.math.impl.RealVectorDivisible; import net.coderodde.math.impl.RealVectorInnerProduct; import net.coderodde.math.impl.RealVectorNegative; import net.coderodde.math.impl.RealVectorProductByScalar; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class GramSchmidtProcessTest { private final GramSchmidtProcess&lt;Double, Double, Double&gt; process = new GramSchmidtProcess&lt;&gt;(new RealVectorInnerProduct(), new RealVectorDivisible(), new RealVectorProductByScalar(), new RealVectorAdditive(), new RealVectorNegative()); @Test(expected = NullPointerException.class) public void testThrowsNullPointerExceptionOnNullBasis() { process.process(null); } @Test(expected = IllegalArgumentException.class) public void testThrowsIllegalArgumentExceptionOnNoVectors() { process.process(); } @Test public void testReturnsSingleVectorWhenBasisContainsOnlyOneVector() { Vector&lt;Double&gt; vec = new Vector&lt;&gt;(1.0, 2.2, 3.0); Vector&lt;Double&gt;[] result = process.process(vec); assertEquals(1, result.length); assertEquals(vec, result[0]); } @Test(expected = IllegalArgumentException.class) public void testThrowsIllegalArgumentExceptionWhenFirstVectorHasDimensionZero() { Vector&lt;Double&gt; v1 = new Vector&lt;&gt;(); Vector&lt;Double&gt; v2 = new Vector&lt;&gt;(1.0); process.process(v1, v2); } @Test(expected = IllegalArgumentException.class) public void testThrowsIllegalArgumentExceptionWhenAnotherVectorHasDimensionZero() { Vector&lt;Double&gt; v1 = new Vector&lt;&gt;(1.0); Vector&lt;Double&gt; v2 = new Vector&lt;&gt;(); process.process(v1, v2); } @Test(expected = IllegalArgumentException.class) public void testThrowsIllegalArgumentExceptionWhenDimensionalityMismatch() { Vector&lt;Double&gt; v1 = new Vector&lt;&gt;(1.0); Vector&lt;Double&gt; v2 = new Vector&lt;&gt;(2.0, 3.0); process.process(v1, v2); } @Test public void testValidInput1() { Vector&lt;Double&gt; v1 = new Vector&lt;&gt;(1., 1., 1.); Vector&lt;Double&gt; v2 = new Vector&lt;&gt;(1., 0., 1.); Vector&lt;Double&gt; v3 = new Vector&lt;&gt;(3., 2., 3.); Vector&lt;Double&gt;[] orthogonalBasis = process.process(v1, v2, v3); assertTrue(Demo.basisIsOrthogonal(orthogonalBasis, 0.001)); } } </code></pre> <p>(The entire project is <a href="https://github.com/coderodde/GramSchmidtProcess/tree/fcf503f84af72691e8130fbf3692cf4bbab41479" rel="nofollow noreferrer">here</a>.)</p> <p><strong>Critique request</strong></p> <p>As always, please tell me anything that comes to mind!</p>
[]
[ { "body": "<p>The way the problem is decomposed doesn't feel right. In particular, there are too many interfaces, and <code>Additive</code>, <code>Divisible</code>, <code>Negative</code> are unnecessarily disconnected.</p>\n\n<p>I recommend to follow a more (mathematically) natural path. The Gram-Schmidt process works in any inner product space (which is by definition a vector space equipped with an inner product), so consider an</p>\n\n<pre><code> abstract class InnerProductSpace &lt;AbelianGroup&lt;V&gt;, Field&lt;F&gt;&gt; {\n V scale(V vector, F scalar);\n F innerProduct(V v1, V v2);\n V[] orthogonalize(V[] basis) {\n // your Gram-Schmidt implementation here\n }\n }\n</code></pre>\n\n<p>As a side note, I wouldn't call an orthogonalization method <code>GramShmidt</code>. As a client of this library I am not concerned with which process is used. The only thing I care about is that there is the method taking a basis and returning an orthogonalized one.</p>\n\n<p>I also took a liberty to make a shortcut and not spell out the VectorSpace interface, to which a <code>scale</code> method really belongs.</p>\n\n<p>The <code>Field</code> is what holds addition and multiplication together:</p>\n\n<pre><code> public interface Field&lt;F&gt; {\n F add(F f1, F f2);\n F mul(F f1, F f2);\n F neg(F f);\n F inv(F f);\n }\n</code></pre>\n\n<p>It is OK to have <code>sub</code> and <code>div</code> instead of <code>neg</code> and <code>inv</code>.</p>\n\n<p>Notice that the field <em>must</em> be closed under its operation. An addition (or multiplication) returning a type different than the type of arguments makes no mathematical sense.</p>\n\n<p>I have to admit that I have no idea how to express other constraints a.k.a. field axioms. I doubt that it is possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T05:03:03.780", "Id": "220605", "ParentId": "220497", "Score": "5" } }, { "body": "<p>My Linear Algebra is a bit rusty, but I think that your terminology is a bit off:</p>\n\n<blockquote>\n<pre><code>public class GramSchmidtProcess&lt;VCT, IPT, FT&gt; {\n …\n\n /**\n * Performs the Gram-Schmidt process upon {@code basis}.\n * \n * @param basis the basis to process.\n * @return the orthogonal basis.\n */\n public Vector&lt;VCT&gt;[] process(Vector&lt;VCT&gt;... basis) {\n …\n\n // Remove the duplicates and return whatever is left:\n return removeDuplicates(orthogonalBasis);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>If the input is in fact a <a href=\"https://en.wikipedia.org/wiki/Basis_%28linear_algebra%29\" rel=\"nofollow noreferrer\">basis</a>, then the vectors are, by definition, linearly independent and spanning. If the inputs are linearly independent, how would it be possible to produce duplicate vectors in the output?</p>\n\n<p>The Wikipedia article says:</p>\n\n<blockquote>\n <p>If the Gram–Schmidt process is applied to a linearly dependent sequence, it outputs the <b>0</b> vector on the <i>i</i>th step, assuming that <b>v</b><sub><i>i</i></sub> is a linear combination of <b>v</b><sub>1</sub>, …, <b>v</b><sub><em>i</em>−1</sub>. If an orthonormal basis is to be produced, then the algorithm should test for zero vectors in the output and discard them because no multiple of a zero vector can have a length of 1.</p>\n</blockquote>\n\n<p>Perhaps you are prepared to accept as input a list of vectors that do not necessarily constitute a basis? In that case, the <code>basis</code> parameter should be renamed to something more general, such as <code>vectors</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T05:43:16.733", "Id": "220696", "ParentId": "220497", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T04:21:36.950", "Id": "220497", "Score": "3", "Tags": [ "java", "algorithm", "mathematics", "coordinate-system" ], "Title": "Gram-Schmidt process in Java for computing independent bases in linear spaces" }
220497
<p>I'm writing a torrent streaming client. The plan is to wrap WebTorrent-cli and provide a Java interface to observe download state, cancel or pause downloads etc.</p> <p>Anyways, I came up with the following <code>DownloadManagerImpl</code>. I want the instances to this class be immutable, strictly enough that they remain thread safe if accessed from multiple threads. I'm using the builder pattern to create instances of <code>DownloadManagerImpl</code> as more fields can be added in the future. I would like to avoid any repetitions of fields. Really sorry for posting the partly documented (and yet unfinished:)) code, but here it is:</p> <pre><code>package hyena.dmanager; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.Executor; import java.nio.file.Path; import java.nio.file.Paths; /** * Default implementation for DownloadManager. * * @author Devashish Jaiswal * @see hyena.dmanager.DownloadManager */ public final class DownloadManagerImpl implements DownloadManager { private transient Executor exec; /** * Absolute path of the directory where files will be saved, * excluding the file name. */ @SerializedName(JsonKey.SAVE_LOCATION) private Path mSaveTo; /** Magnet URL of the torrent. */ @SerializedName(JsonKey.MAGNET_URL) private String mMagnetUrl; /** * Absolute path to vlc media player's install location. User * assistance might be required for this field. */ @SerializedName(JsonKey.VLC_PATH) private Path mVlcPath; /** * WebTorrent has this tendency to hang in-between downloads if * the network is slow. On these situations, we kill this instance * of the downloader, save download state and compose a new task that * loads the state and resumes download. */ @SerializedName(JsonKey.RESUME_TIMEOUT) private int mResumeAfterInactiveSeconds; /** * The index of the file to be downloaded in a multi-file torrent. * Set it to -ve if all files have to be downloaded, or if torrent * contains only a single file. */ @SerializedName(JsonKey.FILE_INDEX) private int mFileIndex; private DownloadManagerImpl(){} @Override public void start() { } @Override public ProgressState getProgressState() { return null; } public String exportStateJson () { return new Gson().toJson(this); } private class JsonKey { static final String MAGNET_URL = "magent_url"; static final String RESUME_TIMEOUT = "inactivity_resume_timeout"; static final String SAVE_LOCATION = "save_location"; static final String VLC_PATH = "vlc_path"; static final String FILE_INDEX = "file_index"; } public static class Builder { private boolean isCompositionComplete; private final DownloadManagerImpl mManager; public Builder () { isCompositionComplete = false; mManager = new DownloadManagerImpl(); mManager.exec = new DefaultExecutor(); } private synchronized boolean canModify() { if (isCompositionComplete) { // [TODO: Log the event or throw exception or do both] return false; } return true; } public Builder setSaveLocation (String absolutePath) { if (canModify()) { mManager.mSaveTo = Paths.get(absolutePath); } return this; } public Builder setMagnetUrl (String magnetUrl) { if (canModify()) { mManager.mMagnetUrl = magnetUrl; } return this; } public Builder setVlcPath (String absolutePath) { if (canModify()) { mManager.mVlcPath = Paths.get(absolutePath); } return this; } public Builder setInactivityResumeTimeout (int seconds) { if (canModify()) { mManager.mResumeAfterInactiveSeconds = seconds; } return this; } public Builder setFileIndex (int fileIndex) { if (canModify()) { mManager.mFileIndex = fileIndex; } return this; } public synchronized DownloadManager build () { isCompositionComplete = true; return mManager; } } public static DownloadManager buildFromState (String json) { JsonParser parser = new JsonParser(); JsonObject stateObject = parser.parse(json).getAsJsonObject(); return new DownloadManagerImpl.Builder() .setMagnetUrl(stateObject.get(JsonKey.MAGNET_URL).getAsString()) .setInactivityResumeTimeout(stateObject.get(JsonKey.RESUME_TIMEOUT).getAsInt()) .setSaveLocation(stateObject.get(JsonKey.SAVE_LOCATION).getAsString()) .setVlcPath(stateObject.get(JsonKey.VLC_PATH).getAsString()) .setFileIndex(stateObject.get(JsonKey.FILE_INDEX).getAsInt()) .build(); } } </code></pre> <p>I highly appreciate you taking the time to review my code.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T06:20:09.273", "Id": "220501", "Score": "1", "Tags": [ "java", "design-patterns", "thread-safety", "immutability" ], "Title": "Near immutable, thread safe Builder" }
220501
<p>i've been working on an implementation of a my own from scratch set of library <a href="https://github.com/thenameless314159/Astron" rel="noreferrer">Astron</a> and I wanted to get my TPL usage reviewed because i'm not confident with this technology :/</p> <p>My app is currently unpacking .d2p files, which is a custom file format from a french game called Dofus, it's simply an archive of others inflated archives of another custom file format .dlm. Here is the current output of my app :</p> <p><a href="https://i.stack.imgur.com/QIiS5.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/QIiS5.gif" alt="application output"></a> The progress bars came <a href="https://github.com/goblinfactory/konsole" rel="noreferrer">from here</a>.</p> <p>So everything seems to works as expected, files are processes concurrently, 308mo of .dlm files are parsed deflated in 10sec, that is exactly what i wants it to do but i may have misused the TPL. The full project can be <a href="https://github.com/thenameless314159/Astron.Unpacker" rel="noreferrer">found at this address</a>, but the portion of code I want to get reviewed is from <code>src/Astron.Unpacker/Managers/D2PManager.cs</code> :</p> <pre><code>public class D2PManager : BaseFileManager { private readonly ILogger _logger; private readonly string _dlmFilesFolder; public D2PManager(IContainer container) : base(container) { _logger = ServiceLocator.Logger; _dlmFilesFolder = container.GetInstance&lt;Settings&gt;().DlmOutputFolder; } public async Task UnpackAll(string[] filesPath) { _logger.Log&lt;D2PManager&gt;(LogLevel.Info, $"Attempting to unpack {filesPath.Length} d2p files..."); var tasks = new List&lt;Task&gt;(filesPath.Length); tasks.AddRange(filesPath.Select(d2PFilePath =&gt; UnpackD2PFile(d2PFilePath))); await Task.WhenAll(tasks).ConfigureAwait(false); } public async Task UnpackD2PFile(string path) { var d2PFile = new FileAccessor(path); var metaUnpacker = new D2PFileMetadataUnpacker(_binaryFactory, _serDes); metaUnpacker.Unpack(d2PFile); var archiveUnpacker = new DlmArchivesUnpacker(_binaryFactory, _serDes, metaUnpacker.Value); archiveUnpacker.Unpack(d2PFile); var progressCount = 1; var progressBar = new ProgressBar(PbStyle.SingleLine, archiveUnpacker.Values.Count); progressBar.Refresh(0, Path.GetFileName(d2PFile.FullPath)); await Task.Delay(10); // doesn't print all either way foreach (var archive in archiveUnpacker.Values) { var filePath = (_dlmFilesFolder + archive.RelativePath).Replace('/', '\\'); var fileDirectory = Path.GetDirectoryName(filePath); using var decompressedData = new MemoryStream(); using var deflatedStream = new DeflateStream(new MemoryStream(archive.CompressedData), CompressionMode.Decompress); await deflatedStream.CopyToAsync(decompressedData); if (!Directory.Exists(fileDirectory)) Directory.CreateDirectory(fileDirectory); File.WriteAllBytes(filePath, decompressedData.GetBuffer()); progressBar.Refresh(progressCount, filePath); progressCount++; } } } </code></pre> <p>Here are my questions :</p> <ul> <li>If I don't add the <code>Task.Delay()</code> right after the processbar initialization, the files seems to be processed synchronously (the progress bar show up when the last completed), why does it happen ?</li> <li>Is it right to use <code>.ConfigureAwait(false)</code> on <code>Task.WhenAll()</code> ?</li> <li>Am I starting every tasks the right way ? Shouldn't I use <code>Task.Run()</code> instead with <code>Task.WaitAll()</code> ?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T07:47:08.563", "Id": "426033", "Score": "0", "body": "At first glance, I would say remove the ConfigureAwait(false) and await Task.Delay(10) and see what happens..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T08:09:19.930", "Id": "426036", "Score": "0", "body": "I would replace your current `Task.WhenAll` with `Parallel.ForEach(filesPath, ...)` and let the framework create and handle the concurrency or alternatively `filesPath.AsParallel()...` btw, you are not disposing any streams." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T08:16:41.817", "Id": "426037", "Score": "0", "body": "@dfhwze without the task.delay files are processed synchronously according to this output: https://i.imgur.com/24O9ZzX.gif as I said on the question, why should I remove the configure await ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T08:17:44.373", "Id": "426039", "Score": "0", "body": "@t3chb0t yeah i was doing this before but Parallel foreach doesn't ensure that everything will be processed concurrently, thank you for the not disposed streams, i didn't noticed that, thanks to C#8 i just have to add using before the var definition :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T08:26:14.260", "Id": "426040", "Score": "0", "body": "`async Task` requires an `await`, if there is nothing else you can `await` then I think you should `return Task.CompltetedTask.` and use `Task.Factory.StartNew (() => )` to call this method... but I looked through your repository and you could add some awaitable methods to make it _naturally_ awaitable but this would require changing a lot of other APIs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T08:29:20.070", "Id": "426041", "Score": "0", "body": "Hum, i've modified my code with the Parallel.Foreach(), because before i wasn't using the progress bar to show the progression and it provide me this output : https://i.imgur.com/aWvISMv.gif with parsing in under 8 sec, which is better but the behavior is different, each tasks doesn't start at the same moment, but this is not really a problem" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T08:42:18.017", "Id": "426042", "Score": "0", "body": "@NamelessK1NG replace the AddRange with tasks.AddRange(filesPath.Select(async d2PFilePath => await Task.Run(() => UnpackD2PFile(d2PFilePath)))); and remove the Delay. It should work now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T08:47:48.257", "Id": "426043", "Score": "0", "body": "@dfhwze That way it have the same behavior as the Parallel.ForEach() and provide the same output !\nThank you very much both of you now I undestand a little bit more how the TPL shoud be used and when. I'll use the parallel foreach to keep a synchronous API" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T08:49:18.480", "Id": "426044", "Score": "0", "body": "@NamelessK1NG just out of curiousity, which one is the faster; the Task or Parallel approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T08:50:43.950", "Id": "426045", "Score": "0", "body": "They do it both in 8 seconds with the different approach but everything is implemented using my own from scratch library Astron so it may be better with something that have been benched and optimized ^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T09:06:30.157", "Id": "426046", "Score": "0", "body": "@NamelessK1NG Perhaps you could answer your own question for future readers to get a nice overview. I have noticed several posts about Task vs Parallel. This is a very good example of such a problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T09:22:26.073", "Id": "426047", "Score": "0", "body": "@dfhwze Sure, i'll do the post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:18:09.993", "Id": "426173", "Score": "0", "body": "The `Directory.Exists` call may be safely removed. From the docs on `CreateDirectory`, \"Creates all directories and subdirectories in the specified path *unless they already exist*.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T15:29:59.197", "Id": "426197", "Score": "0", "body": "I didn't noticed that then I should look more attentively at the BCL doc, thank you !" } ]
[ { "body": "<p>As seen with @t3chb0t and @dfhwze I have been misusing the TPL. I also don't see any point on <code>.ConfigureAwait(false)</code> a <code>Task.WhenAll()</code> call, also with the <em>async all-the-way</em> rule, using an awaitable task for this case would have me to convert many of my APIs to async one.</p>\n\n<p>So they provided me these solutions :</p>\n\n<ul>\n<li>Modifiy my task creation logic this way : <code>tasks.AddRange(filesPath.Select(async d2PFilePath =&gt; await Task.Run(() =&gt; UnpackD2PFile(d2PFilePath))));</code> and removing the <code>Task.Delay(10);</code> on my <code>UnpackD2PFile(string path)</code> task</li>\n<li>Use the <code>Parallel.Foreach()</code> loop to let the framework create and handle the concurrency and also allow me to keep a synchronous API</li>\n</ul>\n\n<p>Both of these solutions completed the work in the same time, and provided this output :</p>\n\n<p><a href=\"https://i.stack.imgur.com/9kMHd.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9kMHd.gif\" alt=\"new application output\"></a></p>\n\n<p>As you can see now the behavior is quite different than before, not every task start at the same moment, also now there is a delay before every progress bars shown up. But we gained almost 2sec on the total execution time :)</p>\n\n<p><strong>I highly recommend to use the Parallel approach as it is the easiest one to implement.</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T09:36:34.140", "Id": "220505", "ParentId": "220504", "Score": "6" } } ]
{ "AcceptedAnswerId": "220505", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T07:33:13.587", "Id": "220504", "Score": "7", "Tags": [ "c#", "comparative-review", "file", "task-parallel-library", ".net-core" ], "Title": "Usage of TPL vs Parallel.ForEach() on file processing" }
220504
<p>I made a postfix calculator in Java.</p> <p>The code performs the functions I planned without problems, However, I'm not satisfied with it, because it's too verbose and I couldn't split it up into methods properly, especially <code>PostfixCalculator.changeNotation()</code>.</p> <p>Any help would be greatly appreciated.</p> <hr> <p>Main.java</p> <pre class="lang-java prettyprint-override"><code> public class Main { public static void main(String[] args) { PostfixCalculator postCalc = new PostfixCalculator(); } } </code></pre> <p>Stack.java (I didn't use the library because I'm studying data structures.)</p> <pre><code>import java.util.ArrayList; import java.util.Scanner; public class Stack { Scanner scan = null; public ArrayList&lt;String&gt; stack; public Stack() { scan = new Scanner(System.in); stack = new ArrayList&lt;String&gt;(); } public boolean isEmpty() { if (stack.size() == 0) { return true; } else { return false; } } public void push(String element) { stack.add(element); } public void pop() { if(stack.isEmpty()) { return; } else { stack.remove(stack.size()-1); } } public int size() { return stack.size(); } public String peek() { if (stack.isEmpty()) { return null; } else { return stack.get(stack.size() - 1); } } } </code></pre> <p>PostfixCalculator.java</p> <pre><code>import java.util.ArrayList; import java.util.Scanner; public class PostfixCalculator { String[] infixNotation = null; String postfixNotation = ""; ArrayList&lt;String&gt; aListPostfixNotation = null; Scanner scan = null; Stack stk = null; public PostfixCalculator() { aListPostfixNotation = new ArrayList&lt;String&gt;(); stk = new Stack(); scan = new Scanner(System.in); String myInput = scan.nextLine(); infixNotation = myInput.split("",0); postfixCalculate(changeNotation()); } public String changeNotation() // Change the entered code from infixnotation to postfixnotation { for (int i = 0; i &lt; infixNotation.length; i++) { if(infixNotation[i].equals(" ")) { continue; } else if( !infixNotation[i].equals("+") &amp;&amp; // when infixNotation[i] is operand !infixNotation[i].equals("-") &amp;&amp; !infixNotation[i].equals("*") &amp;&amp; !infixNotation[i].equals("/") &amp;&amp; !infixNotation[i].equals("(") &amp;&amp; !infixNotation[i].equals(")") ) { postfixNotation = postfixNotation + infixNotation[i]; } else // when infixNotation[i] is operator or bracket { if(stk.isEmpty()) // It can push()ed, when stack is empty // Don't care ")~~~", because the ")" can't be first char { stk.push(infixNotation[i]); } else { if (infixNotation[i].equals("(")) // Just push() when it's '(' { stk.push(infixNotation[i]); } else if (infixNotation[i].equals(")")) // When bracket is balanced (left and right), pop() a pair of bracket { stk.push(infixNotation[i]); whenRightPush(); } else // Have to the priority, when infixNotation[i] is operator { if (stk.peek().equals("(")) { stk.push(infixNotation[i]); } else { if ( infixNotation[i].equals("*") || infixNotation[i].equals("/") ) { if ( stk.peek().equals("+") || stk.peek().equals("-") ) { stk.push(infixNotation[i]); } else if ( stk.peek().equals("*") || stk.peek().equals("/") ) { postfixNotation = postfixNotation + stk.peek(); stk.pop(); stk.push(infixNotation[i]); } } else if ( infixNotation[i].equals("+") || infixNotation[i].equals("-") ) { if ( stk.peek().equals("+") || stk.peek().equals("-")) // Equal level's operators can't enter the stack twice sequentially, // so they need to be considered only once. { postfixNotation = postfixNotation + stk.peek(); stk.pop(); stk.push(infixNotation[i]); } else if ( stk.peek().equals("*") || stk.peek().equals("/") ) { postfixNotation = postfixNotation + stk.peek(); stk.pop(); if ( stk.peek().equals("+") || stk.peek().equals("-") ) // ex + * - { postfixNotation = postfixNotation + stk.peek(); stk.pop(); } stk.push(infixNotation[i]); } } } } } } if (i == infixNotation.length-1) // All elements is pop()ed, when 'i' have last value { while(!stk.isEmpty()) { if(stk.peek().equals("(")) { stk.pop(); } else if (stk.peek().equals(")")) { stk.pop(); } else { postfixNotation = postfixNotation + stk.peek(); stk.pop(); } } } } System.out.println(postfixNotation); return postfixNotation; } public void whenRightPush() // This method will work when ')' is push()ed // I can't find proper name for this method { stk.pop(); while(true) { if ( stk.peek().equals("(") ) { stk.pop(); break; } else // 연산자일 경우 후위표기식 문자열에 붙인 후 pop() { postfixNotation = postfixNotation + stk.peek(); stk.pop(); } } } public void postfixCalculate(String postNotation) // Calculate the postfixnotation { int operatorCount = 0; int resultTemp = 0; String[] arrayPostfixNotation = postNotation.split("", 0); for (String str : arrayPostfixNotation) { aListPostfixNotation.add(str); } for (String str : aListPostfixNotation) { if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")) { operatorCount++; } } while(operatorCount &gt; 0) { for(int i = 0; i &lt; aListPostfixNotation.size(); i++) { if (aListPostfixNotation.get(i).equals("+") || aListPostfixNotation.get(i).equals("-") || aListPostfixNotation.get(i).equals("*") || aListPostfixNotation.get(i).equals("/")) { if(aListPostfixNotation.get(i).equals("+")) { resultTemp = Integer.parseInt(aListPostfixNotation.get(i-2)) + Integer.parseInt(aListPostfixNotation.get(i-1)); } else if(aListPostfixNotation.get(i).equals("-")) { resultTemp = Integer.parseInt(aListPostfixNotation.get(i-2)) - Integer.parseInt(aListPostfixNotation.get(i-1)); } else if(aListPostfixNotation.get(i).equals("*")) { resultTemp = Integer.parseInt(aListPostfixNotation.get(i-2)) * Integer.parseInt(aListPostfixNotation.get(i-1)); } else { resultTemp = Integer.parseInt(aListPostfixNotation.get(i-2)) / Integer.parseInt(aListPostfixNotation.get(i-1)); } aListPostfixNotation.remove(i-2); // Remove the used operator and operand aListPostfixNotation.remove(i-2); aListPostfixNotation.remove(i-2); aListPostfixNotation.add(i-2, Integer.toString(resultTemp)); // Add the result of operation into the arraylist operatorCount--; break; } } } System.out.println(resultTemp); } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>I didn't go over all the code. Here are my comments so far:</p>\n\n<h2>Stack</h2>\n\n<ol>\n<li><p>The class contains a <code>Scanner</code> for no apparent reason.</p></li>\n<li><p>While it is <em>your</em> implementation, which does not implement the interface from the JDK, you should be aware that in the \"standard\" contract for Stack, (in Java as in other programming languages) the <code>pop()</code> method returns the removed item. (making <code>peek</code>ing sometimes redundant)</p></li>\n<li><p>any reason why your Stack isn't generic? it's good practice...</p></li>\n</ol>\n\n<h2>PostfixCalculator</h2>\n\n<ol>\n<li><p>This class violates the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">single responsibility principle</a>. besides doing what it is supposed to do (all the arithmetic calculation), It also receives input from the user, parses it and outputs the result. so your calculator cannot be used in a web app or mobile device because it can only receive input and emit output from/to the console. Your calculator should receive and return a <code>String</code> (or possible return an <code>int</code> or <code>float</code>) and let the caller worry about how to get the input and where to display the output. </p></li>\n<li><p>The constructor - it does everything. in fact, while there are other public methods, the constructor is the only interface that is used by whoever uses this Calculator, as can be seen by Main. this design poses three problems: 1) it's counter-intuitive. 2) there is no way to reuse the same instance to do multiple calculations and 3) yet another violation of the single responsibility principle. a constructor should only set up the state (instance variables) of the instance. any operation or action should be done by different methods.</p></li>\n<li><p>avoid literals. the parenthesis and operators should be defined once. either as <code>public static final</code> constants or better yet, as enum. putting then in an enum has the advantage that you can assign \"properties\" to the values, like precedence.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T05:27:54.863", "Id": "426117", "Score": "0", "body": "Thanks a lot. Although I can't understand some parts of your advice, I will continue my studies based on your advice and try to understand your advice that I couldn't understand. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T14:44:14.823", "Id": "220513", "ParentId": "220506", "Score": "5" } }, { "body": "<p>Here are a few potential things that could be changed:</p>\n\n<p><strong>Stack.java</strong></p>\n\n<p>The <code>isEmpty()</code> method can be simplified, since your underlying data structure that you are using to implement a stack also exposes this method:</p>\n\n<pre><code>public boolean isEmpty()\n{\n return stack.isEmpty();\n}\n</code></pre>\n\n<p>In Java, <code>pop()</code> generally returns the element that was popped, while here it simply removes the element. This necessitates a <code>peek()</code> + <code>pop()</code> combination, where the convention is just <code>pop()</code>. There is nothing really wrong with your approach, so this is just a matter of convention.</p>\n\n<p>One thing though, <code>pop()</code> simply returns when the stack is empty - so there is no direct indication that the operation failed. That is, if the stack is misused, it does not directly indicate it, either using some kind of Exception or by returning false on failure. Generally, <code>pop()</code> \"convention\" in Java would throw an Exception on an empty stack.</p>\n\n<pre><code>public String pop() throws StackException\n{\n if(isEmpty())\n throw new StackException(\"pop on empty stack\");\n\n return stack.remove(stack.size() - 1);\n}\n\n</code></pre>\n\n<p><strong>Main.java</strong> and <strong>PostfixCalculator.java</strong></p>\n\n<p>Moving the I/O work from PostfixCalculator class to your Main class. Ideally, the PostfixCalculator should only perform calculations and postfix related operations - getting the data to pass to it should be done elsewhere.</p>\n\n<p>Therefore, the <code>changeNotation()</code> method could be modified to take in a String as input, rather than obtaining it itself, which ties the class to a particular input method. Deciding to read from a file or from the network rather than Standard Input should not trigger changes to the PostfixCalculator.</p>\n\n<pre><code>public String changeNotation(String infix) { ... }\n</code></pre>\n\n<p>In addition, it is also possible to make these methods static, since you don't really need to save any state: the calculator simply takes in an input and returns an output.</p>\n\n<p>Within <code>changeNotation()</code>:</p>\n\n<pre><code>for(int i = 0; i &lt; infixNotation.length; i++)\n{\n ...\n}\n</code></pre>\n\n<p>A local variable can be introduced, since there are quite a lot of references to <code>infixNotation[i]</code> within the loop body, so this can be cleaned up. </p>\n\n<p>There is one point where 'i' is referenced in the code, so converting to a for-each loop would require maintaining a counter, which is why just introducing a local variable would be better here.</p>\n\n<pre><code>for(int i = 0; i &lt; infixNotation.length; i++)\n{\n /* 's' could be changed to something more representative */\n String s = infixNotation[i];\n\n if(s.equals(\" \"))\n continue;\n\n ...\n}\n</code></pre>\n\n<p>There is also quite a bit of if-else nesting, which makes the code a bit harder to follow:</p>\n\n<pre><code>for(int i = 0; i &lt; infixNotation.length; i++)\n{\n if(infixNotation[i].equals(\" \"))\n {\n continue;\n }\n else if(!infixNotation[i].equals(\"+\") &amp;&amp; /* other conditions here */)\n {\n ...\n }\n else { ... } \n\n ...\n}\n</code></pre>\n\n<p>The <code>else if</code> isn't needed here, since the if-body's control flow will go back to the loop header check and cannot fallthrough. Therefore, it's fine to have that <code>else if</code> just be an <code>if</code>.</p>\n\n<p>Towards the end of the method:</p>\n\n<pre><code>System.out.println(postfixNotation);\nreturn postfixNotation; \n</code></pre>\n\n<p>I'm not sure whether the calculator should print to standard out, or do any I/O for that matter. Just return the result, and let the caller (in this case, main) to do what it wants, e.g. print to standard out, log to a file, etc.</p>\n\n<p>As stated before, the I/O work should probably be moved to main.</p>\n\n<pre><code>public class Main\n{\n public static void main(String[] args)\n {\n /* \n * Obviously, the user-interaction (printing a prompt, etc.) presented\n * here can be greatly improved upon :)\n */\n Scanner scan = new Scanner(System.in);\n String infix = scan.nextLine();\n\n PostfixCalculator calc = new PostfixCalculator();\n String postfix = calc.changeNotation(infix);\n System.out.println(postfix);\n\n /* or if using static methods */\n String postfix = PostfixCalculator.changeNotation(infix);\n System.out.println(postfix);\n }\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T05:29:32.950", "Id": "426119", "Score": "0", "body": "most of this is a duplicate of my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T05:31:46.753", "Id": "426120", "Score": "0", "body": "I really appreciate your advice. I'll try to understand and implement based on your codes, although I can't understand right now. I guess It'll be great help to improve me. Thank you :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T05:35:19.453", "Id": "426121", "Score": "0", "body": "Oh, really? I'll analyze each answer in detail as i understand. Although each answer is similar, I really thank you all of you!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T20:36:36.890", "Id": "220526", "ParentId": "220506", "Score": "-1" } }, { "body": "<p>Welcome to codereview.se and thanks for sharing your code.</p>\n\n<h2>Constructors</h2>\n\n<p>As Mentioned by @SharonBenAsher a constructor should only set up the state (instance variables) of the instance.</p>\n\n<p>This implicitly excludes calling any methods on the arguments passed and the use of the <code>new</code> keyword. \nA constructor should only have assignments of parameters to instance variables.</p>\n\n<p>The dependencies should be instantiates <em>before</em> calling the constructor.\nBut this only applies for <em>dependencies</em>, that is: classes that provide <em>additional logic</em>.\nThe class <code>ArrayList</code> does not apply to that.\nIt is a <em>data structure</em> something to hold and organize <em>data</em>.\nBut it should be created at the variable declaration:</p>\n\n<pre><code>public class Stack \n{\n Scanner scan;\n public ArrayList&lt;String&gt; stack = new ArrayList&lt;String&gt;();\n\n public Stack(Scanner scan) \n {\n this.scan = scan; // I also doubt that the scanner is needed here at all.\n }\n</code></pre>\n\n<p>When following the other answers suggestions (extract user IO out of this class, explicitly call the method doing the logic) both of your classes en up with <em>default constructors</em> (having no arguments and doing nothing) which you don't even need to write at all.</p>\n\n<h2>visibility scopes</h2>\n\n<p>Most of your instance variables have no visibility key word which makes them <code>package private</code> (that is: accessible by other classes in same package) or are declared to be <code>public</code>.\nThis violates the <em>information hiding/encapsulation</em> paradigm of object oriented programming.\nAlways restrict the visibility to the least necessary scope. \nFor instance variables should almost ever be declared <code>private</code> (and there should be no <em>getter/setter</em>).</p>\n\n<p>The same applies to methods. \nA class should have one <code>public</code> method as <em>entry point</em> for a service.\nThis methods may call other methods in the same class but this other methods should be <code>private</code>.</p>\n\n<h2>avoid state</h2>\n\n<p>Your PostfixCalculator uses an <em>instance variable</em> (<code>infixNotation</code>) to accumulate the result. \nThis is called a <em>mutable state</em>.\nMutable state limits the re-usability of an object.\nThat is: each time you need an object of this class you have to create a new instance (using the <code>new</code> operator) instead of passing an existing instance around.</p>\n\n<h2>do not initialize with <code>null</code></h2>\n\n<p>You initialize your instance variables with <code>null</code>.\nThis prevents you from using the <code>final</code> key word on them which would indicate to you (and the compiler) that this variable will never change (and therefore) never be <code>null</code> which in turn prevents you from doing <em>Null Checks</em> all over the code.</p>\n\n<h2>code duplication</h2>\n\n<p>Your code is quite \"algorithm driven\". That resulted in lots of code duplication like this:</p>\n\n<blockquote>\n<pre><code>while(!stk.isEmpty()) \n{\n if(stk.peek().equals(\"(\")) \n {\n stk.pop();\n }\n else if (stk.peek().equals(\")\")) \n {\n stk.pop();\n }\n else \n {\n postfixNotation = postfixNotation + stk.peek();\n stk.pop();\n }\n}\n</code></pre>\n</blockquote>\n\n<p>A little more \"OO-ish\" approach could look like this:</p>\n\n<pre><code>while(!stk.isEmpty()) \n{\n if(!Arrays.asList( \"(\" , \")\" ).contains(stk.peek())\n {\n postfixNotation = postfixNotation + stk.peek();\n }\n stk.pop();\n}\n</code></pre>\n\n<p>Since Java after all is an <em>object oriented</em> you should start looking for oo-Approaches to your problems.</p>\n\n<h2>Naming</h2>\n\n<p>Finding good names is the hardest part in programming. So always take your time to think carefully of your identifier names.</p>\n\n<h3>Choose your names from the problem domain</h3>\n\n<p>You have some identifiers which are named after their technical implementation like this:</p>\n\n<pre><code> Scanner scan = null;\n Stack stk = null;\n</code></pre>\n\n<p>They should have names that reveal their task within your application. </p>\n\n<pre><code>Scanner userInput\nStack notationElements\n</code></pre>\n\n<h3>Avoid abbreviations</h3>\n\n<p>In your code you use some abbreviations such as <code>stk</code>. Although this abbreviation makes sense to you (now) anyone reading your code being not familiar with the problem (like me) has a hard time finding out what this means. \nEspecially for me as a German native the abbreviation <em>Stk</em> stands for <em>Stück</em> meaning <em>piece</em> or <em>item</em>. </p>\n\n<p>If you do this to save typing work: remember that you way more often read your code than actually typing something. Also for Java you have good IDE support with code completion so that you most likely type a long identifier only once and later on select it from the IDEs code completion proposals.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T07:10:06.533", "Id": "426128", "Score": "0", "body": "Wow, Thanks a lot. Because my English is not good, I am having difficulty in expressing gratitude in various ways :(.. \nI want you to know that I feel really really gratitude, although there are many duplicate expressions in way of my gratitude. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T06:53:51.560", "Id": "220544", "ParentId": "220506", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T09:52:38.597", "Id": "220506", "Score": "6", "Tags": [ "java", "math-expression-eval" ], "Title": "Postfix calculator in Java" }
220506
<h1>Introduction</h1> <p>When implementing a one-dimensional array, you need to keep track of the size. Such quantities are best represented by <code>std::size_t</code>:</p> <pre><code>std::size_t count; </code></pre> <p>Analogously, when implementing a multi-dimensional array, you need to store the dimensions. This time, a one-dimensional <code>std::size_t</code> does not suffice. You need multiple dimensions. Of course, something like this suffices:</p> <pre><code>std::array&lt;std::size_t, N&gt; dims; </code></pre> <p>but in my opinion, it makes more sense to use a dedicated type. As such, I implemented a multi-dimensional dimension type in C++17, so that you can use:</p> <pre><code>Dimensions&lt;N&gt; dims; </code></pre> <p>A common operation is to convert from multiple indices to one flat index. For example, given a 3&nbsp;&times;&nbsp;4 2-dimensional array indexed by 2-dimensional indices:</p> <pre> +--------+--------+--------+ | (0, 0) | (0, 1) | (0, 2) | +--------+--------+--------+ | (1, 0) | (1, 1) | (1, 2) | +--------+--------+--------+ | (2, 0) | (2, 1) | (2, 2) | +--------+--------+--------+ | (3, 0) | (3, 1) | (3, 2) | +--------+--------+--------+ </pre> <p>The corresponding flat indices look like:</p> <pre> +----+----+----+ | 0 | 1 | 2 | +----+----+----+ | 3 | 4 | 5 | +----+----+----+ | 6 | 7 | 8 | +----+----+----+ | 9 | 10 | 11 | +----+----+----+ </pre> <p>This operation is the core part. The <code>at</code> member function is provided, and <code>operator()</code> is also supported for convenience:</p> <pre><code>Dimensions&lt;2&gt; dims{4, 3}; dims(1, 2) // returns 5 dims.at({1, 2}) // returns 5 </code></pre> <p>The practice in the standard library is that <code>operator[]</code> (in this case, <code>operator()</code>) does no error checking, whereas <code>at</code> throws an exception on out-of-range input. However, my principle is that error checking should be an opt-out feature instead of opt-in. As such, <em>both <code>operator()</code> and <code>at</code> do error checking by default.</em> It is even possible to do it manually:</p> <pre><code>dims.valid({1, 2}) // returns true dims.valid({4, 2}) // returns false </code></pre> <p>That said, sometimes it is truly unnecessary, and I decided to trust the user in such cases. It is also possible to disable error checking if you know what you are doing:</p> <pre><code>dims.at(unchecked, {1, 2}) // returns 5, no error checking </code></pre> <p>This way, you don't accidentally bypass the check, but can do intentionally. Here, <code>unchecked</code> is an object used to disambiguate, similar to <code>std::allocator_arg</code>, <code>std::in_place</code>, etc.</p> <h1>Code</h1> <p>Here's the header <code>dimension.hpp</code>:</p> <pre><code>/** * @file dimension.hpp * Implements multi-dimensional utilities. */ #ifndef INC_DIMENSION_HPP_CAdUgZHijL #define INC_DIMENSION_HPP_CAdUgZHijL #include &lt;array&gt; #include &lt;cstddef&gt; #include &lt;stdexcept&gt; #include &lt;type_traits&gt; /** * L. F.'s library */ namespace LF_lib { /** * Multi-dimensional utilities. */ namespace multi { /** * Tag type to indicate unchecked versions of functions. */ struct unchecked_t { explicit unchecked_t() = default; }; /** * Tag object to indicate unchecked versions of functions. */ inline constexpr unchecked_t unchecked{}; /** * Encapsulates @c N dimensions. * Aggregate type that only contains one public member of type &lt;tt&gt;std::array&lt;std::size_t, N&gt;&lt;/tt&gt;. * @c N can be zero. * * @tparam N The number of dimensions */ template &lt;std::size_t N&gt; struct Dimension { using dimension_t = std::array&lt;std::size_t, N&gt;; ///&lt; Type for dimensions. using index_t = std::array&lt;std::size_t, N&gt;; ///&lt; Type for indices. dimension_t dimensions; ///&lt; Stores the @c N dimensions. /** * @name Observers * @{ */ /** * Returns the number of dimensions. * * @return @c N */ static constexpr std::size_t order() noexcept { return N; } /** * Returns the total size. * * @return The product of all dimensions */ constexpr std::size_t size() const noexcept { std::size_t res = 1; for (std::size_t dim : dimensions) res *= dim; return res; } /** * @} */ /** * @name Element access * @{ */ /** * Checks whether the given indices are in range. * * @param indices The indices * * @return @c true if &lt;tt&gt;indices[i] &lt; dimensions[i]&lt;/tt&gt; for &lt;tt&gt;i = 0, 1, 2, ..., N-1&lt;/tt&gt;, @c false otherwise */ constexpr bool valid(const index_t&amp; indices) const noexcept { for (std::size_t i = 0; i &lt; N; ++i) if (indices[i] &gt;= dimensions[i]) return false; return true; } /** * Returns the flat index of the element at @c indices. * * @param indices The indices * * @pre &lt;tt&gt;valid(indices)&lt;/tt&gt; * @throw std::out_of_range At least one index is out of range * * @return &lt;tt&gt;(...((indices[0] * dimensions[1] + indices[1]) * dimensions[2] + indices[2]) * ...) * dimensions[N-1] + indices[N-1]&lt;/tt&gt; */ constexpr std::size_t at(const index_t&amp; indices) const { if (!valid(indices)) throw std::out_of_range{"LF_lib::multi::Dimension&lt;N&gt;::at " "indices out of range"}; return at(unchecked, indices); } /** * Unchecked version of @c at. */ constexpr std::size_t at(unchecked_t, const index_t&amp; indices) const noexcept { std::size_t res = 0; for (std::size_t i = 0; i &lt; N; ++i) res = res * dimensions[i] + indices[i]; return res; } /** * Parentheses notation of @c at. * Let &lt;tt&gt;indices&lt;/tt&gt; denote &lt;tt&gt;index_t{static_cast&lt;std::size_t&gt;(args)...}&lt;/tt&gt;. * * @tparam Args The types of the indices * @param args The indices * * @pre &lt;tt&gt;sizeof...(Args) == N&lt;/tt&gt; * @pre &lt;tt&gt;std::conjunction_v&lt;std::is_convertible&lt;Args, std::size_t&gt;...&gt;&lt;/tt&gt; * @pre &lt;tt&gt;valid(indices)&lt;/tt&gt; * @return &lt;tt&gt;at(indices)&lt;/tt&gt; * @throw std::out_of_range At least one index is out of range */ template &lt;typename... Args&gt; constexpr std::size_t operator()(Args&amp;&amp;... args) const { static_assert(sizeof...(Args) == N, "LF_lib::multi::Dimension&lt;N&gt;::operator() " "must be called with N arguments"); static_assert(std::conjunction_v&lt;std::is_convertible&lt;Args, std::size_t&gt;...&gt;, "LF_lib::multi::Dimension&lt;N&gt;::operator() " "must be called with arguments " "implicitly convertible to std::size_t"); index_t indices{static_cast&lt;std::size_t&gt;(args)...}; if (!valid(indices)) throw std::out_of_range{"LF_lib::multi::Dimension&lt;N&gt;::operator() " "indices out of range"}; return at(unchecked, indices); } /** * @} */ }; /** * Deduction guide. * Deduces &lt;tt&gt;Dimension&lt;N&gt;&lt;/tt&gt; for @c N arguments. */ template &lt;typename... Args&gt; Dimension(Args...) -&gt; Dimension&lt;sizeof...(Args)&gt;; } } #endif </code></pre> <p>You can run Doxygen to generate the documentation. Here's a test, which is also an example of how <code>Dimension</code> can be used:</p> <pre><code>#include "dimension.hpp" #include &lt;type_traits&gt; using namespace LF_lib::multi; int main() { { constexpr Dimension&lt;5&gt; dim {1, 2, 3, 4, 5}; static_assert(dim.order() == 5); static_assert(dim.size() == 120); static_assert(!dim.valid({1, 1, 1, 1, 1})); static_assert(dim.at({0, 1, 2, 3, 4}) == 119); static_assert(dim.at({0, 1, 2, 3, 4}) == dim.at(unchecked, {0, 1, 2, 3, 4})); // static_assert(dim.at({1, 1, 1, 1, 1})); static_assert(dim(0, 1, 2, 2, 4) == dim.at({0, 1, 2, 2, 4})); } { constexpr Dimension&lt;0&gt; dim = {}; static_assert(dim.order() == 0); static_assert(dim.size() == 1); static_assert(dim.valid({})); static_assert(dim.at({}) == 0); static_assert(dim.at({}) == dim.at(unchecked, {})); static_assert(dim() == 0); } { static_assert(std::is_same_v&lt;Dimension&lt;5&gt;, decltype(Dimension{1, 2, 3, 4, 5})&gt;); // static_assert(std::is_same_v&lt;Dimension&lt;5&gt;, decltype(Dimension(1, 2, 3, 4, 5))&gt;); static_assert(std::is_same_v&lt;Dimension&lt;0&gt;, decltype(Dimension{})&gt;); static_assert(std::is_same_v&lt;Dimension&lt;0&gt;, decltype(Dimension())&gt;); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T14:19:59.000", "Id": "426069", "Score": "0", "body": "Looks really nice!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T15:19:28.380", "Id": "426073", "Score": "1", "body": "This may just be a style nit or a copy and past error, but I believe that the second namespace, starting with `namespace multi {` should be another level of indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T15:20:36.750", "Id": "426074", "Score": "1", "body": "On my machine with gcc 8.3.1, I get a compile error on the last line: `error: cannot deduce template arguments for ‘Dimension’ from ()`. Which compiler are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T16:21:02.217", "Id": "426075", "Score": "1", "body": "@Edward, [godbolt](https://godbolt.org/z/kORgLc) seems to be able to compile it. Perhaps there is a bug in gcc 8.3.1 with deduction guides? My intuition says that it should compile, but may be I am wrong, didn't thoroughly read standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T16:36:30.797", "Id": "426077", "Score": "1", "body": "@Edward I can compile it in Visual Studio 2017 when using the C++17 standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T16:40:36.040", "Id": "426079", "Score": "1", "body": "It also compiles cleanly with clang++ 7.0.1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T14:45:11.727", "Id": "431445", "Score": "0", "body": "Couldn't you use nested namespaces here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T22:47:19.557", "Id": "431479", "Score": "0", "body": "@yuri How? I’m already using `LF_lib::multi` right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T05:57:24.640", "Id": "431505", "Score": "1", "body": "Not for the declaration. E.g. `namespace LF_lib::multi {`. You are using C++17 so this should be possible or is there some other reason you omitted this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T08:16:35.233", "Id": "431518", "Score": "1", "body": "@yuri I wanted to document namespaces separately. Can I make Doxygen work with `namespace LF_lib::multi`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T09:50:42.330", "Id": "431535", "Score": "0", "body": "I do not know but it explains why you didn't use it yet, thanks for clarifying." } ]
[ { "body": "<p>Lovely clean readable code - nice. <code>:-)</code></p>\n\n<p>I don't agree with your bounds-checking philosophy (imposing either run-time overhead or syntactic clutter), but I'll respect your choice. I find it, um, <em>interesting</em> that although we have bounds checking, we still cheerfully allow our accessors <code>at()</code> and <code>size()</code> to overflow the range of <code>std::size_t</code>.</p>\n\n<p>Review points, in no particular order:</p>\n\n<ul>\n<li>It's great that you provide a deduction guide; it seems a waste not to use that for at least one of the <code>dim</code> variables in the demo program!</li>\n</ul>\n\n <ul>\n<li><p>I get a compilation failure for the use of <code>Dimension()</code> default constructor:</p>\n\n<pre><code>220508.cpp:204:71: error: cannot deduce template arguments for ‘Dimension’ from ()\n static_assert(std::is_same_v&lt;Dimension&lt;0&gt;, decltype(Dimension())&gt;);\n</code></pre>\n\n<p>I think this is just a consequence of using <code>struct</code> initialisation, rather than declaring a constructor.</p></li>\n<li><p>It's slightly frustrating that only the <code>()</code> accepts unpacked arguments, and we need to write <code>{</code>..<code>}</code> to construct an <code>index_t</code> when using <code>at()</code> or <code>valid()</code>.</p></li>\n<li><p>It's not necessary or particularly useful to mark a default constructor <code>explicit</code> - it can never be a conversion.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T11:20:40.460", "Id": "431554", "Score": "0", "body": "Great! Thank you! As to the second bullet, that's strange because I compiled it successfully. ([demo](https://wandbox.org/permlink/mKixRnplzrepFw6t))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T11:24:16.047", "Id": "431555", "Score": "0", "body": "Also, as to `operator()`: it is considered to be \"convenience syntax\" so I removed the `{ }`. I used universal references because otherwise an object that is intended to be converted to `size_t` may be accidentally copied. For example, I may have an lvalue `foo` of non-copyable type `Foo`, and I want to make sure `dim(foo)` works. But it didn't really work out — I intended to use `std::forward<Args>(args)...` but seems I forgot it ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T11:26:58.793", "Id": "431557", "Score": "0", "body": "I marked the default constructor `explicit` because I was imitating [\\[allocator.tag\\]](http://eel.is/c++draft/allocator.tag) ... But good point anyway! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T11:29:37.103", "Id": "431559", "Score": "0", "body": "Actually, I think you were probably right to use the operator forwarding - a cast isn't a call, so shouldn't cause an unnecessary copy. I should withdraw that criticism!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T11:12:54.277", "Id": "222862", "ParentId": "220508", "Score": "4" } }, { "body": "<p>Writing it down here so I don't forget it: there is a bug in the code about perfect forwarding. I wrote</p>\n\n<pre><code>template &lt;typename... Args&gt;\nconstexpr std::size_t operator()(Args&amp;&amp;... args) const\n{\n // ...\n index_t indices{static_cast&lt;std::size_t&gt;(args)...};\n // ...\n}\n</code></pre>\n\n<p>when it should be </p>\n\n<pre><code>template &lt;typename... Args&gt;\nconstexpr std::size_t operator()(Args&amp;&amp;... args) const\n{\n // ...\n index_t indices{static_cast&lt;std::size_t&gt;(std::forward&lt;Args&gt;(args))...};\n // ...\n}\n</code></pre>\n\n<p>Also, it is preferable to constrain the function with SFINAE instead of putting in <code>static_assert</code>s:</p>\n\n<pre><code>template &lt;typename... Args, typename = std::enable_if_t&lt;\n sizeof...(Args) == N &amp;&amp;\n std::conjunction_v&lt;std::is_convertible&lt;Args, std::size_t&gt;...&gt;\n&gt;&gt;\nconstexpr std::size_t operator()(Args&amp;&amp;... args) const;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-11T08:30:00.937", "Id": "235466", "ParentId": "220508", "Score": "3" } } ]
{ "AcceptedAnswerId": "222862", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T11:44:44.080", "Id": "220508", "Score": "4", "Tags": [ "c++", "c++17" ], "Title": "Multi-dimensional dimension type" }
220508
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/island-perimeter/" rel="nofollow noreferrer">leetcode</a></p> <blockquote> <p>You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.</p> <p>Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).</p> <p>The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.</p> <p>Example:</p> <p>Input:</p> <pre><code>[[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] </code></pre> <p>Output: 16</p> <p>Explanation: The perimeter is the 16 yellow stripes in the image below: <a href="https://i.stack.imgur.com/9vYLm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9vYLm.png" alt="enter image description here"></a></p> </blockquote> <p><strong>My solution</strong></p> <pre><code>/** * @param {number[][]} grid * @return {number} */ var islandPerimeter = function(grid) { const getWaterNeighborAt = position =&gt; { if (!grid[position.y][position.x]) { return 0; } const north = position.y - 1 &lt; 0 ? true : grid[position.y - 1][position.x] === 0; const east = position.x + 1 &gt;= grid[0].length ? true : grid[position.y][position.x + 1] === 0; const south = position.y + 1 &gt;= grid.length ? true : grid[position.y + 1][position.x] === 0; const west = position.x - 1 &lt; 0 ? true : grid[position.y][position.x - 1] === 0; return north + east + south + west; }; let perimeter = 0; grid.forEach((row, y) =&gt; { row.forEach((_, x) =&gt; { perimeter += getWaterNeighborAt({x, y}); }); }); return perimeter; }; </code></pre>
[]
[ { "body": "<ul>\n<li><p>Objects should be making the code easier to read. The Object you name <code>position</code> provides no behavioral benefit and serves only to bloat the code. </p></li>\n<li><p>You should be using good old for loops for this rather than the hacky way you use the array iteration function <code>forEach</code></p></li>\n<li><p>Use function declarations <code>function islandPerimeter(grid)</code>. Do not use function expressions <code>var islandPerimeter = function(grid)</code></p></li>\n</ul>\n\n<h2>Rewrite</h2>\n\n<p>Rewriting your coder I would do it as follows</p>\n\n<pre><code>function islandPerimeter(grid) {\n const W = grid[0].length, H = grid.length;\n const countEdges = (x, y) =&gt; {\n var res = 0;\n if (grid[y][x]) { \n res += y - 1 &lt; 0 ? 1 : grid[y - 1][x] === 0;\n res += x + 1 &gt;= W ? 1 : grid[y][x + 1] === 0;\n res += y + 1 &gt;= H ? 1 : grid[y + 1][x] === 0;\n res += x - 1 &lt; 0 ? 1 : grid[y][x - 1] === 0;\n }\n return res;\n };\n var perimeter = 0, x = 0; y = 0;\n for (y = 0; y &lt; H; y ++) {\n for (x = 0; x &lt; W; x ++) {\n perimeter += countEdges(x, y);\n }\n }\n return perimeter;\n}\n</code></pre>\n\n<h2>A flaw in the problem</h2>\n\n<p>The question states all the land is connected which hints at an optimal solution however the problem is flawed.</p>\n\n<p>There is a solution that is <span class=\"math-container\">\\$O(l)\\$</span> where <span class=\"math-container\">\\$l\\$</span> is the land cell count if you had one extra tit-bit of information, a coordinate of a land cell. </p>\n\n<p>That way you could use a flood fill and thus only need to check land cells. </p>\n\n<p>Without that coordinate you need to search for the land and the worst case would have the land cell the last cell making it <span class=\"math-container\">\\$O(n)\\$</span> where <span class=\"math-container\">\\$n\\$</span> is the cell count.</p>\n\n<h2>Performance</h2>\n\n<p>You can however improve the performance by counting edges as you cross them. If a cell is different than the cell to the left, or above then there is a edge to count</p>\n\n<pre><code>function islandPerimeter(grid) {\n const W = grid[0].length, H = grid.length;\n var x = 0, y = 0, res = 0, prevRow = 0, prev;\n while (y &lt; H) {\n x = prev = 0;\n const row = grid[y];\n const prevCount = res;\n while (x &lt; W) {\n const cell = row[x];\n res += cell !== prev;\n res += prevRow &amp;&amp; prevRow[x] !== cell;\n prev = cell;\n x++;\n }\n res += prev;\n if (res &amp;&amp; prevCount === res) { return res }\n prevRow = row;\n y++;\n }\n while (x--) { res += prevRow[x] === 1 }\n res += prevRow[0];\n return res;\n}\n</code></pre>\n\n<p>As the question states that all he land is connected thus I added an early exit if there is an empty row after some land cells have been found.</p>\n\n<h2>Flood Fill</h2>\n\n<p>And here is a flood fill example. Its just a quick write as it does not really provide an improvement without at least a coordinate of a land cell. There are a few optimizations that could be added and it also needs to modify the map so to not repeat cells</p>\n\n<p>It finds the first cell by stepping over empty cells.</p>\n\n<pre><code>function islandPerimeter(arr) {\n const H = arr.length, W = arr[0].length, SIZE = H * W;\n const EDGES = [[1, 0], [-2, 0], [1, -1], [0, 2]];\n const stack = [];\n\n const isLand = () =&gt; (cell = arr[y] &amp;&amp; arr[y][x] || 0) &gt; 0;\n const isLandIdx = () =&gt; (x = idx % W, y = idx / W | 0, isLand());\n const checked = () =&gt; (stack.push([x,y]), arr[y][x] = 2);\n var x, y, res = 0, idx = 0, cell;\n while (idx &lt; SIZE &amp;&amp; !isLandIdx()) { idx++ }\n if (idx &lt; SIZE) {\n checked();\n while (stack.length) {\n [x, y] = stack.pop();\n for (const e of EDGES) {\n x += e[0];\n y += e[1];\n isLand() ? (cell === 1 &amp;&amp; checked()) : res++;\n }\n }\n }\n return res;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T16:37:18.567", "Id": "426078", "Score": "0", "body": "Why not use function expressions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T17:03:07.843", "Id": "426080", "Score": "0", "body": "@thadeuszlay Because they are more verbose and because they only become available after the expression, while declared functions are available anywhere and any time (after parsed) in the scope they are in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T17:08:58.270", "Id": "426081", "Score": "0", "body": "`Objects should be making the code easier to read`: Robert C. Martin (Uncle Bob) once mentioned that ideally functions should have only one parameter. I tried to follow that. Would you still advice against it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T17:14:28.970", "Id": "426082", "Score": "1", "body": "`y - 1 < 0 ? 1 : grid[y - 1][x] === 0;`: Do you think this is a good style to mix `Number` and `Boolean` a value can take? It's working because addition/subtraction converts `Boolean` values to `Numbers`. But I got the impression that's kind of messy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T17:16:11.680", "Id": "426083", "Score": "0", "body": "`const W = grid[0].length, H = grid.length;`: Why did you wrote `W` and `H` in capital letters? Because they are constants?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T17:28:40.727", "Id": "426084", "Score": "0", "body": "@thadeuszlay Re `W`,`H` its a habit of mine, yes they are const but i used to do it for vars as well. The number in the ternary means that it does not need to be coerced (should both not be numbers not bools?) One parameter! that does not means make objects to keep to the one parameter guide. Personally I would have let closure handle the variables rather than pass them as in the last example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T21:21:44.867", "Id": "426096", "Score": "0", "body": "What was actually your reasoning for writing `H = grid.length;`? I assume it is more concise and not because of performance concerns? `grid.length` is an attribute and accessing `length` doesn't cost much, does it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T22:05:51.077", "Id": "426099", "Score": "0", "body": "Why do you think I used the forEach in a hacky way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:42:46.637", "Id": "426153", "Score": "0", "body": "@thadeuszlay The `W,H` where used to keep the layout of the code neat. The use of the `_` to soak up an argument in the hack." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T16:35:59.500", "Id": "220517", "ParentId": "220510", "Score": "3" } } ]
{ "AcceptedAnswerId": "220517", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T13:51:45.280", "Id": "220510", "Score": "4", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6" ], "Title": "Island Perimeter" }
220510
<p>I am currently learning javascript at university. We have an assignment where we shall write various functions for calculating values. In one case, we shall write a function which returns the sum of two values, if only those two values were passed as arguments. If there is the third optional argument, which shall be an operation like subtract or multiply, than it should return the result of this operation.</p> <p>Now, my question is: Is this code written in good way or is it like really bad style?</p> <p>Btw: One assignment before, we should write the add, subtract and multiply functions in inside of this calculate function. So this was set.</p> <pre><code> let rechne2b = function(a, b, ...operator){ let addiere = function(a, b){ return a + b; } let subtrahiere = function(a, b){ return a - b; } let multipliziere = function(a, b){ return a * b; } let argsLength = arguments.length if(argsLength &gt; 2){ switch(arguments[2].operation){ case "subtrahiere": return subtrahiere(a, b); break; case "multipliziere": return multipliziere(a, b); break; } } else { return a + b; } } console.log(rechne2b(4, 5, {operation: "multipliziere"})) </code></pre>
[]
[ { "body": "<ul>\n<li>Use a function declaration <code>function rechne2b(a, b, {operator}){</code> rather than a function expression <code>let rechne2b = function(a, b, {operator}){</code></li>\n<li>There is only a single optional argument so don't use the rest operator <code>...</code></li>\n<li>The optional argument is passed in an object so you should use destructuring assignment <code> function rechne2b(a, b, {operator})</code> to extract the operator if given.</li>\n<li>Avoid <code>switch</code> statements if you can by using a lookup (see example)</li>\n</ul>\n<h2>Rewrite</h2>\n<pre><code>function rechne2b(a, b, {operator}) {\n const ops = {\n subtrahiere(a, b) { return a - b },\n multipliziere(a, b) { return a * b },\n };\n return ops[operator] ? ops[operator](a, b) : a + b;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T16:57:57.767", "Id": "220519", "ParentId": "220514", "Score": "1" } } ]
{ "AcceptedAnswerId": "220519", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T15:06:24.737", "Id": "220514", "Score": "1", "Tags": [ "javascript", "homework" ], "Title": "Calculate function with optional operator argument" }
220514
<p>A while ago I was working on a multipurpose database class (an es6 javascript class) that works with any database supporting adodb.</p> <p>This class is a wrapper on the "node-adodb" npm library. This database class has four main methods, all of which process some options, passed in as parameters, into sql, which is then run on the database.</p> <p>I am particularly worried about my processing of the options, as I have little experience in that field.</p> <p>I have been programming for about 2 years or so and am looking for any criticisms/feedback.</p> <p>Here is my code:</p> <pre><code>'use strict' /** * @file A file that contains the "dataBase" class. */ const debug = require('debug')('Data-comms:dataBase') const adodb = require('node-adodb') adodb.debug = true /** * @constructor * @param {string} connection - The connection string to the database. * @param {boolean} X64 - Whether or not you are using the 64 bit version. * @name dataBase * @description A class for: Connecting to, Querying, etc, adodb databases. */ exports.dataBase = class DataBase { constructor(connection, X64) { this.connectString = connection this.X64 = X64 this.connection = adodb.open(connection, X64) debug('Connection opened:', this.connection) this._this = this debug('dataBase class initialized:', this) } /** * @async * @function dataBase#close * @description Closes the connection to the database. */ async close() { await this.connection.close() debug('connection closed:', this.connection) return } /** * @async * @function dataBase#reopen * @description Reopens the connection to the database if it has been closed. */ async reopen() { this.connection = adodb.open(this.connectString, this.X64) debug('connection reopened:', this.connection) return } /** * @async * @function dataBase#runSQL * @param {string} SQL - The SQL that will be run. * @description Runs any valid SQL on the database. * @returns {object[]|object} If the SQL is a query, this is the result. */ async runSQL(sql) { debug('starting SQL execution:', sql) debug('SQL code execution type:', sql.match('SELECT') ? 'query' : 'execute') const data = await this.connection[sql.match('SELECT') ? 'query' : 'execute'](sql) debug('SQL ran with result:', data) return data } /** * @async * @function dataBase#query * @param {string} table - The table that you are querying. * @param {string[]|string} [columns] - The column(s) you want to query - If left empty or as '*' it will query all columns. * @param {string[]|string} [rows] - The ID of the row(s) you want to query - If left empty or as '*' it will query all rows. * @param {string[]|string} [options] - Any additional paramiters in the query - If left empty there will be no additional paramiters. * @param {Boolean|object} [isUpdate=false] - Whether or not to update the selected fields, if so it is an object containing info about what columns change to what. * @description Runs a query based on the four paramiters described below. Here are all of it's child functions. * @returns {object[]} The result of the query. */ async query(table, columns = '*' || [], rows = '*' || [], options = '*' || []) { debug('starting query with arguments:', 'table:', table, 'columns:', columns, 'rows:', rows, 'options:', options) function makeArray(str) { return typeof str === 'string' &amp;&amp; str !== '*' ? [str] : str } columns = makeArray(columns) rows = makeArray(rows) options = makeArray(options) function processData(table, columns, rows, options) { debug('Starting data processing') function processColumns(columns) { let retval = '' for(const i in columns) { if(i != columns.length - 1) { retval += `${columns[i]},` } else { retval += `${columns[i]}` return retval } } } function processRows(rows) { let retval = '' for(const i in rows) { if(i != rows.length - 1) { retval += `ID=${rows[i]} OR ` } else { retval += `ID=${rows[i]}` } } return retval } function processOptions(options) { let retval = '' for(const i in rows) { retval += ` AND ${options[i]}` } return retval } const SQLcolumns = processColumns(columns) const SQLrows = processRows(rows) const SQLoptions = processOptions(options) debug('Finished data processing') debug('Running query:', `SELECT ${SQLcolumns} FROM [${table}] ${rows === '*' &amp;&amp; options === '*'? '' : 'WHERE'} ${rows === '*' ? '' : SQLrows}${options === '*' ? '' : SQLoptions};`) return `SELECT ${SQLcolumns} FROM [${table}] ${rows === '*' &amp;&amp; options === '*'? '' : 'WHERE'} ${rows === '*' ? '' : SQLrows}${options === '*' ? '' : SQLoptions};` } const processed = processData(table, columns, rows, options) const data = await this.runSQL(processed) debug('Query ran with result:', data) return data } /** * @async * @function dataBase#createTable * @param {string} name - The name of the table that will be made. * @param {object} columns - The columns in the table, for each property the key is the column name and the value is the column type. * @param {object} [rows] - The rows to initially add to the dataBase, if left blank there will be no inital rows. - In each property the value will be the value inserted into the column, the column is determined by the order of the properties. * @description Creates a table based on the peramiters below. */ async createTable(name, columns, rows = null) { debug('starting table creation with paramiters:', 'name:', name, 'columns:', columns, 'rows:', rows) debug('Starting data processing') function processColumns(columns) { let retval = '' for(const i of Object.keys(columns)) { i !== Object.keys(columns)[Object.keys(columns).length - 1] ? retval += `${i} ${columns[i]},\n` : retval += `${i} ${columns[i]}` } return retval } debug('Finished data processing') const SQLcolumns = processColumns(columns) debug('Creating table') const data = await this.runSQL(`CREATE TABLE ${name} (\n${SQLcolumns}\n);`) debug('Table created with result:', data) if(rows !== null) { debug('Adding records:', rows) await this.addRecords(name, rows) debug('Records added') } return data } /** * @async * @function dataBase#addRecords * @param {string} table - The name of the the table that the rows will be inserted into. * @param {object} values - The rows to add to the dataBase. - In each property the value will be the value inserted into the column, the column is determined by the order of the properties. * @description Adds records to a database based on the peramiters below. */ async addRecords(table, values) { debug('starting record adding with paramiters:', 'table:', table, 'values:', values) debug('Starting data processing') const data = [] function processValues(values) { let retval = '' for(const i of Object.keys(values)) { i !== Object.keys(values)[Object.keys(values).length - 1] ? retval += `${values[i]}, ` : retval += values[i] } return retval } debug('Finished data processing') for(const i of values) { const SQLvalues = processValues(i) debug('Inserting:', SQLvalues) await this.runSQL(`INSERT INTO [${table}] VALUES (${SQLvalues});`).then((result) =&gt; { debug('Values inserted with result:', result) data.push(result) }) } debug('Finished row insertion with result:', data) return data } } </code></pre>
[]
[ { "body": "<h1>Review</h1>\n<p>From a first look your code is bloated with debug noise and due to poor language feature utilization.</p>\n<p>Looking deeper I see that poor encapsulation makes using the class <code>DataBase</code> ambiguous and non-intuitive.</p>\n<h2>General points</h2>\n<ul>\n<li><p>Learn to use DevTools and don't fill your code with debugging code as it is a source of bugs and as you are not enforcing the truth of the debug calls can result in misleading debug information.</p>\n</li>\n<li><p>Functions return automatically you don't need empty returns at the end of functions</p>\n</li>\n<li><p>Don't add code not used. <code>this._this = this</code> is not used, and if you did need to use it (ie no access to <code>this</code>) how would you get <code>this._this</code> ?</p>\n</li>\n<li><p>Use default parameters when you can. eg <code>X64</code> (why would anyone want to run 32bit when on a 64bit OS) The parameter is an annoyance and should default to <code>true</code></p>\n</li>\n<li><p>Avoid single use variables. eg <code>const data = await this.connection[sql.match('SELECT') ? 'query' : 'execute'](sql); return data</code> can be <code>return this.connection[sql.match('SELECT') ? 'query' : 'execute'](sql)</code></p>\n</li>\n<li><p>In functions use arrow functions for utility functions. eg <code>function makeArray(str) { return typeof str === 'string' &amp;&amp; str !== '*' ? [str] : str}</code> becomes <code> const makeArray = str =&gt; typeof str === 'string' &amp;&amp; str !== '*' ? [str] : str;</code></p>\n</li>\n<li><p>Don't repeat expensive operations. This is particularly important for node.js services. Node is great for IO but JS is slow and you should always keep in mind that CPU cycles cost money. Eg <code>for(const i of Object.keys(columns)) { i !== Object.keys(columns)[Object.keys(columns).length - 1] ?</code> becomes <code>const keys = Object.keys(values); for(const i of keys) { i !== keys[keys.length - 1] ? </code> without the CPU and Memory overhead needed to create the keys array 2 times for each key`</p>\n</li>\n<li><p>Become familiar with the language by studying the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript\" rel=\"nofollow noreferrer\">reference material</a>. This is an ongoing task that will need to be maintained for the length of you career. The vast majority of your code is performing <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\"><code>Array.join</code></a> (all the <code>process...</code> calls). Code length is a source of bugs, always keep the code length down</p>\n</li>\n<li><p>Watch the naming. <code>SQLrows</code> and <code>SQLoptions</code> should be <code>SQLRows</code> and <code>SQLOptions</code></p>\n</li>\n<li><p>JavaScript uses &quot;;&quot; if you do not include them they are added automatically. There are some edge cases that make the human readable source difficult to determine where or if the semicolon is inserted. Add it manually so you never need to deal with the ambiguity</p>\n</li>\n<li><p>Code should be understandable without comments. It is bad practice to rely on comments to understand the code. Comments are not vetted, verifiable, and can easily modified, removed, become defunct and are thus dangerous to the understanding of the code.</p>\n</li>\n</ul>\n<h2>The interface</h2>\n<ul>\n<li>Your interface does not check state when performing behaviors</li>\n</ul>\n<p>E.G.</p>\n<pre><code>const db = new DataBase(SQLConnect);\ndb.close();\nconst result = db.runSQL(query); // what is expected if the db is closed.\n</code></pre>\n<p>All the calls should check if the state is valid to perform any operation. Use setting to define behaviors. eg <code>db.autoConnect = true</code> will have the DB connect if disconnected</p>\n<ul>\n<li>Using the class syntax has forced you into a poor encapsulation pattern</li>\n</ul>\n<p>E.G.</p>\n<pre><code>const db = new DataBase(SQLConnect);\ndb.connectString = SQLConnect2; // What now??\n</code></pre>\n<p>The <code>connectString</code> should be set via a setter. If the connection differs then the current connection should be closed (depending on behavioral settings)</p>\n<ul>\n<li>No error checking</li>\n</ul>\n<p>Every call has a possibility of error yet none of the code vets for errors, or handles any errors gracefully</p>\n<h2>Rewrite</h2>\n<p>The rewrite does not change the behavior (apart from defaults <code>X64</code> to true and added <code>open</code> function), removes redundant and debug code, and uses a more compact style.</p>\n<p>This is meant as an example only and may contain many typos as I am unable to test run it.</p>\n<p>The first thing I do when reviewing code is automatically remove comments (code should be understandable without them). Poor naming means I have had to guess as to what is contained in the many arguments passed.</p>\n<p>It is valid to argue that &quot;I should have read the comments.&quot;, to which I can but reply &quot;This is only a review the code below is not meant to be accurate.&quot;.</p>\n<pre><code>&quot;use strict&quot;;\nconst adodb = require(&quot;node-adodb&quot;);\nexports.dataBase = class DataBase {\n constructor(connection, X64 = true) {\n this.connectString = connection;\n this.X64 = X64;\n this.open();\n }\n async close() {\n await this.connection.close();\n }\n open() {\n this.connection = adodb.open(this.connectString, this.X64);\n }\n async reopen() {\n this.open();\n }\n async runSQL(sql) {\n return this.connection[sql.match(&quot;SELECT&quot;) ? &quot;query&quot; : &quot;execute&quot;](sql);\n }\n async query(table, columns = &quot;*&quot; || [], rows = &quot;*&quot; || [], options = &quot;*&quot; || []) {\n const makeArray = str =&gt; typeof str === &quot;string&quot; &amp;&amp; str !== &quot;*&quot; ? [str] : str;\n rows = makeArray(rows);\n options = makeArray(options);\n const SQLRows = rows === &quot;*&quot; ? &quot;&quot; : &quot;ID=&quot; + rows.join(&quot; OR &quot;);\n const SQLoptions = options === &quot;*&quot; ? &quot;&quot; : &quot; AND &quot; + options.join(&quot; AND &quot;);\n return this.runSQL(`SELECT ${makeArray(columns).join(&quot;,&quot;)} FROM [${table}] ${rows === &quot;*&quot; &amp;&amp; options === &quot;*&quot;? &quot;&quot; : &quot;WHERE&quot;} ${SQLRows}${SQLOptions};`);\n }\n async createTable(name, columns, rows = null) {\n const data = await this.runSQL(`CREATE TABLE ${name} (\\n${columns.map(col =&gt; &quot;${i} ${columns[i]}&quot;).join(&quot;,\\n&quot;)}\\n);`);\n if (rows !== null) {\n await this.addRecords(name, rows);\n }\n return data;\n }\n async addRecords(table, values) {\n const data = [];\n for (const i of values) {\n await this.runSQL(`INSERT INTO [${table}] VALUES (${Object.keys(i).join(&quot;, &quot;)});`).then(result =&gt; {\n data.push(result);\n });\n }\n return data;\n }\n};\n</code></pre>\n<p>Or</p>\n<pre><code>&quot;use strict&quot;;\nconst adodb = require(&quot;node-adodb&quot;);\nexports.dataBase = class DataBase {\n constructor(connection, X64 = true) {\n this.connectString = connection;\n this.X64 = X64;\n this.open();\n }\n async close() { await this.connection.close() }\n open() { this.connection = adodb.open(this.connectString, this.X64) }\n async reopen() { this.open() }\n async runSQL(sql) { return this.connection[sql.match(&quot;SELECT&quot;) ? &quot;query&quot; : &quot;execute&quot;](sql) }\n async query(table, columns = &quot;*&quot; || [], rows = &quot;*&quot; || [], options = &quot;*&quot; || []) {\n const makeArray = str =&gt; typeof str === &quot;string&quot; &amp;&amp; str !== &quot;*&quot; ? [str] : str;\n rows = makeArray(rows);\n options = makeArray(options);\n const SQLRows = rows === &quot;*&quot; ? &quot;&quot; : &quot;ID=&quot; + rows.join(&quot; OR &quot;);\n const SQLoptions = options === &quot;*&quot; ? &quot;&quot; : &quot; AND &quot; + options.join(&quot; AND &quot;);\n return this.runSQL(`SELECT ${makeArray(columns).join(&quot;,&quot;)} FROM [${table}] ${rows === &quot;*&quot; &amp;&amp; options === &quot;*&quot;? &quot;&quot; : &quot;WHERE&quot;} ${SQLRows}${SQLOptions};`);\n }\n async createTable(name, columns, rows = null) {\n const data = await this.runSQL(`CREATE TABLE ${name} (\\n${columns.map(col =&gt; &quot;${i} ${columns[i]}&quot;).join(&quot;,\\n&quot;)}\\n);`);\n if (rows !== null) { await this.addRecords(name, rows) }\n return data;\n }\n async addRecords(table, values) {\n const data = [];\n for (const i of values) {\n await this.runSQL(`INSERT INTO [${table}] VALUES (${Object.keys(i).join(&quot;, &quot;)});`).then(result =&gt; {data.push(result)});\n }\n return data;\n }\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T19:18:28.610", "Id": "426225", "Score": "0", "body": "Thanks for the feedback, I now have some more things to work on, I would mention that my comments are there in order to document it with the JSdocs tool as the majority of people find that easier to read, other than that I agree with everything you say in this answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T04:36:27.003", "Id": "426236", "Score": "0", "body": "@MilesZew I am aware that your comments are JSDocs related, however they still remain unverifiable and as such have no place in the source code. Documentation should be separate from source code or there is a tenancy to rely on the documentation to support poor naming and code structure," } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T12:43:34.623", "Id": "220563", "ParentId": "220515", "Score": "1" } } ]
{ "AcceptedAnswerId": "220563", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T16:16:13.850", "Id": "220515", "Score": "1", "Tags": [ "javascript", "object-oriented", "node.js", "adodb" ], "Title": "Node.js DataBase class for adodb databases" }
220515
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/" rel="nofollow noreferrer">leetcode</a></p> <blockquote> <p>Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.</p> <p>Find all the elements of [1, n] inclusive that do not appear in this array.</p> <p>Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.</p> <p><strong>Example:</strong></p> <p>Input:</p> <p>[4,3,2,7,8,2,3,1]</p> <p>Output:</p> <p>[5,6]</p> </blockquote> <p><strong>My solution</strong></p> <pre><code>/** * @param {number[]} nums * @return {number[]} */ var findDisappearedNumbers = function(nums) { return nums .reduce((arr, x) =&gt; { arr[x - 1] = null; return arr; }, Array.from({length: nums.length}, (v, k) =&gt; k+1)) .filter(Boolean); }; </code></pre> <p>There has to be a more elegant solution to that.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T17:50:57.540", "Id": "426085", "Score": "0", "body": "does this work? `console.log(findDisappearedNumbers([4,7,2,9]));` yields `[1,3]`. The problem description is defective." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T18:09:28.553", "Id": "426087", "Score": "0", "body": "@radarbob `1 ≤ a[i] ≤ n (n = size of array)`. Your array `[4,7,2,9]` has to have at least the size of `9`." } ]
[ { "body": "<p>You have created a good solution, just a few style points that can reduce code size.</p>\n<ul>\n<li><p>Why <code>null</code> rather than <code>false</code> or even <code>0</code> in <code>arr[x - 1] = null;</code></p>\n</li>\n<li><p>Why not use commas to remove need for return. Eg <code>.reduce((arr, x) =&gt; {arr[x - 1] = null; return arr; }</code> becomes <code>.reduce((arr, x) =&gt; (arr[x - 1] = null, arr))</code></p>\n</li>\n<li><p>To create an array of indexes you could have used the shorter forms, <code>Array.from(nums, (item, i) =&gt; i + 1))</code> or <code>nums.map((item,i) =&gt; i + 1)</code></p>\n</li>\n</ul>\n<h2>Rewrites</h2>\n<pre><code>function findMissing(arr) {\n return arr\n .reduce((a, i) =&gt; (a[i - 1] = 0, a), arr.map((item, i) =&gt; i + 1))\n .filter(Boolean);\n}\n</code></pre>\n<p>or</p>\n<pre><code>const findMissing = arr =&gt; arr\n .reduce((a, i) =&gt; (a[i - 1] = 0, a), arr.map((item, i) =&gt; i + 1))\n .filter(Boolean);\n</code></pre>\n<p>You could also have solved it with a set as follows</p>\n<pre><code>function findMissing(arr) {\n const s = new Set(arr), res = [];\n var i = arr.length;\n while (i) { s.has(i--) || res.push(i + 1) }\n return res;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T14:33:06.953", "Id": "426187", "Score": "0", "body": "Finally I received a praise from you :p. J/k. Btw: don’t mind that I use function expression instead of function statement. I copied from the original task" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T14:41:41.823", "Id": "426190", "Score": "0", "body": "@thadeuszlay Most points I make are what I consider good practice but there is only one right way and that is \"does it work?\", I will try not to harp on about points if people don't follow or disagree. Did I give praise WTF.... lol... I think you are developing your skills very well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:52:13.193", "Id": "220568", "ParentId": "220516", "Score": "2" } }, { "body": "<blockquote>\n <p>Could you do it without extra space and in <span class=\"math-container\">\\$O(n)\\$</span> runtime?</p>\n</blockquote>\n\n<p>The implementation uses <span class=\"math-container\">\\$O(n)\\$</span> extra space.\nA different approach is possible without extra space,\nby rearranging the content of the input array,\nso that the values that appear ordered, and at the position where they would be if nothing was missing.</p>\n\n<p>Going with the example <code>[4,3,2,7,8,2,3,1]</code>, the content can be rearranged in <span class=\"math-container\">\\$O(n)\\$</span> time to become this:</p>\n\n<pre><code>[1,2,3,4,3,2,7,8]\n</code></pre>\n\n<p>Then, with one more pass, you can identify <code>[5, 6]</code> as the missing pieces.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T20:21:47.910", "Id": "220587", "ParentId": "220516", "Score": "2" } } ]
{ "AcceptedAnswerId": "220568", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T16:30:57.677", "Id": "220516", "Score": "2", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6" ], "Title": "Find All Numbers Disappeared in an Array" }
220516
<p>How can I make this code faster? the string can contain characters such as ", .?#" and possibly others.</p> <pre><code>Const Nums = ['0'..'9']; function CleanNumber(s: String): Int64; Var z: Cardinal; begin for z := length(s) downto 1 do if not (s[z] in Nums) then Delete(s,z,1); if s = '' then Result := 0 else Result := StrToInt64(s); end; </code></pre>
[]
[ { "body": "<p>Don't over use <code>set</code>. It is faster when the items are discrete, but slower when the items are continuous. Although, the difference is very small in your case.</p>\n\n<p>The problem here is that you use <code>delete</code> repeatedly. Each call moves (copies) a potentially large chuck of characters. This is inefficient because many characters are moved multiple times. For example, <code>5</code> in string <code>1 2 3 4 5</code> is moved 4 times.</p>\n\n<p>Given that <code>string</code> in Delphi is mutable, it is better to copy individual characters:</p>\n\n<pre><code>function CleanNumber(s: String): Int64;\nVar\n z, l: Cardinal;\nbegin\n l := 1;\n for z := 1 to length(s) do\n if (s[z] &gt;= '0') and (s[z] &lt;= '9') then\n begin\n s[l] := s[z];\n inc(l);\n end;\n SetLength(s, l - 1);\n\n if s = '' then\n Result := 0 else\n Result := StrToInt64(s);\nend;\n</code></pre>\n\n<p>It can be further improved:</p>\n\n<pre><code>function CleanNumber(s: String): Int64;\nVar\n z, l: Cardinal;\nbegin\n l := 1;\n while (l &lt;= length(s)) and (s[l] &gt;= '0') and (s[l] &lt;= '9') do\n inc(l); // Scan for the first non-numeric char\n\n for z := l + 1 to length(s) do // Start from l + 1\n if (s[z] &gt;= '0') and (s[z] &lt;= '9') then\n begin\n s[l] := s[z];\n inc(l);\n end;\n\n if l = 1 then Result := 0 else\n begin\n SetLength(s, l - 1);\n Result := StrToInt64(s);\n end;\nend;\n</code></pre>\n\n<p>Note: code not tested.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-02T20:07:41.427", "Id": "442461", "Score": "1", "body": "Why did you choose `z` and `l` for the variable names? Especially the assignment `l := 1` is hard to read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-02T21:34:06.403", "Id": "442471", "Score": "0", "body": "@Roland Illig: I used `z` because that's what hikari used. I usually use `i` and `j` for loop variables. I used single char `l` instead of my usual `len` because it is more consistent to his/her style. I seldom get confused by `l` and `1` because they are shown in different colors due to the use of theme. I guess I should." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-02T18:55:22.140", "Id": "227351", "ParentId": "220522", "Score": "4" } }, { "body": "<p>Practically speaking, this function is probably not the single bottleneck of your application, which would mean it takes more than 30% of the total run time. Therefore you don't need to optimize this code for speed, but for correctness and legibility.</p>\n\n<p>If you want to get the maximum speed out of this little function nevertheless, you should look at the implementation of <code>StrToInt64</code> and implement the essential from that function yourself. Approximately like this:</p>\n\n<pre class=\"lang-pascal prettyprint-override\"><code>function CleanNumber(s: String): Int64;\nvar\n i, num, limit10, limit1: Int64;\nbegin\n limit10 := MaxInt64 div 10;\n limit1 := MaxInt64 mod 10;\n\n num := 0;\n for i := 1 to Length(s) do\n if (s[i] &gt;= '0') and (s[i] &lt;= '9') then begin\n if num &gt; limit10 then raise EValue();\n if (num = limit10) and (Ord(s[i]) - Ord('0') &gt; limit1) then raise EValue();\n\n num := 10 * num + Ord(s[i]) - Ord('0');\n end;\n Result := num;\nend;\n</code></pre>\n\n<p>I didn't test the code and I'm not sure about the correct syntax for throwing exceptions, but I expect the basic algorithm to work fine. Some test cases:</p>\n\n<pre class=\"lang-pascal prettyprint-override\"><code>''\n'0'\n'9'\n'100'\n'1.0.0'\n'1234567890123456789'\n'9223372036854775807'\n'9223372036854775808' // too large\n'-9223372036854775808' // also too large\n'aaaaaaaaaaaaaa' // =&gt; 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-02T21:48:54.770", "Id": "442473", "Score": "0", "body": "It is a good thinking to get the result without modifying `s`. Although personally I am against reimplementing built-in functions, unless one is buggy or highly inefficient. I am also not sure whether your version is faster, because I believe `StrToInt64` is implemented in assembly and your function has quite a few comparisons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-03T00:25:37.693", "Id": "442481", "Score": "0", "body": "Interesting results, 1 million loops with \"1234.5678;\": 32-bit: Mine = 120-125ms, yours 65-70ms. 64-bit: Mine = 90-95ms, yours... 15-20ms" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-03T05:27:42.487", "Id": "442510", "Score": "0", "body": "Regarding the number of comparisons: the first two comparisons are hopefully optimized by the compiler into a single comparison. The other ones probably don't hurt because branch prediction always predicts them correctly. The two comparisons with `limit10` can also be merged into a single `cmpq` instruction. All in all, I expect the generated machine code to be more efficient than the Delphi source code appears to be." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-02T20:56:52.180", "Id": "227358", "ParentId": "220522", "Score": "3" } } ]
{ "AcceptedAnswerId": "227358", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T18:42:40.923", "Id": "220522", "Score": "2", "Tags": [ "converting", "delphi" ], "Title": "Dephi: faster way to convert a \"dirty\" string to a number" }
220522
<p>I have a drive with many thousands of sound effects. The files have been stored on different operating systems and NAS devices over time and there are now duplicates of many files, but the filenames contain different UTC timestamps. For example:</p> <p><code>1-14 Crowded Bowling Alley (2016_06_28 02_14_41 UTC).aif</code></p> <p><code>1-14 Crowded Bowling Alley (2016_02_18 05_56_59 UTC).aif</code></p> <p>I would like to remove the duplicate files. There are also junk files left over from audio software and operating system indexing that I would like to remove. Using a copied subset of the data I have tested the following PowerShell script under PS version 5.1, it appears to give me what I'm after:</p> <pre><code># Remove files left over from audio editors Get-ChildItem -Name -Recurse -Filter "*.clip*" | Remove-Item Get-ChildItem -Name -Recurse -Filter "*.ptf" | Remove-Item Get-ChildItem -Name -Recurse -Filter "*.wfm" | Remove-Item Get-ChildItem -Name -Recurse -Filter "*.repeaks" | Remove-Item # Remove old indexing files Get-ChildItem -Name -Recurse -Filter "*.DS_STORE" | Remove-Item Get-ChildItem -Name -Recurse -Filter "._.*" | Remove-Item Get-ChildItem -Name -Recurse -Filter "Thumbs*.db" | Remove-Item Get-ChildItem -Name -Recurse -Filter "*.ini" | Remove-Item # Remove UTC stamp from all files (will fail on duplicates) Get-ChildItem -Recurse -Filter "*(?????????? ???????? UTC).*" | Rename-Item -newname { $_.basename.substring(0,$_.basename.length-26) + $_.Extension } # Remove files that still have the UTC stamp (they were the duplicates) Get-ChildItem -Name -Recurse -Filter "*(?????????? ???????? UTC).*" | Remove-Item </code></pre> <p>However, I would love to get a critique of the script and learn a few things. In particular it seems a little hacky to use an expected failed command as part of the workflow. It also seemed wise to get notes before I run it on the entire set of files.</p>
[]
[ { "body": "<p>While <code>-Filter</code> is usually the fastest way as it handled by the provider,<br>\nI'm not sure this is true compared to one <code>-Include</code> with an array which only recurses once instead of 8 times.</p>\n\n<pre><code>$Include = '*.clip*','*.ptf','*.wfm','*.repeaks','*.DS_STORE','._.*','Thumbs*.db','*.ini'\n\nGet-ChildItem -Recurse -Name -Include $Include | Remove-Item\n</code></pre>\n\n<p>As for the duplicates, your approach will only eliminate dupes in the same folder.<br>\nAn alternative would be grouping the output with a calculated property which strips off the date in parentheses. And then iterating the groups and sorting by whatever means, keeping only the first/last - removing the others.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T20:21:38.653", "Id": "220525", "ParentId": "220523", "Score": "1" } } ]
{ "AcceptedAnswerId": "220525", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T19:15:04.897", "Id": "220523", "Score": "3", "Tags": [ "powershell" ], "Title": "Removing duplicate audio files with different UTC timestamps in filenames, using PowerShell 5" }
220523
<p><strong>The task</strong></p> <p>is taken from <a href="https://leetcode.com/problems/first-unique-character-in-a-string/" rel="nofollow noreferrer">leetcode</a></p> <blockquote> <p>Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.</p> <p><strong>Examples:</strong></p> <p>s = "leetcode"</p> <p>return 0.</p> <p>s = "loveleetcode",</p> <p>return 2.</p> <p>Note: You may assume the string contain only lowercase letters.</p> </blockquote> <p><strong>My solution</strong></p> <pre><code>/** * @param {string} s * @return {number} */ function firstUniqChar(s) { const arr = Array.from([...s] .reduce((map, x, i) =&gt; map.set(x, !isNaN(map.get(x)) ? null : i) , new Map()) .values()); for(let i = 0; i &lt; arr.length; i++) { if (arr[i] !== null) { return arr[i]; } } return -1; }; </code></pre>
[]
[ { "body": "<p>Your solution looks rather map-happy.</p>\n\n<p>It is important to remember for this task that counting higher than 2 of any encountered letter is needless processing as is any processing on any letter after the earliest positioned unique letter.</p>\n\n<p>Also, doing a complete sweep of the input string may be ill-advised if the input string is of <em>considerable</em> length.</p>\n\n<p>Due to not being as well across .js as others here are, I'll post a humble <code>for</code> loop.</p>\n\n<pre><code>function firstNonRepeatedCharacterPosition(string) {\n    for (let char, pos, i = 0; i &lt; string.length; ++i) {\n        char = string.charAt(i);\n        pos = string.indexOf(char);\n        if (pos == i &amp;&amp; string.indexOf(char, i + 1) == -1) {\n            return pos;\n        } \n    }\n    return -1;\n}\n\nconsole.log(firstNonRepeatedCharacterPosition('abcbebc'));\n</code></pre>\n\n<p>It does make 3 function calls per iteration, but they aren't heavy ones, there is at most only one pass through the string, and early-return programming is in effect.</p>\n\n<ul>\n<li>Grab the letter at the incremented position. </li>\n<li>Find the earliest occurrence of that letter.</li>\n<li>Check if there is a later occurrence of the same letter.</li>\n</ul>\n\n<p>The later the unique letter exists (or if there are no unique letters), the more laborious my function is. On the other hand, if the first letter is unique, then you are finished in just 3 function calls.</p>\n\n<p>p.s. I lack the knowledge to interpret your js code, so I cannot review it beyond saying that it isn't very novice friendly.</p>\n\n<hr>\n\n<p>After Rotora's challenge, I was doubting myself, so I whacked this little battery of tests together:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function MickMacKusa(string) {\n for (let char, pos, i = 0; i &lt; string.length; ++i) {\n char = string.charAt(i);\n pos = string.indexOf(char);\n if (pos == i &amp;&amp; string.indexOf(char, i + 1) == -1) {\n return pos;\n } \n }\n return -1;\n}\n\nfunction RoToRa(string) {\n for (let char, pos, i = 0; i &lt; string.length; ++i) {\n char = string.charAt(i);\n if (string.indexOf(char, i + 1) == -1) {\n return i;\n } \n }\n return -1;\n}\n\nlet table = document.getElementById(\"test\"),\n row;\nfor (let i = 1; i &lt; table.rows.length; ++i) {\n row = table.rows[i];\n row.cells[3].innerHTML = MickMacKusa(row.cells[0].innerHTML);\n row.cells[4].innerHTML = RoToRa(row.cells[0].innerHTML);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;table id=\"test\" border=\"1\" cellpadding=\"4\"&gt;\n&lt;tr&gt;&lt;th&gt;Input&lt;/th&gt;&lt;th&gt;Letter&lt;/th&gt;&lt;th&gt;Index&lt;/th&gt;&lt;th&gt;MickMacKusa&lt;/th&gt;&lt;th&gt;RoTora&lt;/th&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;td&gt;abccbcba&lt;/td&gt; &lt;td&gt;-&lt;/td&gt; &lt;td&gt;-1&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;td&gt;abcbebc&lt;/td&gt; &lt;td&gt;a&lt;/td&gt; &lt;td&gt; 0&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;td&gt;abc&lt;/td&gt; &lt;td&gt;a&lt;/td&gt; &lt;td&gt; 0&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;td&gt;aabbc&lt;/td&gt; &lt;td&gt;c&lt;/td&gt; &lt;td&gt; 4&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;td&gt;abcba&lt;/td&gt; &lt;td&gt;c&lt;/td&gt; &lt;td&gt; 2&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;td&gt;abba&lt;/td&gt; &lt;td&gt;-&lt;/td&gt; &lt;td&gt;-1&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;td&gt;abaa&lt;/td&gt; &lt;td&gt;b&lt;/td&gt; &lt;td&gt; 1&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;td&gt;aabcbcbca&lt;/td&gt; &lt;td&gt;-&lt;/td&gt; &lt;td&gt;-1&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;/table&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:34:58.747", "Id": "426175", "Score": "0", "body": "I haven't tried it out, but I think you don't need to use `indexOf` twice. Just `if (string.indexOf(char, i + 1) == -1) {` would do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:47:07.977", "Id": "426179", "Score": "0", "body": "As `i` gets closer to the tail end, there will be a greater chance that the duplicate letter will be \"behind\" (left of) `i` rather than \"in front\" (to the right of it). Consider the third `b` in my sample. It is not a unique letter, but would be considered one because there are no `b`s to the right to find." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T11:50:09.673", "Id": "426282", "Score": "0", "body": "But there never can be a duplicate \"behind\" `i`, because they have already been tested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T11:54:07.730", "Id": "426284", "Score": "0", "body": "On `abcbebc`, when `i = 5` and `char = 'b'`, looking for the next `b` from `i + 1` will return `-1`, but that character is not unique. I could be wrong, I'll consider your advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T13:26:05.020", "Id": "426299", "Score": "0", "body": "@RoTora I've included a runnable test script in my answer. If I have misunderstood your recommendation, please clarify." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T13:48:26.183", "Id": "426303", "Score": "0", "body": "But you never reach `i = 5`. Once the algorithm reaches `i = 1` `indexOf('b', i + 1)` will return `3` for the second 'b' and it will exit sucessfully." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T13:50:02.173", "Id": "426304", "Score": "0", "body": "Did you run my snippet, am I executing your proposed technique as you expect?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T12:20:34.123", "Id": "220558", "ParentId": "220528", "Score": "3" } }, { "body": "<ul>\n<li>Never indent as you have done. This make code very unreadable due to the long lines.</li>\n</ul>\n<p><code>Map.values()</code> creates an iteratable object. It does not require an array to be created and is <span class=\"math-container\">\\$O(1)\\$</span> storage as it iterates over the already stored values</p>\n<p>You have forced the map to be stored as an array. <code>Array.from(map.values())</code> That means that it must be iterated and stored <span class=\"math-container\">\\$O(n)\\$</span> complexity and storage best case. If you just kept the map and iterated to find the result you could have a best case of <span class=\"math-container\">\\$O(1)\\$</span> to find the result.</p>\n<p>Always iterate iteratable objects to reduce memory uses and if there is an early exit to reduce CPU use and complexity.</p>\n<h2>Rewrite</h2>\n<p>Is around 2* as fast depending on input</p>\n<pre><code>function firstUniqChar(str) {\n const counts = new Map();\n var idx = 0;\n for (const c of str) { // iterate to avoid storing array of characters\n if (counts.has(c)) { counts.get(c).count ++ }\n else { counts.set(c, {idx, count: 1}) }\n idx++;\n }\n for (const c of counts.values()) {\n if (c.count === 1) { return c.idx }\n }\n return - 1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T17:44:01.273", "Id": "426215", "Score": "0", "body": "this looks like a good solution, but is there any way we could leverage the constraint \"string contains only lowercase letters\" to our advantage?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T17:58:20.760", "Id": "426217", "Score": "0", "body": "@I.Am.A.Guy JS has unicode Strings and upper and lowercase characters are spread throughout the character set not just `[a-z]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T18:03:48.773", "Id": "426218", "Score": "0", "body": "Interesting! However, in the case that it's just `a-z`, we could check if map length exceeds 26. Depends on how much overhead it would be though. I'm thinking not much if we put it in the else clause. What do you think?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T14:32:21.267", "Id": "220570", "ParentId": "220528", "Score": "3" } } ]
{ "AcceptedAnswerId": "220570", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T21:12:04.660", "Id": "220528", "Score": "1", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6" ], "Title": "First Unique Character in a String" }
220528
<p>I want to implement my own custom observable class so I can have a hierarchy of components and the closest defined configuration item bubbles to the front.</p> <pre><code>&lt;form controlClasses="formDefinedClass"&gt; &lt;group controlClasses="groupDefinedClass"&gt; &lt;control controlClasses="controlDefinedClass"&gt;&lt;/control&gt; &lt;/group&gt; &lt;/form&gt; </code></pre> <p>The setter property of these inputs then passes the value to the next method of an observable.</p> <pre><code>@Input() set controlClasses(value: string) { this.controlClasses$.next(value); } </code></pre> <p>My goal is to have the closest config push to the front. In the above example on the control the controlClasses observable will emit 'controlDefinedClass' but if I was to remove the property it would emit 'groupDefinedClass' as it is the closest config in the control hierarchy.</p> <p>I have spent a bit of time looking through the source code of the rxjs repository and was looking for some advise on implementing my own observable classes. To solve the above requirement I have come up with two data structures.</p> <p>One is the StackSubject.</p> <pre><code>import { Observable, Subject, Subscriber, Subscription, SubscriptionLike, ObjectUnsubscribedError } from 'rxjs'; import { StackSubjectSubscription } from './stack-subject-subscription'; export class StackSubject&lt;T&gt; extends Subject&lt;T&gt; { constructor(private _value: T, private defaultValue: T, private parent$?: Observable&lt;T&gt;) { super(); } private parentSubscription: Subscription; private parentValue: T; get value(): T { return this.getValue(); } complete() { super.complete(); this.parentUnsubscribe(); } unsubscribe() { super.unsubscribe(); this.parentUnsubscribe(); } parentUnsubscribe() { if (this.parentSubscription) { this.parentSubscription.unsubscribe(); } this.parentSubscription = undefined; } /** @deprecated This is an internal implementation detail, do not use. */ _subscribe(subscriber: Subscriber&lt;T&gt;): Subscription { if (!this.parentSubscription &amp;&amp; this.parent$ &amp;&amp; !this.closed &amp;&amp; !this.hasError &amp;&amp; !this.isStopped) { this.parentSubscription = this.parent$.subscribe(value =&gt; { this.parentValue = value; super.next(this.calcValue()); }); } const subscription = super._subscribe(subscriber); if (subscription &amp;&amp; !(&lt;SubscriptionLike&gt;subscription).closed) { subscriber.next(this.calcValue()); } return new StackSubjectSubscription(this, subscription); } getValue(): T { if (this.hasError) { throw this.thrownError; } else if (this.closed) { throw new ObjectUnsubscribedError(); } else { return this.calcValue(); } } private calcValue() { return this._value || this.parentValue || this.defaultValue; } next(value: T): void { this._value = value; super.next(this.calcValue()); } } </code></pre> <p>Demo at <a href="https://stackblitz.com/edit/angular-tdajza?file=src%2Fapp%2Fstack-subject.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-tdajza?file=src%2Fapp%2Fstack-subject.ts</a></p> <p>The other is the PushStack.</p> <pre><code>import { Observable, BehaviorSubject, Subscription, SubscriptionLike, combineLatest, Subscriber } from 'rxjs'; import { map } from 'rxjs/operators'; export class PushStack&lt;T&gt; extends Observable&lt;T&gt; implements SubscriptionLike { private behaviorSubject$ = new BehaviorSubject(this._value); private observable$ = this.parent$ ? combineLatest(this.behaviorSubject$, this.parent$).pipe( map(([behaviorSubject, parent]) =&gt; behaviorSubject || parent || this.defaultValue) ) : this.behaviorSubject$.pipe(map(behaviorSubject =&gt; behaviorSubject || this.defaultValue)); get closed(): boolean { return this.behaviorSubject$.closed; } constructor(private _value: T, private defaultValue: T, private parent$?: Observable&lt;T&gt;) { super(); } complete() { this.behaviorSubject$.complete(); } unsubscribe() { this.behaviorSubject$.unsubscribe(); } _subscribe(subscriber: Subscriber&lt;T&gt;): Subscription { return this.observable$.subscribe(subscriber); } next(value: T): void { this.behaviorSubject$.next(value); } } </code></pre> <p>Demo at <a href="https://stackblitz.com/edit/angular-cnrttk?file=src%2Fapp%2Fpush-stack.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-cnrttk?file=src%2Fapp%2Fpush-stack.ts</a></p> <p>Should I be implementing the _subscribe method? The rxjs classes for subjects and behavour subjects do so but also have the comment /** @deprecated This is an internal implementation detail, do not use. */ Is this implementation detail likely to change in a future version of rxjs?</p> <p>Is having a subject that subscribes to another observable as in my StackSubject good practice?</p> <p>Is creating a private observable and exposing the subscribe of the private observable to implement my observable as in my PushStack good practice?</p> <p>The two methods both fulfil my requirements but I personally prefer the push stack method but the stack subject offers the additional benefit of having the getValue() method and value property so you can get the closest push value without needing to subscribe.</p> <p>Are there any devs who have implemented custom observable classes or have worked on the rxjs repository who can provide an opinion on my implementation of these observables?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T22:58:57.287", "Id": "220531", "Score": "3", "Tags": [ "typescript", "observer-pattern", "rxjs" ], "Title": "Implementing custom observable classes" }
220531
<p>I have the following function and code snippet to extract cell values for multiple years, format it, and save to a list. Each raster has 365 bands — one for each day. A separate operation is performed on each flattened list <code>pr_flt</code> which contains daily cell values of XY for 1991-2015. The cursor contains XY coordinates for each cell. The following code works but it takes hours to finish due to the huge amount of data and possible use of lists instead of multidimensional arrays. I am wondering if there are any suggestions to reduce the runtime of the code, if possible. </p> <pre><code>import arcpy def row_to_values(row): values = [] for col in row: if isinstance(col, unicode) and col != u'f': # split and convert all entries to float values += (float(v) for v in col.split(',')) else: values.append(col) return values with arcpy.da.SearchCursor(fc, fields) as cursor: for idx, row in enumerate(cursor): pt_annual_lists = [] pt_loc = str(row[0]) + str(" ") + str(row[1]) for y in xrange(1991,2016,1): pt_year_list = [] result = arcpy.GetCellValue_management(in_raster = "D:/temp/ras" + str(y) + ".tiff", location_point = pt_loc, band_index="") cell_value = result.getOutput(0) pt_year_list.append(cell_value) cell_value = [s.replace('\\n', ',') for s in pt_year_list] pt_annual_lists.append(row_to_values(cell_value)) # flatten list of lists pr_str = [val for sublist in pt_annual_lists for val in sublist] pr_flt = [float(i) for i in pr_str] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T23:11:42.930", "Id": "426103", "Score": "0", "body": "If you're truly interested in performance don't code in python, use C++ or C# if you find C++ too daunting. If the total size of the raster is smaller than your available memory you can read the whole raster into an array (RasterToNumpyArray https://resources.arcgis.com/en/help/main/10.2/index.html#//03q300000029000000) then index the array rather than trying to read a single cell at a time; if your raster is compressed the GetCellValue needs to work very hard to get a single cell value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T04:17:49.233", "Id": "426111", "Score": "0", "body": "You would be more likely to get an answer if you included enough information to actually run the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T05:28:06.473", "Id": "426118", "Score": "1", "body": "Michael, that's not really true. Numpy is typically about as fast as handwritten c code due to being a heavily optimized library. Numpy is slow when people think it is C and do loops" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T08:41:46.667", "Id": "426142", "Score": "0", "body": "@200_success I have yearly NetCDF files with 365 bands. Please suggest how to include that information here for anyone to try and run my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T18:18:07.730", "Id": "426221", "Score": "0", "body": "Use of coordinates from *.csv file instead of using `arcpy.da.SearchCursor` has reduced run time by 150%. Other bottleneck is `arcpy.GetCellValue_management` which is taking 95% of the processing time in each iteration. Please suggest any open source library to extract pixel values faster." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T21:39:37.453", "Id": "220535", "Score": "2", "Tags": [ "python", "performance", "python-2.x", "numpy", "arcpy" ], "Title": "Extract cell values from multiband rasters" }
220535
<p>I need a rather simple file encryptor/decryptor in Python, after some research, I decided to use tye pynacl library reading the file in blocks, writing them back out, and then at the end using Blake2b to generate a signature for the file. Each file is encrypted with a unique key, which will be distributed along side the encrypted file, with the file key RSA encrypted using a pre-shared key pair, and that whole message signed with ECDSA to verify it came from me. </p> <p>The encryption/decryption example code: </p> <pre><code>import base64 import struct import nacl.secret import nacl.utils import nacl.hashlib import nacl.hash BUFFER_SIZE = 4 * (1024 * 1024) def read_file_blocks(file, extra_bytes=0): while True: data = file.read(BUFFER_SIZE + extra_bytes) if not data: break yield data def hmac_file(file, key): blake = nacl.hashlib.blake2b(key=key) with open(file, 'rb') as in_file: for block in read_file_blocks(in_file): blake.update(block) return blake.hexdigest() def encrypt_archive(archive_name, encrypted_name): key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE) #Use 4 bytes less than the nonce size to make room for the block counter nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE - 4) block_num = 0 box = nacl.secret.SecretBox(key) with open(archive_name, 'rb') as in_file, open(encrypted_name, 'wb') as out_file: for data in read_file_blocks(in_file): #Append the block counter to the nonce, so each block has a unique nonce block_nonce = nonce + struct.pack("&gt;I", block_num) block = box.encrypt(data, block_nonce) out_file.write(block.ciphertext) block_num += 1 hmac_key = nacl.hash.sha256(key + nonce, encoder=nacl.encoding.RawEncoder) output = {} output['key'] = base64.b64encode(key + nonce) output['signature'] = hmac_file(encrypted_name, hmac_key) return output def decrypt_archive(encrypted_name, archive_name, key_info): key_bytes = base64.b64decode(key_info['key']) key = key_bytes[:nacl.secret.SecretBox.KEY_SIZE] nonce = key_bytes[nacl.secret.SecretBox.KEY_SIZE:] extra_bytes = nacl.secret.SecretBox.MACBYTES hmac_key = nacl.hash.sha256(key_bytes, encoder=nacl.encoding.RawEncoder) hmac = hmac_file(encrypted_name, hmac_key) if hmac != key_info['signature']: print('hmac mismatch') return block_num = 0 box = nacl.secret.SecretBox(key) with open(encrypted_name, 'rb') as in_file, open(archive_name, 'wb') as out_file: # nacl adds a MAC to each block, when reading the file in, this needs to be taken into account for data in read_file_blocks(in_file, extra_bytes=extra_bytes): block_nonce = nonce + struct.pack("&gt;I", block_num) block = box.decrypt(data, block_nonce) out_file.write(block) block_num += 1 key_info = encrypt_archive("C:\\temp\\test.csv", "C:\\temp\\test.enc") print(key_info) decrypt_archive("C:\\temp\\test.enc", "C:\\temp\\test.enc.csv", key_info) </code></pre> <p>Outside of general mistakes, the two things I'm doing I'm not entirely sure are sound:</p> <ol> <li><p>To keep the block nonces unique, I create a slightly smaller random list of bytes for the nonce than required, then when encrypting the blocks I append the block number, as a four byte integer to the nonce. </p></li> <li><p>When generating the blake2b hash, for a key, I hash the file key and nonce. This seems somewhat useless overall, since if they have the key and nonce, they could just replace the file. Although, I can't really think of a better alternative that doesn't have similar weaknesses. Should I just ditch that bit, since NaCl does per-block MACs anyhow? (which I found out only after I wrote the hmac code)</p></li> </ol>
[]
[ { "body": "<p>Code / protocol comments under the code sections.</p>\n\n<pre><code>def read_file_blocks(file, extra_bytes=0):\n while True:\n data = file.read(BUFFER_SIZE + extra_bytes)\n</code></pre>\n\n<p>At least specify why the extra bytes are used and document what <code>extra-bytes</code> argument means.</p>\n\n<pre><code>def hmac_file(file, key):\n</code></pre>\n\n<p>Why would you go over the entire file and then dispose of the read bytes only to perform HMAC? You just processed all the blocks in memory! Why blake2b instead of one of the more common SHA-2 hashes?</p>\n\n<pre><code>#Use 4 bytes less than the nonce size to make room for the block counter\n</code></pre>\n\n<p>I'll bet that this isn't required; undoubtedly the counter is already included. Maybe you can point to a specific requirement to include a block counter every 4MiB?</p>\n\n<pre><code>hmac_key = nacl.hash.sha256(key + nonce, encoder=nacl.encoding.RawEncoder)\n</code></pre>\n\n<p>At least use HMAC instead of a hash to derive keys, the is a poor man's KDF.</p>\n\n<pre><code>output['key'] = base64.b64encode(key + nonce)\n</code></pre>\n\n<p>Sorry, output <em>what?</em> The key?</p>\n\n<pre><code>output['signature'] = hmac_file(encrypted_name, hmac_key)\n</code></pre>\n\n<p>CryptoBox uses an <strong>authenticated cipher</strong>. No need at all to HMAC it again.</p>\n\n<blockquote>\n <p>Algorithm details:<br>\n Encryption: Salsa20 stream cipher<br>\n Authentication: Poly1305 MAC </p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T00:57:59.207", "Id": "238212", "ParentId": "220536", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T01:15:40.507", "Id": "220536", "Score": "3", "Tags": [ "python", "cryptography" ], "Title": "File Encryption using pynacl" }
220536
<p>I've been a fan of coroutines and asynchronous programming for a while, and I recently took a trip down memory lane to when I was using Python's <code>tkinter</code> module for a GUI. I wanted to combine the two worlds, one of smooth coroutines and one of callbacks.</p> <p>My hope is to find a better solution for the basic event loop, implemented in <code>Window._coro_step</code>. The current way of calling again in 1 ms seems too hackish, but the tkinter mainloop has no way to be run in non-blocking steps. (Please take a look at my formatting and style too. Sorry for the lack of comments.)</p> <p>Here's my unfinished but working code:</p> <pre class="lang-py prettyprint-override"><code>import tkinter from collections import deque from contextlib import closing from types import coroutine class Window: def __init__(self, title, min_size, start_size, screens=None, gvars=None): if screens is None: screens = {} if gvars is None: gvars = {} self.title = str(title) self.min_size = tuple(min_size) self.start_size = tuple(start_size) self.screens = dict(screens) self.gvars = dict(gvars) self.current = None self._events = deque() self._window = None self._canvas = None self._coro = None self._wait = None def run(self, start_screen, start_title=None): self._window = window = tkinter.Tk() window.minsize(*self.min_size) window.rowconfigure(1, weight=1) window.columnconfigure(1, weight=1) window.title(start_title if start_title is None else self.title) self._canvas = canvas = tkinter.Canvas(window, highlightthickness=0) canvas.rowconfigure(1, weight=1) canvas.columnconfigure(1, weight=1) canvas.grid(row = 1, column=1, sticky='nsew') window.geometry('x'.join(map(str, self.start_size))) Widget.canvas = canvas self.switch(start_screen) window.after(1, self._coro_step) with closing(self): window.mainloop() def switch(self, screen_name): # Switch the current coroutine to 'screen_name' canvas = self._canvas if self.current is not None: self._coro.close() for event_name in self.current.event_names: canvas.unbind(event_name) if screen_name == '': current = self.current else: self.current = current = self.screens[screen_name] self._coro, self._wait = current.setup(self, canvas, self.gvars) for event_name in current.event_names: canvas.bind(event_name, self._events.append) def destroy(self): self._window.destroy() self._coro.close() self._coro = None def close(self): # Idempotent try: self._window.destroy() except: pass if self._coro is not None: try: self._coro.close() except: pass self._coro = None async def aevents(self, *, forever=False, ty='get_events'): coro = getattr(self, ty) multiple = ty.endswith('events') if forever and multiple: while True: for event in await coro(): yield event elif forever: while True: yield await coro() elif multiple: for event in await coro(): yield event else: yield await coro() def _coro_step(self): if self._coro is None: return # Mini event loop that doesn't block while True: if ( type(self._wait) is not tuple or self._wait[0] not in { 'get_event', 'get_events', 'poll_event', 'poll_events', } ): exc = ValueError('invalid yield type') self._coro.throw(exc) raise exc # In case the coroutine yielded another value allow_empty, allow_multiple = self._wait[0].split('_') allow_empty = (allow_empty == 'poll') # 'get' or 'poll allow_multiple = (allow_multiple == 'events') # 'event' or 'events if allow_multiple: send = [] try: while True: send.append(self._events.popleft()) except IndexError: if not allow_empty and not send: # Reschedule for a later time self._window.after(1, self._coro_step) return else: send = None try: send = self._events.popleft() except IndexError: if not allow_empty: # Reschedule for a later time self._window.after(1, self._coro_step) return try: self._wait = self._coro.send(send) except StopIteration as e: result = e.value if result in {'return', None}: self.destroy() return else: self.switch(result) else: if allow_multiple and allow_empty: # Reschedule for a later time self._window.after(1, self._coro_step) return # Wrappers around decorated coroutines async def get_event(self): return await self._get_event() async def get_events(self): return await self._get_events() async def poll_event(self): return await self._poll_event() async def poll_events(self): return await self._poll_events() # Raw yielding coroutines @staticmethod @coroutine def _get_event(): return (yield ('get_event',)) @staticmethod @coroutine def _get_events(): return (yield ('get_events',)) @staticmethod @coroutine def _poll_event(): return (yield ('poll_event',)) @staticmethod @coroutine def _poll_events(): return (yield ('poll_events',)) class Screen: event_names = [ '&lt;ButtonPress&gt;', '&lt;ButtonRelease&gt;', '&lt;KeyPress&gt;', '&lt;KeyRelease&gt;', '&lt;Configure&gt;', '&lt;Deactivate&gt;', '&lt;Destroy&gt;', '&lt;Enter&gt;', '&lt;Motion&gt;', '&lt;Leave&gt;', '&lt;Expose&gt;', '&lt;FocusIn&gt;', '&lt;FocusOut&gt;', '&lt;MouseWheel&gt;', '&lt;Visibility&gt;', ] def __init__(self, name='', screen=None): if screen is None: screen = lambda window, canvas, gvars: iter([]) self.name = name self._func_screen = screen self._gen_screen = None def __repr__(self): return f'&lt;{type(self).__name__} name={self.name}&gt;' def setup(self, window, canvas, gvars): self._gen_screen = gen_screen = self._func_screen(window, canvas, gvars) return gen_screen, gen_screen.send(None) class Widget: canvas = None def __init__(self): self.canvas = type(self).canvas self.id = None def __repr__(self): return f'&lt;{type(self).__name__} at {hex(id(self))}&gt;' def draw(self): ... def check(self, event): ... def cget(self, item): self.canvas.itemcget(self.id, item) def config(self, **kwargs): self.canvas.itemconfig(self.id, **kwargs) class RectWidget(Widget): def __init__(self, x1, y1, x2, y2, colour='#000000'): super().__init__() self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.colour = colour def draw(self): if self.id is not None: self.canvas.delete(self.id) self.id = self.canvas.create_rectangle( self.x1, self.y1, self.x2, self.y2, fill=self.colour, width=0, ) return self.id def check(self, event): super().check(event) def touches(self, x=None, y=None): if x is None: x = self.canvas.winfo_pointerx() - self.canvas.winfo_rootx() if y is None: y = self.canvas.winfo_pointery() - self.canvas.winfo_rooty() x1, x2 = sorted([self.x1, self.x2]) y1, y2 = sorted([self.y1, self.y2]) return x1 &lt;= x &lt;= x2 and y1 &lt;= y &lt;= y2 class TextWidget(Widget): def __init__(self, x, y, text='', colour='#000000', font='Helvetica', size=50): super().__init__() self.x = x self.y = y self.text = text self.colour = colour self.font = font self.size = size def draw(self): if self.id is not None: self.canvas.delete(self.id) self.id = self.canvas.create_text( self.x, self.y, text=self.text, fill=self.colour, font=(self.font, str(self.size)), ) return self.id def check(self, event): super().check(event) async def main_screen(window, canvas, gvars): canvas.delete('all') canvas.configure(bg='#7777FF') width, height = canvas.winfo_width(), canvas.winfo_height() scale = min(width/320, height/220) pressed = False buttons = { (-60, -25, 60, 5): {'return': 'main'}, (-60, 15, 60, 45): {'return': 'main'}, (-60, 55, 60, 85): {'return': 'return'}, } text = { (width/2, scale*40, 'Async Window', 30): {}, (width/2, height/2 - scale*10, 'MAIN', 18): {}, (width/2, height/2 + scale*30, 'OTHER', 18): {}, (width/2, height/2 + scale*70, 'QUIT', 18): {}, } for info in buttons: x1, y1, x2, y2 = info x1, x2 = map(lambda i: width/2 + scale*i, (x1, x2)) y1, y2 = map(lambda i: height/2 + scale*i, (y1, y2)) rect_widget = RectWidget(x1, y1, x2, y2, '') rect_widget.colour = '#EEEEEE' if rect_widget.touches() else 'white' rect_widget.draw() buttons[info]['widget'] = rect_widget for info in text: x, y, t, size = info text_widget = TextWidget(x, y, t, '#CCCCCC', size=round(size*scale)) text_widget.draw() text[info]['result'] = text_widget async for event in window.aevents(forever=True): e_type = str(event.type) if e_type == 'Destroy': return elif e_type == 'Configure': return '' elif e_type == 'Motion': x, y = event.x, event.y for pos, info in buttons.items(): button = info['widget'] if button.touches(x, y): button.config(fill='#DDDDDD' if pressed else '#EEEEEE') else: button.config(fill='white') if pressed == button: pressed = True elif e_type == 'ButtonPress': x, y = event.x, event.y pressed = True for pos, info in buttons.items(): button = info['widget'] if button.touches(x, y): button.config(fill='#DDDDDD') pressed = button else: button.config(fill='white') elif e_type == 'ButtonRelease': x, y = event.x, event.y for pos, info in buttons.items(): button = info['widget'] if button.touches(x, y): if pressed == button: return info['return'] else: button.config(fill='#EEEEEE') else: button.config(fill='white') pressed = False main = Screen('main', main_screen) window = Window('Async Window', (320, 220), (350, 250), {'main', main}) if __name__ == '__main__': window.run('main') <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>I've been working on this for a while now, and from that hard work is <a href=\"https://github.com/GeeTransit/tkio\" rel=\"nofollow noreferrer\">tkio</a>, a <a href=\"https://github.com/dabeaz/curio\" rel=\"nofollow noreferrer\">curio</a> inspired asynchronous library for Python's <code>tkinter</code>. Here are some notable changes from my previous design.</p>\n\n<ol>\n<li><p>I removed the idea of screens / windows and added in tasks / loop (from curio and asyncio). The idea about screens was me thinking about video games and their different menus and such. It wouldn't apply to other things like a Sudoku solver or bootleg MS Paint as they would only have one \"screen\". Tasks are something well known and when combined with synchronizing can replicate the screen layout (one task runs at a time).</p></li>\n<li><p>The loop is run from <code>tkinter</code>'s <code>wait_window</code> method. Not many people use this but it is basically <code>mainloop</code> but one that ends when the specified widget is destroyed. With this in mind, <code>mainloop</code> could just be <code>wait_window(root)</code> where <code>root</code> is the top level <code>Tk</code> instance.</p></li>\n<li><p>The event and <code>after</code> callbacks run the loop. This means that there needs to be a difference between sending in a coroutine to run versus a suspend point. Luckily there are asynchronous generators which can suspend in between yield points. The loop can be run by sending in a coroutine using <code>cycle = loop.asend(coro)</code> on the loop and event / <code>after</code> callbacks can run the cycle using <code>cycle.send(\"EVENT_WAKE\")</code> or something similar.</p></li>\n</ol>\n\n<p>Everything else is from curio: traps, cancellation, and timeout just to name a few. I've also used many different resources to create this and it has been a great experience. I hope that this will be of help to someone and upgrade <code>tkinter</code> to the async world.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T01:10:51.380", "Id": "226224", "ParentId": "220539", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T02:57:43.773", "Id": "220539", "Score": "7", "Tags": [ "python", "python-3.x", "event-handling", "async-await", "tkinter" ], "Title": "Simple integration of async and tkinter in Python" }
220539
<p>I am trying to search a single linked list with a particular value and delete it. Only the first occurrence of the value.</p> <pre><code>typedef struct node { int val; struct node * next; } node_t; </code></pre> <p>So my code is:</p> <pre><code>int remove_by_value(node_t ** head, int val) { /* TODO: fill in your code here */ node_t *temp = *head; if(*head == NULL) return -1; if((*head)-&gt;next == NULL &amp;&amp; (*head)-&gt;val == val) { *head = NULL; return 0; } while(temp-&gt;next-&gt;val != val) { temp = temp-&gt;next; } temp-&gt;next=temp-&gt;next-&gt;next; return 0; } </code></pre> <p>The above solution works fine. My question is:</p> <ol> <li>Is this correct way of doing it? Because when I searched online, there are different solutions.</li> <li>Am I missing any corner cases? I check for empty list and whether the head node contains the first occurrence.</li> </ol> <p>Please help me improve my code. Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T11:39:22.730", "Id": "426157", "Score": "1", "body": "Do you have a 100% guarantee that the value to delete will always be in the list? Otherwise you will get into trouble, since there seems to be a lack of `NULL` checking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T12:42:26.400", "Id": "426167", "Score": "3", "body": "It would be better if we could see all of the code, right now it isn't clear but there may be a memory leak because the node is never deleted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T17:09:20.983", "Id": "426208", "Score": "4", "body": "What's not to love about C? About 20 lines of code, and already two memory issues to ruin your day :-D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:33:45.730", "Id": "426457", "Score": "1", "body": "I strongly suspect this comes from a programming-challenge. If so, please state the requirements. I don't see usage here and it's currently unclear who's responsible for testing this. Online judges aren't necessarily good judges, so they may say it works fine while missing some obvious edge-cases. You say you check for (at least) 2 things, but have you tested whether you actually do this correctly? Where is the rest of your linked-list defined and does that part work as intended too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:56:57.330", "Id": "426468", "Score": "0", "body": "@Mast. Not really a challenge. In this link, https://www.learn-c.org/en/Linked_lists\nyou see an Exercise in the bottom. I am trying to solve it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T09:19:45.490", "Id": "220548", "Score": "1", "Tags": [ "c", "linked-list" ], "Title": "Linked list delete a node with a particular value" }
220548
<p>i made an audio player in html5 for learning purposes, also i tried to use BEM pattern with sass (i dont know if i did it well) i also encapsuled my code as much as possible, but i think i can make it better, maybe i can include some js pattern or maybe i can divide my code in different files, basically im just asking for a code review.</p> <p>here is the repo <a href="https://github.com/Zybax/Custom-HTML5-Audio-Player" rel="nofollow noreferrer">https://github.com/Zybax/Custom-HTML5-Audio-Player</a></p> <p>Thank you</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const Player = function(){ const audioTrack = document.querySelector('#audioPlayer'); const playButton = document.querySelector('#playButton'); const timeline = document.querySelector('#timeline'); const progressionBar = document.querySelector('#progression-bar '); const playhead = document.querySelector('#playhead'); const totalTime = document.querySelector('#timer-total-time'); const currentTime = document.querySelector('#timer-current-time'); const volumeIcon = document.querySelector('#volume-icon'); const volumeBar = document.querySelector('#volume-bar'); const volumeLine = document.querySelector('#volume-line'); const volumeHead = document.querySelector('#volume-head'); let duration; // Play and pause audio function toogleAudio(){ if (audioTrack.paused){ playButton.classList.replace("fa-play","fa-pause"); audioTrack.play(); } else { playButton.classList.replace("fa-pause","fa-play"); audioTrack.pause(); } } // Update the timer and the progression bar function timeUpdate() { if (!duration) getTrackDuration(); if ( audioTrack.currentTime === duration){ playButton.classList.replace("fa-pause","fa-play"); } timerUpdate(); progressionUpdate(); } // Update the timer function timerUpdate() { const totalMinutes = parseInt(duration / 60, 10); const totalSeconds = parseInt(duration % 60); let currentMinutes = parseInt(audioTrack.currentTime / 60, 10); let currentSeconds = parseInt(audioTrack.currentTime % 60); totalTime.innerHTML = totalMinutes + ":" + totalSeconds; currentTime.innerHTML = currentMinutes + ":" + currentSeconds; } // Fills the progression bar function progressionUpdate() { let playPercent = 100 * (audioTrack.currentTime / duration); timeline.style.width = playPercent + "%"; playhead.style.marginLeft = (playPercent - 1.2) + "%"; } // Gets audio file duration function getTrackDuration(){ if(audioTrack.readyState &gt; 0) { duration = audioTrack.duration; } } // Returns elements left position relative to top-left of viewport function getPosition(el) { return el.offsetLeft; } // Sets new position of the progression bar when clicked function setProgressionPosition(event){ if (!duration) getTrackDuration(); audioTrack.currentTime = (clickPercent(event, progressionBar) * duration); } // Toggle the volume function toogleVolume(){ if (audioTrack.muted){ volumeIcon.classList.replace("fa-volume-mute","fa-volume-up"); volumeLine.style.display = 'block'; volumeHead.style.display = 'block'; audioTrack.muted = false; } else { volumeIcon.classList.replace("fa-volume-up","fa-volume-mute"); volumeLine.style.display = 'none'; volumeHead.style.display = 'none'; audioTrack.muted = true; } } // Update the volume and the volume bar function volumeUpdate(event) { volumeLine.style.display = 'block'; volumeHead.style.display = 'block'; setVolume(event); volumeBarUpdate(); } // Sets audio volume function setVolume(event){ audioTrack.volume = clickPercent(event, volumeBar); } // Fills the volume bar function volumeBarUpdate() { let volumePercent = 100 * (audioTrack.volume / 1); volumeLine.style.width = volumePercent + "%"; volumeHead.style.marginLeft = (volumePercent - 6) + "%"; } // Returns the percent of the bar when clicked related to the bar's width function clickPercent(event, bar) { const newPercent = (event.clientX - getPosition(bar)) / bar.offsetWidth; return newPercent; } // Removes events on mouse up function mouseUpEventRemove() { window.removeEventListener('mousemove', playHeadMove, true); window.removeEventListener('mousemove', volumeHeadMove, true); } // Adds mousemove event on mousedown with a specified function function mouseDown(event, func){ window.addEventListener('mousemove', func, true); } function playHeadMove(event){ setProgressionPosition(event); } function volumeHeadMove(event){ volumeUpdate(event); } // Listeners function addListeners(){ audioTrack.addEventListener("timeupdate", timeUpdate, false); playButton.addEventListener('click', toogleAudio, false); progressionBar.addEventListener("click", setProgressionPosition, false); progressionBar.addEventListener("mousedown", function(event){mouseDown(event, playHeadMove)}, false); playhead.addEventListener('mousedown', function(event){mouseDown(event, playHeadMove)}, false); volumeBar.addEventListener("click", volumeUpdate, false); volumeBar.addEventListener('mousedown', function(event){mouseDown(event, volumeHeadMove)}, false); volumeIcon.addEventListener("click",toogleVolume, false); volumeHead.addEventListener('mousedown', function(event){mouseDown(event, volumeHeadMove)}, false); window.addEventListener('mouseup', mouseUpEventRemove, false); } window.onload = addListeners(); } export default Player();</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T09:25:41.553", "Id": "220549", "Score": "1", "Tags": [ "javascript", "html5", "audio", "sass" ], "Title": "HTML5 Custom Audio Player with SASS" }
220549
<p>I have the following Python script. The purpose of the script is to extract text from PDFs. I use textract for that because soon I realized there is no easy way to check if a page contains an image or not. So I extract the whole text using textract. </p> <p>The workflow is like this. <code>main()</code> parses each pdf file from a folder, I extract the text, I search for keyword strikes and then I export the result to a csv file inside folder <code>output_results</code>.</p> <p>What I can fix on my logic? What can I change in my code? I find it messy, how I can clean it up?</p> <pre class="lang-py prettyprint-override"><code>import textract import os import csv class PdfMiner(): path = os.getcwd() + '/folderForPdf/' output_path = os.getcwd() + '/output_results/' def __init__(self): pass def main(self): for self.filename in os.listdir(self.path): self.text = (PdfMiner().extract_text_from_pdf(self.path + self.filename)) self.keyword_strike_dict = PdfMiner().keyword_strike(self.text) if bool(self.keyword_strike_dict): PdfMiner().output_to_csv(self.filename, self.keyword_strike_dict) def keyword_strike(self, text, keyword_strike_dict={}): '''keyword_strike function counts how many times a specific keyword occurs''' self.keyword_strike_dict = {} self.text = text self.keywords_list = PdfMiner().extract_keywords() for keyword in self.keywords_list: if keyword in text.decode('utf-8'): self.keyword_strike_dict[keyword] = text.decode('utf-8').count(keyword) return self.keyword_strike_dict def extract_keywords(self, keywords_list=None): '''function extract_keywords extract the keywords from file keywords.txt, into a list''' keywords_list = [] with open('keywords.txt', 'r', encoding='utf8') as keywords_file: for keyword in keywords_file: keywords_list.append(keyword.strip('\n')) return keywords_list def extract_text_from_pdf(self, file_destination, text=None): '''extract_text_from_pdf''' self.file_destination = file_destination text = textract.process(self.file_destination, method='tesseract', language='eng', encoding='utf-8') return text def output_to_csv(self, *args, **kwargs): '''output_csv exports results to csv''' self.filename = args[0] self.keyword_strike_dict = args[1] self.output_file_path = PdfMiner().output_path + self.filename.strip('.pdf') with open(self.output_file_path + '.csv', 'w+', newline='') as csvfile: row_writer = csv.writer(csvfile, delimiter=',') row_writer.writerow(['keyword', 'keyword_count']) for keyword, keyword_count in self.keyword_strike_dict.items(): print(keyword, keyword_count) row_writer.writerow([keyword, keyword_count]) if __name__ == "__main__": PdfMiner().main() </code></pre>
[]
[ { "body": "<p>I don't see a good reason why this should be a class. You only have two things in your state, <code>self.text</code>, which you could pass as an argument, and <code>self.path, self.output_path</code>, which I would also pass as arguments, maybe with a default value.</p>\n\n<p>Also, you are probably using classes wrong if your class has a <code>main</code> method that needs to instantiate new instances of the class on the fly.</p>\n\n<p>Your algorithm is not very efficient. You need to run over the whole text <em>twice</em> for each keyword. Once to check if it is in there and then again to <code>count</code> it. The former is obviously redundant, since <code>str.count</code> will just return <code>0</code> if the value is not present.</p>\n\n<p>However, what would be a better algorithm is to first extract all the words (for example using a regex filtering only letters) and then count the number of times each word occurs using a <code>collections.Counter</code>, optionally filtering it down to only those words which are keywords. It even has a <code>most_common</code> method, so your file will be ordered by number of occurrences, descending.</p>\n\n<p>Instead of mucking around with <code>os.getcwd()</code> and <code>os.listdir</code>, I would recommend to use the (Python 3) <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path\" rel=\"nofollow noreferrer\"><code>pathlib.Path</code></a> object. It supports globbing (to get all files matching a pattern), chaining them to get a new path and even replacing the extension with a different one.</p>\n\n<p>When reading the keywords, you can use a simple list comprehension. Or, even better, a set comprehension to get <code>in</code> calls for free.</p>\n\n<p><code>line.strip()</code> and <code>line.strip(\"\\n\")</code> are probably doing the same thing, unless you <em>really</em> want to preserve the spaces at the end of words.</p>\n\n<p>At the same time, doing <code>self.filename.strip('.pdf')</code> is a bit dangerous. It removes all characters given, until none of the characters is found anymore. For example, <code>\"some_file_name_fdp.pdf\"</code> will be reduced to <code>\"some_file_name_\"</code>.</p>\n\n<p>The <code>csv.writer</code> has a <a href=\"https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows\" rel=\"nofollow noreferrer\"><code>writerows</code></a> method that takes an iterable of rows. This way you can avoid a <code>for</code> loop.</p>\n\n<p>I would ensure to run only over PDF files, otherwise you will get some errors if a non-PDF file manages to sneak into your folder.</p>\n\n<p>I have done all of this in the following code (not tested, since I don't have <code>textract</code> installed ATM):</p>\n\n<pre><code>from collections import Counter\nimport csv\nfrom pathlib import Path\nimport re\nimport textract\n\ndef extract_text(file_name):\n return textract.process(file_name, method='tesseract', language='eng',\n encoding='utf-8').decode('utf-8')\n\ndef extract_words(text):\n return re.findall(r'([a-zA-Z]+)', text)\n\ndef count_keywords(words, keywords):\n return Counter(word for word in words if word in keywords)\n\ndef read_keywords(file_name):\n with open(file_name) as f:\n return {line.strip() for line in f}\n\ndef save_keywords(file_name, keywords):\n with open(file_name, \"w\", newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n writer.writerow(['keyword', 'keyword_count'])\n writer.writerows(keywords.most_common())\n\ndef main():\n output_folder = Path(\"output_results\")\n keywords = read_keywords('keywords.txt')\n\n for f in Path(\"folderForPdf\").glob(\"*.pdf\"):\n words = extract_words(extract_text(f))\n keyword_counts = count_keywords(words, keywords)\n save_keywords(output_folder / f.with_suffix(\".csv\"), keyword_counts)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:33:06.850", "Id": "426147", "Score": "0", "body": "Wow amazing job thank you very much. I see, most of my code is pointless" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:35:46.827", "Id": "426150", "Score": "2", "body": "@IakovosBelonias Not pointless (it worked before, didn't it?), just a bit too verbose, maybe ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:48:53.497", "Id": "426154", "Score": "0", "body": "Should I use regex considering that I don't care to much about extract the text but mostly to count the number of occurrence?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:52:00.233", "Id": "426155", "Score": "0", "body": "@IakovosBelonias Well, with this approach you *need* to find the words of the text first in order to count them. This is one advantage of your approach, at the cost of performance and false positives in case of partial matches with the keyword." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T11:16:38.317", "Id": "426156", "Score": "0", "body": "I see thank you again" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:30:26.813", "Id": "220555", "ParentId": "220550", "Score": "11" } } ]
{ "AcceptedAnswerId": "220555", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T09:47:00.283", "Id": "220550", "Score": "11", "Tags": [ "python", "python-3.x", "pdf" ], "Title": "Python script to extract text from PDF with images" }
220550
<p>I'm implementing a <strong>Yahtzee</strong> app and i have a class <code>StrategicAdvisor</code> that is responsible for deciding which strategy should be followed. The <code>StrategicAdvisor</code> has some tools: a <code>RollAnalyzer</code> which provides information about the current roll and a <code>BoardAnalyzer</code> which can tell us about the Fields vaccant (or occupied) in the game board (as well as the amount of eyes required for the bonus and other infos about the board). </p> <p>The Strategy just tells the player (either AI player or human) which die should be best kept to maximize on the next roll - or if the result already is optimal to stop rolling and write immediately into the board.</p> <h2>Note:</h2> <p>The <code>StrategicAdvisor</code> just gives Hints on which die should be kept; there is another Advisor, namely the <code>WriteAdvisor</code> who decides which field is optimal at the end of rolling to be written at.</p> <h2>Update / Note 2</h2> <p>the Strategy represents the Strategy for the current Roll - it is not applicatable for the <em>Strategy of the AI-Player</em> for this i had the idea to implement different <em>StrategyAdvisors</em>, e.g. <code>AggressiveStrategicAdvisor</code> or <code>DefensiveStrategicAdvisor</code>... i'm not there yet so the current <code>StrategicAdvisor</code> works a kind of <code>BasicStrategyAdvisor</code> (right now i cannot yet make proper estimates onthe <em>value</em> of a Strategy)</p> <h2>Question here is:</h2> <p><strong>Clean Code:</strong> My <code>StrategicAdvisor</code> has a lot of complexity and i can't find a nice way to reduce complexity here... </p> <pre><code>public class StrategyAdviser { private final YahtzeeGame yahtzeeGame; public StrategyAdviser(YahtzeeGame yahtzeeGame) { this.yahtzeeGame = yahtzeeGame; } public Strategy getAdvise() { Roll roll = yahtzeeGame.getRoll(); Board board = yahtzeeGame.getBoard(); YahtzeePlayer currentPlayer = yahtzeeGame.getCurrentPlayer(); StrategyFactory factory = new StrategyFactory(); if (!roll.hasRoll()) { return factory.createStartRollStrategy(); } if (!yahtzeeGame.canRoll()) { return factory.createWriteToBoardStrategy(); } RollAnalyze rollAnalyze = new RollAnalyze(roll); BoardAnalyze boardAnalyze = new BoardAnalyze(board, currentPlayer); int amountOfIdenticals = rollAnalyze.getAmountOfIdenticals(); int highestEyeOfIdenticals = rollAnalyze.getHighestEyeOfIdenticals(); boolean has6 = rollAnalyze.hasSix(); boolean has5 = rollAnalyze.hasFive(); boolean is6Empty = boardAnalyze.isTopRowEmpty(6); boolean is5Empty = boardAnalyze.isTopRowEmpty(5); boolean has3InRow = rollAnalyze.hasThreeInRow(); boolean has4InRow = rollAnalyze.hasFourInRow(); boolean hasBottomVariables = boardAnalyze.hasBottomRowsWithVariableCounter(); if (amountOfIdenticals == 5) { return factory.createWriteToBoardStrategy(); } if ((amountOfIdenticals &gt;= 3 &amp;&amp; boardAnalyze.isTopRowEmpty(highestEyeOfIdenticals))) { return factory.createStrategyRollForThreeOrMoreIdentical(highestEyeOfIdenticals, rollAnalyze); } if (amountOfIdenticals &gt;= 2 &amp;&amp; highestEyeOfIdenticals &gt;= 4) { return factory.createStrategyRollForThreeOrMoreIdentical(highestEyeOfIdenticals, rollAnalyze); } if (has4InRow) { return factory.createStrategyRollForMajorStreet(); } if (has6 &amp;&amp; is6Empty) { return factory.createStrategyRollForSix(rollAnalyze); } if (((!has6) &amp;&amp; (has5 &amp;&amp; is5Empty))) { return factory.createStrategyRollForSix(rollAnalyze); } if (hasBottomVariables) { if (has6) { return factory.createStrategyRollForSix(rollAnalyze); } if (has5) { return factory.createStrategyRollForFive(rollAnalyze); } } if (has3InRow) { if (has5) { return factory.createStrategyRollForMinorStreet(3, 4, 5); } else { return factory.createStrategyRollForMinorStreet(2, 3, 4); } } return factory.createStrategyReRollAll(); } </code></pre> <p>I could write some Methods to simplify the statements but i think that would only slighlty decrease complexity... (e.g. instead of <code>amountOfIdenticals == 5</code> write a method <code>boolean hasFiveIdenticals(rollAnalyze ra);</code></p> <h2>Update</h2> <p>here is the intercace <code>Strategy</code>: There are two abstract implementations in the <code>StrategyFactory</code> for easier creation of <code>Strategy</code>s.</p> <pre><code>public interface Strategy { boolean adviseToContinueRolling(); void apply(YahtzeeGame game); } </code></pre> <p>and <code>StrategyFactory</code>:</p> <pre><code>public class StrategyFactory { private static final Logger LOGGER = LoggerFactory.getLogger(Strategy.class); public Strategy createStrategyRollForThreeOrMoreIdentical(int highestEyeOfIdenticals, RollAnalyze rollAnalyze) { return new ContinueStrategy() { @Override public void apply(YahtzeeGame game) { LOGGER.debug("apply strategy: roll, try to get as much identicals of {} as possible", +rollAnalyze.getHighestEyeOfIdenticals()); LOGGER.debug("based on roll: {}", rollAnalyze.getRoll()); roll(game, rollAnalyze.getKeepingFor(highestEyeOfIdenticals)); } @Override public String toString() { return "roll for identicals of " + highestEyeOfIdenticals; } }; } public Strategy createStartRollStrategy() { return new ContinueStrategy() { @Override public void apply(YahtzeeGame game) { LOGGER.debug("apply strategy: roll for the first time..."); roll(game); } @Override public String toString() { return "roll for the first time..."; } }; } public Strategy createWriteToBoardStrategy() { return new StopStrategy() { @Override public void apply(YahtzeeGame game) { LOGGER.debug("apply strategy: write to board... do NOT roll anymore"); } @Override public String toString() { return "do not roll - write it into the board!"; } }; } public Strategy createStrategyRollForMajorStreet() { return new ContinueStrategy() { @Override public void apply(YahtzeeGame game) { LOGGER.debug("apply strategy: roll, try to get as much different since we have alreadey minor straight"); roll(game, new Keeping(new HashSet&lt;&gt;(Arrays.asList(2, 3, 4, 5)))); } @Override public String toString() { return "roll for a major street"; } }; } public Strategy createStrategyRollForSix(RollAnalyze rollAnalyze) { return createStartRollForEye(6, rollAnalyze); } public Strategy createStrategyRollForFive(RollAnalyze rollAnalyze) { return createStartRollForEye(5, rollAnalyze); } private Strategy createStartRollForEye(int eye, RollAnalyze rollAnalyze) { return new ContinueStrategy() { @Override public void apply(YahtzeeGame game) { Keeping keeping = rollAnalyze.getKeepingFor(eye); LOGGER.debug("apply strategy: roll, try to get as much identicals of {} as possible", +eye); LOGGER.debug("based on roll: {}", keeping); roll(game, keeping); } @Override public String toString() { return "roll one certain eye: " + eye; } }; } public Strategy createStrategyRollForMinorStreet(Integer... eyes) { return new ContinueStrategy() { @Override public void apply(YahtzeeGame game) { LOGGER.debug("apply strategy: roll, try to get as much different since we have alreadey 3/4 of minor straight"); roll(game, new Keeping(new HashSet&lt;&gt;(Arrays.asList(eyes)))); } @Override public String toString() { return "roll for a minor street"; } }; } public Strategy createStrategyReRollAll() { return new ContinueStrategy() { @Override public void apply(YahtzeeGame game) { LOGGER.debug("apply strategy: reRoll all..."); roll(game); } @Override public String toString() { return "reRoll all... "; } }; } private abstract class TemplateStrategy implements Strategy { private final boolean adviseToContinue; private TemplateStrategy(final boolean adviseToContinue) { this.adviseToContinue = adviseToContinue; } @Override public boolean adviseToContinueRolling() { return adviseToContinue; } void roll(YahtzeeGame yahtzeeGame, Keeping keeping) { LOGGER.debug("set keeping: {}", keeping); yahtzeeGame.setKeepings(keeping); yahtzeeGame.roll(); LOGGER.debug("...done with set Keeping and rolling..."); } void roll(YahtzeeGame yahtzeeGame) { yahtzeeGame.roll(); LOGGER.debug("...done, rolling..."); } } private abstract class StopStrategy extends TemplateStrategy { private StopStrategy() { super(false); } } private abstract class ContinueStrategy extends TemplateStrategy { private ContinueStrategy() { super(true); } } } </code></pre> <h2>further note:</h2> <p>a <code>Keeping</code> is a set of Numbers, which tells the <code>YahtzeeGame</code> which die should be kept (so it's a <code>Keeping</code>) and wich shall be re-rolled</p> <p>if you want to dig deeper into the code, it can be found under <a href="https://github.com/martinFrank/yatzee" rel="nofollow noreferrer">https://github.com/martinFrank/yatzee</a> but please don't look too close - i fear i might get kicked out of this board, hahaha =)</p> <h2>Update</h2> <p>in hindsight of the progress of the question i think i should as well add the AiPlayer's turn</p> <pre><code>public class YahtzeePlayer extends BasePlayer&lt;YahtzeeGame&gt; { private static final Logger LOGGER = LoggerFactory.getLogger(YahtzeePlayer.class); YahtzeePlayer(String name, int color, boolean isHuman) { super(name, color, isHuman); } @Override public void performAiTurn() { YahtzeeGame yahtzeeGame = getBoardGame();//weg damit StrategyAdviser strategyAdviser = new StrategyAdviser(yahtzeeGame); Strategy currentStrategy = strategyAdviser.getAdvise(); while (currentStrategy.adviseToContinueRolling()) { currentStrategy.apply(yahtzeeGame); currentStrategy = strategyAdviser.getAdvise(); } WriteAdviser writeAdviser = new WriteAdviser( yahtzeeGame.getRoll(), yahtzeeGame.getBoard(), this, new RollAnalyze(yahtzeeGame.getRoll())); RowType rowType = writeAdviser.getOptimalRow(); if (!yahtzeeGame.getBoard().getRow(rowType, this).isEmpty()) { throw new IllegalStateException("error - writing into an already filled row"); } LOGGER.debug("write roll {} into rowType {}", yahtzeeGame.getRoll(), rowType); yahtzeeGame.write(rowType); LOGGER.debug("done Ai turn"); yahtzeeGame.endPlayersTurn(); yahtzeeGame.startPlayersTurn(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:30:37.393", "Id": "426146", "Score": "0", "body": "maybe i'm not 100% accurate with the official Rules but i don't think that really matters here...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T15:48:01.397", "Id": "426199", "Score": "2", "body": "This is probably just a language barrier issue, but I've heard native speakers do it also, so: one die, multiple dice. There's no such thing as \"dices\". :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T17:01:49.557", "Id": "426206", "Score": "0", "body": "oh my - yes, one dice, two die! thank you very much.... i'm definitly no native english speaker =).... i'll adjust my code! to keep consitency i will not alter my question here..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T17:03:12.350", "Id": "426207", "Score": "1", "body": "As far as your actual problem goes, have you considered using a [chain of responsibility](https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern)? I think it might require some rework of your current design outside of the StrategyAdvisor class, but it's something to consider." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T17:27:10.127", "Id": "426213", "Score": "0", "body": "thank you very much - i know some more design patterns but there are always some unknown one - i think this will guide me into the right direction! It's no problem to do a major refactoring if it increases the readability and maintainability. In my first approach i was not even able to use the strategy-pattern... it was some work but it is much better now!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T19:12:40.980", "Id": "426224", "Score": "2", "body": "I suggest that you include the `Strategy` and `StrategyFactory` classes as well, as they are likely part of the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T05:26:32.357", "Id": "426237", "Score": "0", "body": "I will add them, I can not reach my source code right now but I will provide them as soon as possible!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:40:42.170", "Id": "426362", "Score": "0", "body": "ok, code is updated...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T19:38:26.853", "Id": "426371", "Score": "0", "body": "i think the question title is misleading - i will rename it from *Strategy advisor for a Yahtzee game* into *Strategy advisor for a Yahtzee Roll*" } ]
[ { "body": "<p>There are <a href=\"http://www.yahtzee.org.uk/strategy.html\" rel=\"nofollow noreferrer\">more than one way</a> to play Yahtzee, so you need several strategies. Thus the <code>StrategyFactory</code> can not be instatiated in the <code>StrategyAdviser</code>, it has to be <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">injected as a dependency</a>.</p>\n\n<p>The name suggests that <code>StrategyAdviser</code> would just be a proxy between the chosen <code>Strategy</code> and the ongoing game. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">division of responsibilities</a> should be clear and well documented.</p>\n\n<p>At every state of the game, there are a known set of actions the player can take (mainly, 32 different combinations of roll/hold a dice in the hand). These actions should be enumerated by a component that is responsible for maintaining the rules of the game. The strategy should be provided with these actions as input and calculate the risk and reward for each one (related to the strategy type) as output. The role of the advisor would then be to implement riskiness (e.g. a risk averse or reckless advisor or maybe an advisor that just gives bad advise) and select one of the choices.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T16:53:28.317", "Id": "426332", "Score": "0", "body": "Thanks Torben - my idea was to make the strategic advisor decide if it's a 'risk-ful' advisor or if it is a 'defensive' advisor - right now i am not there, so there is just one strategic advisor who has just this (see above) algorithm... The Strategy is used on the current roll - not on the whole game at all... i am still only online via mobile and can't yet provide more code - but i'll stick wiht it!! (+1)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:40:45.380", "Id": "426363", "Score": "0", "body": "ok, code is updated...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T19:00:57.727", "Id": "426364", "Score": "0", "body": "uh - about my comment above - i hope that my updated question makes it more clear: the strategy appiels to the current Roll! (ok, i might rename it into `RollingStrategy` to prevent any further questions) it should just tell the AiPlayer what would be a good idea to do with the current roll." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T06:40:39.350", "Id": "220609", "ParentId": "220554", "Score": "2" } }, { "body": "<p>First of all - I do not know the game and just want to point out some code related things. Thanks :)</p>\n\n<hr>\n\n<h1>Not a Getter</h1>\n\n<p>From the <a href=\"https://web.archive.org/web/20100226131716/http://java.sun.com/developer/onlineTraining/Beans/JBeansAPI/shortcourse.html#SimpleProperties\" rel=\"nofollow noreferrer\">JavaBeans naming conventions</a>:</p>\n\n<blockquote>\n <p>By default, <strong>properties</strong> are determined from get/set access method combinations that follow a prescribed naming convention.<br>\n [...]</p>\n\n<pre><code>public int getMood() {\n return mood;\n}\n</code></pre>\n</blockquote>\n\n<p>The name of the method <code>getAdvise</code> supposes that this will return a \n<strong>property</strong> but it calculates the <code>Strategy</code> - I would rename the method to <code>predict</code>. So the API could look like:</p>\n\n<pre><code>StrategyAdviser strategyAdviser = new StrategyAdviser(game);\nStrategy strategy = strategyAdvise.predict();\n</code></pre>\n\n<hr>\n\n<h1><code>RollAnalyze</code> and <code>BoardAnalyze</code></h1>\n\n<p>I can't justify following with resources and maybe it is just my personal experience: </p>\n\n<blockquote>\n<pre><code>RollAnalyze rollAnalyze = new RollAnalyze(roll);\nBoardAnalyze boardAnalyze = new BoardAnalyze(board, currentPlayer);\n</code></pre>\n</blockquote>\n\n<p>The <code>rollAnalyze</code> and <code>boardAnalyze</code> can't be reused because they only work for <code>roll</code>, <code>board</code> and <code>currentPlayer</code>. So we need to instantiate on each call on <code>getAdvise</code> new objects of them.</p>\n\n<p>It could be bette, if we can create instance variables of them and call the methods on them with passing in the arguments they need:</p>\n\n<pre><code>RollAnalyze rollAnalyze;\nBoardAnalyze boardAnalyze;\n\n// constuctor\n\npublic Strategy getAdvise() {\n// ...\n\n boolean has6 = rollAnalyze.hasSix(roll);\n boolean has5 = rollAnalyze.hasFive(roll);\n}\n</code></pre>\n\n<hr>\n\n<h1>Instance Variable</h1>\n\n<p>The <code>StrategyFactory</code> should be a instance variable of <code>StrategyAdviser</code> that gets injected in by the constructor. </p>\n\n<p>One benefit of a Factory is the possibility to change it dynamically. Currently it is <em>hard coded</em> in side your logic without the possibility to change the behavior dynamically on runtime. </p>\n\n<hr>\n\n<h1>Factory Pattern</h1>\n\n<p>From <a href=\"https://en.wikipedia.org/wiki/Factory_method_pattern#Structure\" rel=\"nofollow noreferrer\">Wikipedia</a>: </p>\n\n<blockquote>\n <p>The Factory Method design pattern describes how to solve such problems:</p>\n \n <ul>\n <li>Define a separate operation <strong>(factory method)</strong> for creating an object.</li>\n <li>Create an object by calling a factory method</li>\n </ul>\n \n <p><a href=\"https://i.stack.imgur.com/rzFlI.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rzFlI.jpg\" alt=\"enter image description here\"></a></p>\n</blockquote>\n\n<p>In the UML-Diagram you can see that there exists in the <code>Creator1</code> only one method \n - the <strong>factory method</strong>. </p>\n\n<p>Currently the <code>StrategyFactory</code> provides for each possible Strategy a method. Instead it should have only one method and it decides witch object will be returned.</p>\n\n<p>There for we need to paste the <code>if-branches</code> from <code>getAdvise</code> into <code>StrategyFactory</code>:</p>\n\n<pre><code>public class StrategyFactory {\n\n RollAnalyze rollAnalyze;\n BoardAnalyze boardAnalyze;\n\n // constructor\n\n public Strategy build(YahtzeeGame yahtzeeGame) {\n Roll roll = yahtzeeGame.getRoll();\n Board board = yahtzeeGame.getBoard();\n YahtzeePlayer currentPlayer = yahtzeeGame.getCurrentPlayer();\n\n if (!roll.hasRoll()) {\n return createStartRollStrategy();\n }\n\n if (!yahtzeeGame.canRoll()) {\n return createWriteToBoardStrategy();\n }\n\n if (rollAnalyze.getAmountOfIdenticals(roll) == 5) {\n return createWriteToBoardStrategy();\n }\n\n // ...\n }\n\n private Strategy createStartRollStrategy() {}\n private Strategy createWriteToBoardStrategy() {}\n}\n</code></pre>\n\n<p>and the <code>getAdvise</code> will look like:</p>\n\n<pre><code>public class StrategyAdviser {\n\n private final YahtzeeGame yahtzeeGame;\n private final StrategyFactory strategyFactory;\n\n // constructor\n\n public Strategy predict() {\n return strategyFactory.build(yahtzeeGame);\n }\n}\n</code></pre>\n\n<p>The benefit we now have is, that if you want to create different game rules, you can switch the strategyFactory. </p>\n\n<p>For example: Currently a AmountOfIdenticals needs to be 5 for a special action. You could now create a custom StrategyFactory where the Amount needs to be 100 and if the rule is boring you can switch it back to the old strategyFactory without to touch the logic.</p>\n\n<hr>\n\n<h1><a href=\"https://www.martinfowler.com/bliki/FlagArgument.html\" rel=\"nofollow noreferrer\">Flag Argument</a></h1>\n\n<blockquote>\n <p>A flag argument is a kind of function argument that tells the function to carry out a different operation depending on its value</p>\n\n<pre><code>YahtzeePlayer(String name, int color, boolean isHuman) {\n super(name, color, isHuman);\n}\n</code></pre>\n</blockquote>\n\n<p>We do not need the flag.. We could just build two classes <code>NonHumanPlayer</code> and <code>HumanPlayer</code> and we can avoid the flag, which will build many branches in the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T08:24:40.297", "Id": "429667", "Score": "0", "body": "Hello Roman, glad Rio see you back again. Again you pointed out much of basic mistakes which should be removed first. Actually I'm on holidays and can't respond quickly nor with a real device (currently I'm on the Mobil phone). Your review was very helpful so far." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T08:13:49.197", "Id": "222064", "ParentId": "220554", "Score": "1" } } ]
{ "AcceptedAnswerId": "222064", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T10:29:48.587", "Id": "220554", "Score": "3", "Tags": [ "java", "object-oriented", "design-patterns", "dice" ], "Title": "Strategy advisor for a Yahtzee Roll" }
220554
<p>I created it to map buffers returned by ODBC driver to my objects directly without creating DataSet like storage. It works quite nice, but I have some questions. <em>UPD: I resoled those questions, just sharing code.</em></p> <p>For those who unfamiliar with ODBC: after calling to <code>SQLFetch</code> driver fills buffers specified by <code>SQLBindCol</code> and NULL indicator in <code>*Length</code> field <a href="https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/row-wise-binding?view=sql-server-ver15" rel="nofollow noreferrer">in batch of <code>ROW_ARRAY_SIZE</code></a>. You can ignore parts related to ODBC.</p> <p>The main idea behind this code is to minimize number of API calls, because profiler shows significant amount of time is spent in intermediate layers (not waiting for IO). Сurrent code is an order of magnitude faster than rebinding (each row) directly to std::string buffer, and around twice as fast than <code>SQLGetData</code> approach.</p> <pre class="lang-cpp prettyprint-override"><code>//----- template&lt;class... Ts&gt; struct Visitor: Ts... { using Ts::operator()...; }; // for std::visit template&lt;class... Ts&gt; Visitor(Ts...)-&gt;Visitor&lt;Ts...&gt;; // deduction guide for Visitor //----- template &lt;typename T, typename V, SQLULEN ROW_ARRAY_SIZE = 100&gt; class OdbcBinder final { private: using pll = std::tuple&lt;long T::*, SQLLEN T::*, long V::*&gt;; using pcs = std::tuple&lt;char(T::*)[], SQLLEN T::*, std::string V::*, size_t&gt;; using pts = std::tuple&lt;SQL_TIMESTAMP_STRUCT T::*, SQLLEN T::*, std::string V::*&gt;; using mapvar = std::variant&lt;pll, pcs, pts&gt;; SQLUSMALLINT N = 0; Odbc&amp; m_odbc; const autoHSTMT stmt; // TODO: use std::span, remove ROW_ARRAY_SIZE const std::unique_ptr&lt;std::array&lt;T, ROW_ARRAY_SIZE&gt;&gt; in; std::vector&lt;mapvar&gt; mappings; public: explicit OdbcBinder(Odbc&amp; odbc): m_odbc(odbc), stmt(odbc.GetHstmt()), in(std::make_unique&lt;std::array&lt;T, ROW_ARRAY_SIZE&gt;&gt;()) {} template &lt;std::size_t ArrSize&gt; void BindCol(char(T::* ptrin)[ArrSize], SQLLEN T::* ptrinLen, std::string V::* ptrout) { static_assert(sizeof(ptrin) == sizeof(char(T::*)[100]) &amp;&amp; alignof (decltype(ptrin)) == alignof(char(T::*)[100])); // no decay to unbound member array. TODO: Resolved in C++ 20 BindCol(reinterpret_cast&lt;char (T::*)[]&gt;(ptrin), ArrSize, ptrinLen, ptrout); } // non template version (to reduce code size) void BindCol(char (T::* ptrin)[], size_t ArrSize, SQLLEN T::* ptrinLen, std::string V::* ptrout) { mappings.emplace_back(std::make_tuple(ptrin, ptrinLen, ptrout, ArrSize)); SQLRETURN rc = SQLBindCol(stmt, ++N, SQL_C_CHAR, &amp;((*in)[0].*ptrin), ArrSize, &amp;((*in)[0].*ptrinLen)); if (rc != SQL_SUCCESS) m_odbc.LogLastError(stmt); } void BindCol(SQL_TIMESTAMP_STRUCT T::* ptrin, SQLLEN T::* ptrinLen, std::string V::* ptrout) { mappings.emplace_back(std::make_tuple(ptrin, ptrinLen, ptrout)); SQLRETURN rc = SQLBindCol(stmt, ++N, SQL_C_TIMESTAMP, &amp;((*in)[0].*ptrin), sizeof((*in)[0].*ptrin), &amp;((*in)[0].*ptrinLen)); if (rc != SQL_SUCCESS) m_odbc.LogLastError(stmt); } void BindCol(long T::* ptrin, SQLLEN T::* ptrinLen, long V::* ptrout) { mappings.emplace_back(std::make_tuple(ptrin, ptrinLen, ptrout)); SQLRETURN rc = SQLBindCol(stmt, ++N, SQL_C_LONG, &amp;((*in)[0].*ptrin), sizeof((*in)[0].*ptrin), &amp;((*in)[0].*ptrinLen)); if (rc != SQL_SUCCESS) m_odbc.LogLastError(stmt); } [[nodiscard]] std::vector&lt;V&gt; GetResult(std::string_view sql, SQLULEN limit = 0) { return useOracleWorkaround() ? GetResult&lt;SQLLEN&gt;(sql, limit) : GetResult&lt;SQLUSMALLINT&gt;(sql, limit); } private: bool useOracleWorkaround() const { if (m_odbc.Lang() == Odbc::DbType::Oracle) { #ifdef _WIN64 return true; #else if (m_odbc.driverVersion &lt; 12) return true; #endif // _WIN64 } return false; } // @param limit fetch only N rows, 0 - disable template&lt;typename OracleWorkaroundType&gt; [[nodiscard]] std::vector&lt;V&gt; GetResult(std::string_view sql, SQLULEN limit = 0) const { SQLULEN numRowsFetched = 0; // MSSQL conforms to standard and use SQLUSMALLINT (2 byte) // Oracle 11 x32 driver writes 4 byte array // Oracle 12+ x32 are conforming // Oracle x64 drivers writes 8 byte //SQLUSMALLINT rowStatusArray[ROW_ARRAY_SIZE]; OracleWorkaroundType rowStatusArray[ROW_ARRAY_SIZE]{}; SQLRETURN rc = SQL_ERROR; rc = SQLSetStmtAttr(stmt, SQL_ATTR_ROW_ARRAY_SIZE, (SQLPOINTER)ROW_ARRAY_SIZE, SQL_IS_UINTEGER); _ASSERT(rc == 0); rc = SQLSetStmtAttr(stmt, SQL_ATTR_ROW_BIND_TYPE, (SQLPOINTER)sizeof(T), SQL_IS_UINTEGER); _ASSERT(rc == 0); rc = SQLSetStmtAttr(stmt, SQL_ATTR_ROW_STATUS_PTR, rowStatusArray, SQL_IS_POINTER); _ASSERT(rc == 0); rc = SQLSetStmtAttr(stmt, SQL_ATTR_ROWS_FETCHED_PTR, &amp;numRowsFetched, SQL_IS_POINTER); _ASSERT(rc == 0); if (limit != 0) { rc = SQLSetStmtAttr(stmt, SQL_ATTR_MAX_ROWS, (SQLPOINTER)limit, SQL_IS_UINTEGER); _ASSERT(rc == 0); if (rc != SQL_SUCCESS) m_odbc.LogLastError(stmt); } std::vector&lt;V&gt; results; rc = SQLExecDirect(stmt, (SQLCHAR*)sql.data(), static_cast&lt;SQLINTEGER&gt;(sql.size())); if (!SQL_SUCCEEDED(rc) &amp;&amp; rc != SQL_NO_DATA) { m_odbc.LogLastError(stmt); return results; } results.reserve(limit != 0 ? limit : ROW_ARRAY_SIZE / 4); do { while (SQL_SUCCEEDED(rc = SQLFetch(stmt))) { if (rc == SQL_SUCCESS_WITH_INFO) m_odbc.LogLastError(stmt); for (SQLUINTEGER i = 0; i &lt; numRowsFetched; ++i) { if (rowStatusArray[i] != SQL_ROW_SUCCESS &amp;&amp; rowStatusArray[i] != SQL_ROW_SUCCESS_WITH_INFO) continue; V value; const T&amp; info = (*in)[i]; const auto visitor = Visitor{ [&amp;](const pll&amp; tup) { const auto&amp; [ptrin, ptrinLen, ptrout] = tup; if (info.*ptrinLen != SQL_NULL_DATA) value.*ptrout = info.*ptrin; else value.*ptrout = 0; }, [&amp;](const pcs&amp; tup) { const auto&amp; [ptrin, ptrinLen, ptrout, size] = tup; _ASSERTE(/*bufferLength*/size - 1 &gt;= /*gotlength*/size_t(info.*ptrinLen) || /*is null*/info.*ptrinLen == SQL_NULL_DATA); switch (info.*ptrinLen) { case SQL_NULL_DATA: (value.*ptrout).clear(); break; case SQL_NO_TOTAL: // should not happen _ASSERTE(SQL_NO_TOTAL, false); (value.*ptrout).assign(info.*ptrin, size - 1); break; default: // info.*ptrinLen the length of the data before truncation because of the data buffer being too small (value.*ptrout).assign(info.*ptrin, std::clamp&lt;SQLLEN&gt;(info.*ptrinLen, 0, size - 1)); break; } }, [&amp;](const pts&amp; tup) { const auto&amp; [ptrin, ptrinLen, ptrout] = tup; if (info.*ptrinLen != SQL_NULL_DATA) value.*ptrout = TimestampToString(info.*ptrin); else (value.*ptrout).clear(); } }; for (auto&amp;&amp; v : mappings) std::visit(visitor, v); results.push_back(std::move(value)); } } if (rc != SQL_NO_DATA) { m_odbc.LogLastError(stmt); // no partial results results.clear(); return results; } } while (SQL_SUCCEEDED(rc = SQLMoreResults(stmt))); if (rc != SQL_NO_DATA) { m_odbc.LogLastError(stmt); // no partial results results.clear(); } return results; } public: OdbcBinder(const OdbcBinder&amp;) = delete; // copy ctr OdbcBinder(OdbcBinder&amp;&amp;) noexcept = delete; // move ctr OdbcBinder&amp; operator=(const OdbcBinder&amp;) = delete; // copy asign OdbcBinder&amp; operator=(OdbcBinder&amp;&amp;) noexcept = delete; // move asign }; </code></pre> <p>Usage:</p> <pre class="lang-cpp prettyprint-override"><code>struct INCIDENT_INFO { long id; long idLength; char comments[1024]; long commentsLength; /* ... */ SQL_TIMESTAMP_STRUCT timeSend; long timeSendLength; }; class Incident { long id; std::string comments; /* ... */ std::string timeSend; }; int main() { // initialize connection auto odbc = &lt;...&gt;; OdbcBinder&lt;INCIDENT_INFO, Incident&gt; binder(odbc); // map by convention //#define BINDER_MAP(field_name, entity_class, buffer_class) &amp; buffer_class :: field_name, &amp; buffer_class :: field_name ## Length, &amp; entity_class :: field_name //binder.BindCol(BINDER_MAP(id, Incident, INCIDENT_INFO)); // ID - 0 binder.BindCol(&amp;INCIDENT_INFO::id, &amp;INCIDENT_INFO::idLength, &amp;Incident::id); // ID - 0 binder.BindCol(&amp;INCIDENT_INFO::comments, &amp;INCIDENT_INFO::commentsLength, &amp;Incident::comments); // COMMENTS - 1 /* .... */ binder.BindCol(&amp;INCIDENT_INFO::timeSend, &amp;INCIDENT_INFO::timeSendLength, &amp;Incident::timeSend); // TIME_SEND - 31 std::vector&lt;Incident&gt; v = binder.GetResult(&quot;select ID, COMMENTS, &quot; /* .... */ &quot;TIME_SEND from INCIDENTS&quot;); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T18:16:01.807", "Id": "533284", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T18:55:34.390", "Id": "533286", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ sorry, I wanted to delete only the second block of code" } ]
[ { "body": "<h1>Keep it simple</h1>\n<p>There is a lot going on in your code, making heavy use of templates, variant types and pointers-to-members.\nThis is hard to read and understand, and while you might have everything fresh in memory now, if you have to come back to this code after half a year you will probably have a hard time yourself trying to figure out how it works again.\nSo while the thing you have implemented is clearly possible, it might be worthwhile to explore if there are simpler approaches to this problem.</p>\n<p>As you mentioned:</p>\n<blockquote>\n<p>I need to map between 3 buffers {ODBC internal buffer}-&gt;{DTO with in place buffer}-&gt;{Entity}</p>\n</blockquote>\n<p>The idea behind <code>SQLBindCol()</code> is that it automates going from the ODBC internal buffer to the Data Transfer Object (DTO) format. However, the DTO supported is just a plain old C struct, and you want to have the results in a C++ class with <code>std::string</code>s and perhaps even other non-C types. The drawback of <code>SQLBindCol()</code> is that you have to call it before calling <code>SQLFetch()</code>, and then you have to convert from the DTO to your C++ objects. It would help if we could skip the intermediate DTO step, but unfortunately that is not possible.</p>\n<p>Alternatively, if there is some way to do all the conversion after fetching, we can do the conversions all in one place. That is in fact possible by using <code>SQLGetData()</code>. Your code wouldn't be calling <code>SQLBindCol()</code> at all, and <code>GetResult()</code> would be changed to look like this:</p>\n<pre><code>rc = SQLExecDirect(hstmt, (SQLCHAR*)sql.data(), static_cast&lt;SQLINTEGER&gt;(sql.size()));\n...\nstd::vector&lt;V&gt; results;\n\nwhile (SQL_SUCCEEDED(rc = SQLFetch(stmt)) {\n ...\n results.push_back(mapper(stmt));\n}\n</code></pre>\n<p>Where the function <code>mapper()</code> could look like this:</p>\n<pre><code>Incident mapper(const autoHSTMT &amp;stmt) {\n Incident value;\n value.id = GetLong(stmt, 1);\n value.comments = GetString(stmt, 2);\n ...\n value.timeSend = GetTimestamp(stmt, 3);\n return value;\n}\n</code></pre>\n<p>And this in turn uses helper functions to convert a single value. For example, to convert a timestamp:</p>\n<pre><code>std::string GetTimestamp(const autoHSTMT &amp;stmt, SQLUSMALLINT column) {\n SQL_TIMESTAMP_STRUCT timestamp;\n SQLLEN length;\n SQLRETURN rc = SQLGetData(stmt, column, SQL_C_TIMESTAMP, (SQLPOINTER)&amp;timestamp, 0, &amp;length);\n\n if (!SQL_SUCCEEDED(rc))\n throw std::runtime_error(&quot;Could not get column data&quot;);\n\n if (length != SQL_NULL_DATA)\n return TimestampToString(timestamp);\n else\n return {};\n}\n</code></pre>\n<p>Most of the members of <code>class OdbcBinder</code> are just there to support <code>GetResult()</code>. Without the need for binding, you could write a free function that does what you want:</p>\n<pre><code>template&lt;typename Mapper&gt;\nauto GetQueryResult(Odbc&amp; odbc, const std::string &amp;query,\n Mapper&amp;&amp; mapper, SQLULEN limit = 0)\n{\n ...\n // Deduce the value type from the return type of mapper()\n using V = decltype(mapper(stmt));\n std::vector&lt;V&gt; results;\n ...\n while (SQL_SUCCEEDED(rc = SQLFetch(stmt)) {\n ...\n results.push_back(mapper(stmt));\n }\n ...\n return results;\n}\n</code></pre>\n<p>With this in place, writing a mapper function should just be a few lines more than all the <code>binder.BindCol()</code> statements you had to write, and it is much more flexible.</p>\n<p>It is possible to make it even nicer to write mapper functions; for example one could consider creating a wrapper class that represents a row and that has <code>operator&gt;&gt;()</code> overloads that would allow you to write code like:</p>\n<pre><code>Incident mapper(const Row &amp;row) {\n Incident value;\n row &gt;&gt; value.id &gt;&gt; value.comments &gt;&gt; ... &gt;&gt; value.timeSend;\n return value;\n}\n</code></pre>\n<p>Such a wrapper could look like:</p>\n<pre><code>class Row {\n const autoHSTMT &amp;stmt;\n SQLUSMALLINT column{};\npublic:\n Row(const autoHSTMT &amp;stmt): stmt(stmt) {}\n\n Row &amp;operator&gt;&gt;(long &amp;value) {\n SQLLEN length;\n SQLRETURN rc = SQLGetData(stmt, ++column, SQL_C_LONG, (SQLPOINTER)&amp;value, 0, &amp;length);\n ...\n }\n ...\n};\n</code></pre>\n<h1>Use <code>struct</code> instead of <code>std::tuple</code> where possible</h1>\n<p>A <code>std::tuple</code> is an easy way to group several values together in a quick way, but the drawback is that the members of a tuple don't have names. If you can use a <code>struct</code> instead, prefer that. So instead of:</p>\n<pre><code>using pll = std::tuple&lt;long T::*, SQLLEN T::*, long V::*&gt;;\n</code></pre>\n<p>Write:</p>\n<pre><code>struct pll {\n long T::* ptrin;\n SQLLEN T::* ptrinLen;\n long V::* ptrout;\n};\n</code></pre>\n<p>Then inside <code>BindCol()</code> you can just write:</p>\n<pre><code>mappings.emplace_back(ptrin, ptrinLen, ptrout);\n</code></pre>\n<p>In fact, the above line will work with the <code>std::tuple</code> type as well.\nMore importantly, you don't have to unpack the tuples in the visitors anymore, and this removes possible mistakes: for example, it's easy to get the order of the variables wrong in a structured binding without the compiler complaining.</p>\n<h1>Be careful managing state</h1>\n<p>There is a potential problem in your code, because there is state associated with <code>stmt</code>, and conditionally changing that state might result in problems. Take for example <code>SQL_ATTR_MAX_ROWS</code>. You only change this attribute if you pass a non-zero value for <code>limit</code> to <code>GetResult()</code>. But consider what happens if one calls <code>GetResult()</code> twice, once with a non-zero value for <code>limit</code>, and a second time with zero for <code>limit</code>. The second time the attribute is still left at the non-zero value.</p>\n<h1>Error handling</h1>\n<p>The function <code>GetResult()</code> always returns a result, even if the query could not be executed, or if there was a problem fetching some of the rows. It is hard for the caller to distinguish between a perfectly fine query that results in zero rows, versus a query that should have returned rows but failed.</p>\n<p>Consider throwing <a href=\"https://en.cppreference.com/w/cpp/error/exception\" rel=\"nofollow noreferrer\">exceptions</a> or returning a <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional</code></a> so the caller can distinguish between success and failure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:30:17.513", "Id": "532139", "Score": "1", "body": "I need to map between 3 buffers `{ODBC internal buffer}->{DTO with in place buffer}->{Entity}`. Those `std::variant`'s were holding that transforamtion. You suggest to decouple it, but now I need specify both `{ODBC internal buffer}->{DTO with in place buffer}` and `{DTO with in place buffer}->{Entity}` in different places." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:58:48.377", "Id": "532144", "Score": "0", "body": "I updated question with refactored code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T20:28:30.137", "Id": "532205", "Score": "0", "body": "I missed that you had to convert twice. I've updated my answer with a possible solution for this, I hope it is helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T01:05:39.560", "Id": "532222", "Score": "1", "body": "At first, thanks for ideas (use conversion constructor for conversion, row binding DSL, max_rows state).\nAt second, the main idea behind this code was to minimize number of API calls, cause profiler shows significant amount is spent in intermediate layers (not waiting for IO). Сurrent code is an order of magnitude faster than rebinding (each row) directly to `std::string` buffer, and around twice as fast than `SQLGetData` approach in spite of this excessive `memmov`ing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T01:46:30.767", "Id": "532223", "Score": "0", "body": "In my case typical result set is around 20 columns and 200-300k rows. So it would be 20*200'000+200(SetPos) api calls vs 20 (beside SQLFetch)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T19:23:17.193", "Id": "532303", "Score": "0", "body": "Hm, that is unfortunate. The double conversion is also unfortunate, but I guess there is no way around it that is as performant. But perhaps the interface of `OdbcBinder` can be improved so the caller doesn't have to specify the intermediate `INCIDENT_INFO` struct. I might add that as a separate answer." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T21:15:45.900", "Id": "269664", "ParentId": "220557", "Score": "2" } }, { "body": "<p>This is a separate answer. In the first one, I focused on simplifying the API, but as was pointed out, calling <code>SQLGetData()</code> for all the columns in all the rows is slowing things down. In this answer I also want to show a way to simplify things, but this time it's just making things easier for the user of your code.</p>\n<h1>Hide the DTO from the user of your class</h1>\n<p>In your code, the caller is responsible for providing two classes; one being the DTO that holds the output generated by the ODBC library, and the second being the class that you are actually interested in. It would be great if the caller would not have to deal with the DTO, so ideally you can just write:</p>\n<pre><code>class Incident {\n long id;\n std::string comments;\n /* ... */\n std::string timeSend;\n};\n\nint main()\n{\n auto odbc = ...;\n OdbcBinder&lt;Incident&gt; binder(odbc,\n &amp;Incident::id,\n &amp;Incident::comments,\n ...\n &amp;Incident::timeSend\n );\n \n std::vector&lt;Incident&gt; v = binder.GetResult(...);\n}\n</code></pre>\n<p>The idea being that the constructor of <code>OdbcBinder</code> sees all the columns you want to bind up front, so it can create a DTO type. It will have to look like this:</p>\n<pre><code>template &lt;typename V, typename... ColTypes&gt;\nclass OdbcBinder final {\n Odbc&amp; m_odbc;\n std::tuple&lt;ColTypes V::*...&gt; m_columns;\n\n using T = std::tuple&lt;typename DTOType&lt;ColTypes&gt;::type...&gt;;\n std::vector&lt;T&gt; in(ROW_ARRAY_SIZE);\n ...\n OdbcBinder(Odbc&amp; odbc, ColTypes V::*... columns):\n m_odbc(odbc), m_columns(columns...)\n {\n // Bind columns\n ...\n }\n};\n</code></pre>\n<p>Amazingly enough, in C++17 and later, the compiler can even deduce all template parameter types from that constructor.\nTo create a tuple that will act as the DTO type we need to map from C++ column types to what ODBC expects. The helper template <code>DTOType</code> is there to do that:</p>\n<pre><code>template&lt;typename&gt; struct DTOType;\n\ntemplate&lt;&gt; struct DTOType&lt;long&gt; {\n using type = std::pair&lt;long, SQLLEN&gt;;\n static constexpr SQLSMALLINT sql_type = SQL_C_LONG;\n static long toValue(const type &amp;in) {\n return in.first;\n }\n};\n\ntemplate&lt;&gt; struct DTOType&lt;std::string&gt; {\n using type = std::pair&lt;char[1024], SQLLEN&gt;;\n static constexpr SQLSMALLINT sql_type = SQL_C_CHAR;\n static std::string toValue(const type *in) {\n return {in.first, in.second - 1};\n }\n};\n\n...\n</code></pre>\n<p>The difficulty is now when you have something like the timestamps. Either ensure you use a distinct C++ type for them, like <a href=\"https://en.cppreference.com/w/cpp/chrono/time_point\" rel=\"nofollow noreferrer\"><code>std::chrono::time_point</code></a>, or you have to find some other way to convey the desired conversion (I'll ignore this issue for now).</p>\n<p>Now that the column types are part of the class type, all member functions have access to them, so we no longer need to use a vector of variants to store the column type information. We still need to tell ODBC how to bind the columns though, and that's why there still is a <code>BindCol()</code> that we call in the constructor. Now we have to loop over the elements of the tuple <code>T</code> and the member-to-pointers that were passed to the constructor. We can do that like so:</p>\n<pre><code>OdbcBinder(Odbc&amp; odbc, ColTypes V::*... columns):\n m_odbc(odbc), m_columns(columns...)\n{\n std::apply([&amp;](auto&amp;... dto_columns) {\n (BindCol(dto_columns, columns) &amp;&amp; ...);\n }, in[0]);\n}\n</code></pre>\n<p>Here we use <code>std::apply()</code> on the first element of the array <code>in</code>, which is a tuple, so we can use a lambda to access each element of the tuple in a fold expression. This fold expression references both the parameter pack in <code>dto_columns</code> as well as the parameter pack <code>columns</code> from the constructor itself, which have the same size. We pass the column from the DTO type as well as the pointer-to-member of the final type to <code>BindCol()</code>, which looks like this:</p>\n<pre><code>template&lt;typename DTOColumn, typename ColType&gt;\nbool BindCol(DTOColumn &amp;dto_column, ColType V::* column) {\n SQLRETURN rc = SQLBindCol(stmt, ++N,\n DTOType&lt;ColType&gt;::sql_type,\n &amp;dto_column.first,\n sizeof dto_column.first,\n &amp;dto_column.second);\n return rc == SQL_SUCCESS;\n}\n</code></pre>\n<p>Now that we have done the <code>SQLBindCol()</code> statements, we can do a query and fetch the results. To handle the final conversion from the DTO to the desired C++ object we do a similar trick. First, let's simplify <code>GetResult()</code> a bit:</p>\n<pre><code>std::vector&lt;V&gt; GetResult(std::string_view sql) {\n ...\n std::vector&lt;V&gt; results;\n rc = SQLExecDirect(stmt, (SQLCHAR*)sql.data(), static_cast&lt;SQLINTEGER&gt;(sql.size()));\n ...\n for (SQLUINTEGER i = 0; i &lt; numRowsFetched; ++i) {\n auto is = std::make_index_sequence&lt;std::tuple_size_v&lt;T&gt;&gt;;\n results.push_back(Convert(in[i], is));\n }\n ...\n}\n</code></pre>\n<p>Now we can do the conversion of a single DTO object in this function:</p>\n<pre><code>template&lt;std::size_t... I&gt;\nV Convert(const T&amp; t, std::index_sequence&lt;I...&gt;) {\n V value;\n (value::*std::get&lt;I&gt;(m_columns) = DTOType&lt;ColTypes&gt;::toValue(std::get&lt;I&gt;(t)), ...);\n return v;\n}\n</code></pre>\n<p>I used a <a href=\"https://en.cppreference.com/w/cpp/utility/integer_sequence\" rel=\"nofollow noreferrer\"><code>std::index_sequence</code></a> here to help iterate over the tuple <code>t</code> as well as the tuple <code>m_columns</code> simultaneously, as <code>std::apply()</code> only takes one tuple as an argument.</p>\n<p>This also very template-heavy, but adding new conversion types should just require adding another variant of <code>struct DTOType</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:25:05.203", "Id": "532381", "Score": "0", "body": "`std::tuple<long, long>` is neither `std::is_standard_layout` nor `std::is_trivial`, is it ok?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:38:47.420", "Id": "532385", "Score": "0", "body": "That should not be a problem. The only issue might be that you might lose a bit of performance if you plan to resize the vector `in` often, which might require moving it in memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T18:02:47.140", "Id": "533283", "Score": "0", "body": "I updated code in question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T18:19:27.600", "Id": "533285", "Score": "0", "body": "I have rolled back that last update [per site policy](https://codereview.meta.stackexchange.com/a/1765/120114)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:10:48.067", "Id": "533355", "Score": "0", "body": "here is resulting code https://pastebin.com/MNU5K7P9" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T18:06:56.410", "Id": "533364", "Score": "0", "body": "@OwnageIsMagic Nice! You should create a new Code Review question and put the code there, so we can review your changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T14:52:03.493", "Id": "533919", "Score": "0", "body": "I created follow-up post https://codereview.stackexchange.com/questions/270384/sql-odbc-bind-to-c-classes-row-wise-follow-up" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T23:12:57.493", "Id": "269749", "ParentId": "220557", "Score": "2" } } ]
{ "AcceptedAnswerId": "269749", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T11:51:08.313", "Id": "220557", "Score": "5", "Tags": [ "c++", "c++20", "odbc" ], "Title": "SQL (ODBC) bind to C++ classes row-wise" }
220557
<p>The first code I ever wrote, sorry that the prints are in German. I tried to do some code improvements myself but well whenever I do I fail. Hopefully somebody can help me improve my coding skills.</p> <pre><code>while True: print(" ") print("ax^2+bx+c ausrechen UwU, Bitte Achte!!! Bei Kommazahlen . benutzen, nicht , Beispiel: 0.5 0.7 1.6") import time print("Auf ein Neues?") U1 = input("input a ") I1 = input("input b ") O1 = input("input c ") if (U1.isalpha() or I1.isalpha() or O1.isalpha()) is False: print("doing some math") a = float(U1) b = float(I1) c = float(O1) if ((b * b) - (4 * a * c)) &gt; 0: q = float(((b * b) - (4 * a * c)) ** (1 / 2)) x = float(2 * a) y = float(-1 * b) z = float(q * (-1)) result1 = str((y + q) / x) result2 = str((y + z) / x) print("Nullstelle1=" " " + result1 + "") print("Nullstelle2=" " " + result2 + "") abc = float((-1 * b) / (2 * a)) Moo = float((4 * a * c) - (b ** 2)) / (4 * a) cba = str(abc) oom = str(Moo) print("Scheitelpunkt: (" + cba + "|" + oom + ")") if (a &gt; 0) is True: print("Nach oben geöffnete Funktion") print("Schnittpunkt mit der Y-Achse ist" " " + O1 + " ") else: print("Nach unten geöffnete Funktion") print("Schnittpunkt mit der Y-Achse ist" " " + O1 + " ") else: print("sorry, geht nicht da eine negative zahl unter der wurzel sein würde") time.sleep(3) else: print("nur Zahlen bitte") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T14:34:37.607", "Id": "426188", "Score": "1", "body": "`(b * b) - (4 * a * c) == 0` is actually also fine, your two Nullstellen are just the same point. So it should be `(b * b) - (4 * a * c) >= 0`." } ]
[ { "body": "<p>welcome to code review!</p>\n\n<p>The first thing I want to do, is to put the code into a function. This separates it from anything else you might run, and allows you more control. I've used the name <code>quadratic_solver</code> and instead of taking input(), it now takes three arguments which are the coefficients. I've also added a docstring which briefly explains the function's purpose. </p>\n\n<p>My German's not very good so I've just left your comments in; apologies if they're now incorrect. As per PEP8 (python's style guide), I've put your import before the function at the start of the file.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import time\n\n\ndef quadratic_solver(a, b, c):\n \"\"\"\n Solves quadratic equations of the form ax**2 + bx + c\n \"\"\"\n\n print(\"ax^2+bx+c ausrechen UwU, Bitte Achte!!! Bei Kommazahlen . benutzen, nicht , Beispiel: 0.5 0.7 1.6\")\n\n...\n\n</code></pre>\n\n<p>Now, if you want to check the type of your arguments you can do a simple:</p>\n\n<p><code>type(val) is int</code> or <code>type(val) is str</code> for example. </p>\n\n<p>To loop over several values we can use a generator. Here, we loop over all values in a list <code>[a, b, c]</code> and ensure they are NOT all ints:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if not all(type(coeff) is int for coeff in [a, b, c]):\n</code></pre>\n\n<p>I'm not 100% sure why you're checking the type but perhaps your inputs are delicate in some way.</p>\n\n<p>The rest of the code is fairly unchanged. I have however removed a lot of the casting to floats and strings.</p>\n\n<p>If you want to concatenate strings with variables, you can use an fstring. This is of the form:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"Nullstelle1= {result1}\")\n</code></pre>\n\n<p>Where any variables are given in <code>{}</code> and an f at the start of the string denotes to put the variable inside the string <em>as a string</em>.</p>\n\n<p>fstrings can also contain code, so I've used a ternary operator instead of your if else statement:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"Nach {'oben' if a &gt; 0 else 'unten'} geöffnete Funktion\")\n</code></pre>\n\n<p>I've eliminated a few extra variables and brackets too, just for neatness. I'd recommend changing your variable names perhaps to something clearer, and adding a few comments to show what's going on.</p>\n\n<p>Putting this all together, we get:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import time\n\n\ndef quadratic_solver(a, b, c):\n \"\"\"\n Solves quadratic equations of the form ax**2 + bx + c\n \"\"\"\n\n print(\"ax^2+bx+c ausrechen UwU, Bitte Achte!!! Bei Kommazahlen . benutzen, nicht , Beispiel: 0.5 0.7 1.6\")\n\n if not all(type(val) is int for val in [a, b, c]):\n print(\"doing some math\")\n\n numer = b * b - 4 * a * c\n if numer &gt; 0:\n q = numer ** (1 / 2)\n\n result1 = (-b + q) / (2 * a)\n result2 = (-b - q) / (2 * a)\n\n print(f\"Nullstelle1= {result1}\")\n print(f\"Nullstelle2= {result2}\")\n\n abc = -b / (2 * a)\n moo = (4 * a * c - b ** 2) / (4 * a)\n\n print(f\"Scheitelpunkt: ({abc}|{moo})\")\n\n print(f\"Nach {'oben' if a &gt; 0 else 'unten'} geöffnete Funktion\")\n print(f\"Schnittpunkt mit der Y-Achse ist {c}\")\n\n else:\n print(\"sorry, geht nicht da eine negative zahl unter der wurzel sein würde\")\n time.sleep(3)\n else:\n print(\"nur Zahlen bitte\")\n\n</code></pre>\n\n<p>Finally, to call your function, you can now put the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == '__main__':\n quadratic_solver(1.0, 2.0, 3.0)\n\n</code></pre>\n\n<p>Wrapping the function in the <code>if __name__ == '__main__':</code> ensures the function is being run from the right place and not externally. <code>1.0</code>, <code>2.0</code> and <code>3.0</code> are just some example coefficients.</p>\n\n<p>I would also consider removing the <code>time.sleep(3)</code>; what is it for?</p>\n\n<p>EDIT:</p>\n\n<p>For the type checking, per @AlexV's comment, if you're checking an input is of a valid type, it's better to check it IS that type, rather than ISN'T another type. So the condition would actually become:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if all(type(coeff) is float for coeff in [a, b, c]):\n</code></pre>\n\n<p>You could even use Python's new type hinting if you like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def quadratic_solver(a: float, b: float, c: float):\n ...\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:42:54.890", "Id": "426177", "Score": "1", "body": "The \"type checking\" is performed on the user input to make sure it's just numbers, so it's more of an input validation. I think the OP introduced this to avoid exceptions during conversion with `float(...)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:48:20.333", "Id": "426180", "Score": "0", "body": "Added an edit to better explain type checking, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:58:15.000", "Id": "426181", "Score": "0", "body": "Excuse me if I've been misleading, but the original input validation implemented by the OP steps in earlier in the process. It tries to make sure that the input given by the user on the command line, which is always a string in Python 3, can actually be interpreted as a `float`. Your recommendations are nevertheless valid on their own right." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:36:12.843", "Id": "220567", "ParentId": "220560", "Score": "3" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/users/192268/\">@HoboProber</a> already gave a good <a href=\"https://codereview.stackexchange.com/a/220567/92478\">answer</a> talking about various improvements to be done on the code in general, so let's have a closer look at the core algorithm.</p>\n\n<hr>\n\n<p>Your implementation uses the <em>standard form</em> for quadratic equations</p>\n\n<p><span class=\"math-container\">$$a \\cdot x^2+b \\cdot x + c = 0$$</span></p>\n\n<p>and implements the well known <em>quadratic formula</em> to solve and analyze them.</p>\n\n<p><span class=\"math-container\">$$ x_{1,2} = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} $$</span></p>\n\n<p>The term under the square root is often called discriminant in English literature. Also, Python has a builtin <a href=\"https://docs.python.org/3/library/math.html\" rel=\"nofollow noreferrer\"><code>math</code></a> module with all kind of useful mathematical functions, e.g. <a href=\"https://docs.python.org/3/library/math.html#math.sqrt\" rel=\"nofollow noreferrer\"><code>math.sqrt(...)</code></a>, so there is no need to tinker with <code>... ** (1/2)</code>.</p>\n\n<p>With that (<a href=\"https://codereview.stackexchange.com/users/98493/\">and @Graipher's comment</a>) in mind, you should go from</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if ((b * b) - (4 * a * c)) &gt; 0:\n q = float(((b * b) - (4 * a * c)) ** (1 / 2))\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import math # at the beginning of the script\n\n... # other code here\n\ndiscriminant = (b * b) - (4 * a * c)\nif discriminant &gt;= 0:\n q = math.sqrt(discriminant)\n</code></pre>\n\n<p>Considering best-practices for programmers in general, and the already mentioned <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>, there are also some other variable names to be improved, especially <code>Moo</code> and <code>abc</code> since they are quite generic. In your case the coefficients <code>a</code>, <code>b</code>, and <code>c</code> would be exempt from that rule, since they have a quite well defined mathematical meaning in this context. </p>\n\n<p>Just be aware that relying on mathematical conventions can have \"unwanted\" side effects, since this will often mean others always try to see the mathematical meaning behind, possibly arbitrary named, single letter variables. That might lead to some confusion in your case since you're using <code>q</code>, which is also often used in an alternative formulation of the problem (see <a href=\"https://en.wikipedia.org/wiki/Quadratic_equation#Reduced_quadratic_equation\" rel=\"nofollow noreferrer\">Wikipedia - Reduced quadratic equation</a>), but with a different meaning.</p>\n\n<hr>\n\n<p>Another thing I would like to tell you about is Unicode support in Python. All strings in Python 3 are Unicode by default. That allows you to use something like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"a·x² + b·x + c = 0\")\n</code></pre>\n\n<p>directly in your code to generate a more visually appealing command line output.</p>\n\n<hr>\n\n<p>Python also has the notion of <a href=\"https://docs.quantifiedcode.com/python-anti-patterns/readability/asking_for_permission_instead_of_forgiveness_when_working_with_files.html\" rel=\"nofollow noreferrer\">\"It's easier to ask for forgiveness than it is to get permission\"</a>. In your context that would apply to the input validation section, which is a good thing to do! I just want to present an alternative approach to you.</p>\n\n<p>At the moment your code does the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>...\nU1 = input(\"input a \")\nI1 = input(\"input b \")\nO1 = input(\"input c \")\nif (U1.isalpha() or I1.isalpha() or O1.isalpha()) is False:\n print(\"doing some math\")\n a = float(U1)\n b = float(I1)\n c = float(O1)\n ...\nelse:\n print(\"nur Zahlen bitte\")\n</code></pre>\n\n<p>Here, you are trying to avoid situations where a conversion from string to float might raise an exception. So that would be the \"asking for permission\" part. The \"ask for forgiveness\"-way could be like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>...\ninput_a = input(\"input a \")\ninput_b = input(\"input b \")\ninput_c = input(\"input c \")\ntry:\n a = float(input_a)\n b = float(input_b)\n c = float(input_c)\nexcept ValueError:\n # float will throw an ValueError if it cannout convert the input\n print(\"nur Zahlen bitte\")\nelse:\n # you get here only if no ValueError was raised\n print(\"doing some math\")\n quadratic_solver(a, b, c) # this might be the function as proposed by HoboProber\n...\n</code></pre>\n\n<p>This approach actually tries to convert the given user input to a float and handles the case where it fails. In that way, it's often considered more direct and clearer on what you're trying to accomplish. In theory, there would also be no problem to not use the <a href=\"https://docs.python.org/3/tutorial/errors.html#handling-exceptions\" rel=\"nofollow noreferrer\"><code>else</code> block of try-except</a> and simply put it in the <code>try</code> block. The significant disadvantage of the second approach is that also every value error that might be raised in further computations would trigger <code>print(\"nur Zahlen bitte\")</code>, and therefore make it harder to find out what caused the problem in the first place. Some general recommendations for catching exceptions are:</p>\n\n<ol>\n<li>try-except as narrow as you can! This is a generalization of the statement above and means to only surround the parts you are willing to handle with a try-except structure. Otherwise debugging might get quite a bit harder.</li>\n<li>Only catch what you expect! Do <strong>not</strong> use <code>except</code> without specifying which exceptions should be handled unless you are a 100% sure that you absolutely don't care what's happening in that try-except. This blank <code>except</code> also catches keyboard interrupts using Ctrl+C, which can be, ummm, unconvenient sometimes.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T16:56:35.147", "Id": "220579", "ParentId": "220560", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T12:24:33.790", "Id": "220560", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Solve quadratic equation in standard form" }
220560
<p>I'm trying to optimize this nested foreach and if statement function for work. My code is retrieving data from a SSMS SQL database with thousands of fields from multiple tables of data, moving them to lists and then looping through the lists to retrieve the data. It is moving all the data to a data grid view to be exported to an excel sheet.</p> <p>Any ideas on how I can make it run faster?</p> <pre><code>foreach (Calibrations calibration in Model.PostCalibrationsList) { if (calibration.Job_No == textBox1.Text) { foreach (Instruments instrument in Model.InstrumentsList) { if (calibration.Inst_ID == instrument.Inst_ID) { foreach (Proc_InstInfo info in Model.Proc_InstInfoList) { foreach (ProcQRef qRef in Model.ProcQRefList) { if (calibration.Inst_ID == instrument.Inst_ID) { if (instrument.Procedure == info.Proc_No.ToString() &amp;&amp; instrument.Procedure == qRef.Procedure.ToString()) { ex.dataGridView1.Rows.Add(calibration.Order_No, calibration.Inst_ID, instrument.Description, calibration.Cust_Ref, instrument.Manufacturer, instrument.Model_No, instrument.Serial_No, info.Comm1, calibration.Calibration_Required, qRef.StockCode, calibration.Cert_No, info.Proc_No); } } } } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T12:46:04.767", "Id": "426168", "Score": "5", "body": "Could you add a description of what your code is actually doing? All I can gather is you're adding *something* to a data grid view. And make your title match what it's doing, not your concern about the code. How often is this snippet of code called? Perhaps you should show us the entire function, because as it stands you're just looping through every list and adding it to the data grid view, not really much room for optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T12:52:58.560", "Id": "426171", "Score": "2", "body": "1) Please refer to https://codereview.stackexchange.com/help/how-to-ask\n2) What is the reason you want to optimize this code? Is something running particularly slow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:17:17.100", "Id": "426172", "Score": "0", "body": "yeah it takes about 20 seconds to open the data grid view form" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T14:12:57.080", "Id": "426184", "Score": "0", "body": "Your title should describe what your code does, not what you want out of a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T14:32:30.447", "Id": "426186", "Score": "0", "body": "I think you have a copy/paste bug. There are two `if (calibration.Inst_ID == instrument.Inst_ID)` nested within each other. Obviously, only the first one matters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T14:35:52.563", "Id": "426189", "Score": "0", "body": "Also, LINQ can be your friend here: `foreach (Calibrations calibration in Model.PostCalibrationsList.Where(cal => cal.Job_No == textBox1.Text))` will filter out records without the need for nested `if`s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:32:34.120", "Id": "426257", "Score": "0", "body": "This is not a forum and we do not add any _[solved]_ etc, marking an answer is enougth... even though it's off-topic." } ]
[ { "body": "<p>Given that you say you're fetching the data from an SQL database, you should use it. It should be <em>much</em> faster to filter the data with a <code>WHERE</code> in the SQL query than to serialise it, deserialise it, and then filter it without the benefit of any indexes.</p>\n\n<p>Given this tiny fragment of code it's impossible to give more detailed advice on how to do that. It depends enormously on the ORM you're using.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:13:39.540", "Id": "426254", "Score": "0", "body": "i tried using where statements within the sql query and it made the process much faster (20 seconds down to 1-2 seconds), thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:55:49.100", "Id": "220569", "ParentId": "220562", "Score": "5" } } ]
{ "AcceptedAnswerId": "220569", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T12:42:10.830", "Id": "220562", "Score": "-1", "Tags": [ "c#", "winforms" ], "Title": "Adding filtered data from database into a grid view" }
220562
<p>I wrote this code to automate in Word from Visual Fox Pro. I put between the escapes <code>&lt;|&lt;</code> and <code>&gt;|&gt;</code> some VFP code (like take some values from tables and so on). At the press of a button, the code scans all of the document and, when finding these escapes, evaluates the instructions between. The last two <code>FOR</code> loops eliminate the escape strings.</p> <p>The code works, but I ask. Is there a better way to do what I look for?</p> <pre class="lang-vb prettyprint-override"><code>LOCAL oWord, oDocument, oRange, Lc_start, Lc_expr, Lc_ris, Ln_count, Lc_val DIMENSION Lc_funct[1] Lc_expr = "" Ln_count = 1 oWord = CREATEOBJECT("Word.Application") oWord.Visible = .T. cFile = GETFILE() oDoc = oWord.Documents.Add(m.cFile) oRange = oWord.ActiveDocument.Range() nWordCount = oRange.Words.Count oRange.Collapse(1) FOR nWord = 1 TO m.nWordCount-1 oRange.Expand(2) cWord = oRange.Text DO CASE CASE m.cWord = "&lt;|&lt;" Lc_start = .T. Lc_Expr = "" CASE m.cWord = "&gt;|&gt;" Lc_start = .F. Lc_funct[Ln_count] = Lc_Expr Ln_count = Ln_count + 1 DIMENSION Lc_funct[Ln_count] CASE m.Lc_start Lc_expr = Lc_expr + m.cWord OTHERWISE *do anything ENDCASE oRange.Collapse(0) ENDFOR FOR i = 1 TO Ln_count-1 oRange = oWord.ActiveDocument.Range() oRange.Find.Text = Lc_funct[i] oRange.Find.Replacement.Text = EVALUATE(Lc_funct[i]) lFound = oRange.Find.Execute( , , , , , , , , , , 2 ) ENDFOR FOR i = 1 TO Ln_count-1 oRange = oWord.ActiveDocument.Range() oRange.Find.Text = "&lt;|&lt;" oRange.Find.Replacement.Text = "" lFound = oRange.Find.Execute( , , , , , , , , , , 2 ) ENDFOR FOR i = 1 TO Ln_count-1 oRange = oWord.ActiveDocument.Range() oRange.Find.Text = "&gt;|&gt;" oRange.Find.Replacement.Text = "" lFound = oRange.Find.Execute( , , , , , , , , , , 2 ) ENDFOR MESSAGEBOX("DONE") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T08:20:14.097", "Id": "427244", "Score": "1", "body": "Is this real VBA or something closely related like vbscript? Don't recognise `DIMENSION` or `OTHERWISE` and there's no `Set` keyword used || Oh I see, `VFP` is a [programming language](https://en.m.wikipedia.org/wiki/Visual_FoxPro)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T11:28:56.320", "Id": "427273", "Score": "0", "body": "[Cross-posted on Stack Overflow](https://stackoverflow.com/q/56181607/1014587)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T17:35:54.087", "Id": "427321", "Score": "0", "body": "I recommend reading up on the `Range.Find` method, it's a lot more powerful than just find/replace. For starters, there's no need to loop in your last 2 find/replaces, since you use `wdReplaceAll`, it should remove all matches. In fact you can narrow it down further, with some [wildcards](https://wordmvp.com/FAQs/General/UsingWildcards.htm): `oRange.Find.Execute FindText:= \"[\\<\\>]|[\\<\\>]\", MatchWildcards:= True, ReplaceWith:= \"\", Replace:= 2`. That will catch `<|<` or `>|>`. You can probably eliminate looping altogether with some judicious `.Find`. (NB assuming VFP supports named arguments)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T07:46:19.723", "Id": "427418", "Score": "0", "body": "Where I can find some good documentation about word automation? there is something, but I need more specific analysis... By the way, thank you for your time, will try to implement this modifications..." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T13:19:00.997", "Id": "220565", "Score": "3", "Tags": [ "ms-word", "automation", "visual-foxpro" ], "Title": "Visual Fox Pro Automation" }
220565
<p>For a homework assignment, I was asked to complete <a href="https://www.codestepbystep.com/problem/view/javascript/strings/vowelCount" rel="nofollow noreferrer">this CodeStepByStep problem</a>. It's coded correctly and gave me a right answer. I'm just wondering if there's an easier way to solve this problem without the big blocky code in the <code>if</code> statement. The fact that I have to check each lowercase vowel AND THEN the uppercase vowel seems verbose.</p> <blockquote> <p>Write a function named vowelCount that accepts a string and returns the number of vowels (a, e, i, o, or u) that the string contains.</p> <p>For example, the call of <code>vowelCount(&quot;kookaburra&quot;)</code> should return 5 (two o's, 2 a's, and one u). When passed a string without any vowels (such as an empty string, &quot;01234&quot;, or &quot;sky&quot;), 0 should be returned.</p> </blockquote> <pre><code>function vowelCount(string) { if(string.length == 0) { return 0; } let count = 0; for(let i = 0; i &lt; string.length; i++) { let v = string[i]; if(v == &quot;a&quot; || v == &quot;e&quot; || v == &quot;i&quot; || v == &quot;o&quot; || v == &quot;u&quot; || v == &quot;A&quot; || v == &quot;E&quot; || v == &quot;I&quot; || v == &quot;O&quot; || v == &quot;U&quot;) { count += 1; } } return count; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T07:13:14.150", "Id": "426417", "Score": "5", "body": "I would just like to note that while the question and answers are perfectly ok, they only work for English. Many other languages, such as French, Norwegian, etc have a number of additional vowels. While it is irrelevant for a homework, it is good to keep that in mind, because many applications have become global, and localisation can become a topic, if what you do, is supposed to work in more countries than just the US. For example, when checking allowed symbols in a person's name." } ]
[ { "body": "<blockquote>\n <p>I'm just wondering if there's an easier way to solve this problem without the big blocky code in the <code>if</code> statement.</p>\n</blockquote>\n\n<p>Well, you could put all of those in an array:</p>\n\n<pre><code>const vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'];\n</code></pre>\n\n<p>And then the <code>if</code> condition can be simplified using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"noreferrer\"><code>Array.prototype.includes()</code></a>:</p>\n\n<pre><code>if( vowels.includes(v)) {\n</code></pre>\n\n<blockquote>\n <p>The fact that I have to check each lowercase vowel AND THEN the uppercase vowel seems verbose.</p>\n</blockquote>\n\n<p>You could also include either the uppercase or lowercase letters, and then call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase\" rel=\"noreferrer\"><code>String.prototype.toUpperCase()</code></a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase\" rel=\"noreferrer\"><code>String.prototype.toLowerCase()</code></a>, though if performance is your goal, then the extra function call might be something to consider.</p>\n\n<hr>\n\n<p>Additionally, a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"noreferrer\"><code>for...of</code></a> loop could be used instead of the regular <code>for</code> loop, to avoid the need to index into the array. </p>\n\n<pre><code>for( const v of string) {\n</code></pre>\n\n<p>And the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()\" rel=\"noreferrer\">postfix increment operator (i.e. <code>++</code>)</a> could be used to increase <code>count</code> instead of adding 1.</p>\n\n<p>The check for zero length string can be removed, since the loop won't be run.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const vowels = ['A', 'E', 'I', 'O', 'U'];\nfunction vowelCount(string) {\n let count = 0;\n for( const v of string) {\n if( vowels.includes(v.toUpperCase())) {\n count++;\n }\n }\n return count;\n}\n\nconsole.log(vowelCount('kookaburra'));\n\nconsole.log(vowelCount('sky'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>What follows are some advanced techniques that many wouldn't expect a beginner/intermediate-level student to utilize. If you really wanted to shorten this code, you could convert the string to an array with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"noreferrer\">the spread operator</a> and then use array reduction with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"noreferrer\"><code>Array.prototype.reduce()</code></a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const vowels = ['A', 'E', 'I', 'O', 'U'];\nconst charInVowels = c =&gt; vowels.includes(c.toUpperCase());\nconst checkChar = (count, c) =&gt; charInVowels(c) ? ++count : count; \nconst vowelCount = string =&gt; [...string].reduce(checkChar, 0);\n\nconsole.log(vowelCount('kookaburra'));\n\nconsole.log(vowelCount('sky'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>—-</p>\n\n<p><sub><strong>P.s.</strong><em>did you intentionally put an auto-comment about off-topic posts as the body of your profile??</em></sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T07:32:00.110", "Id": "426244", "Score": "0", "body": "Also, `if( string.length == 0) { return 0; }` is unnecessary. Looping through an empty string will just happen zero times and zero will be returned anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T11:05:54.990", "Id": "426281", "Score": "4", "body": "I know that this answer is correct, but being a homework assignment, if the level of the student is such that counting the vowels in a string is of reasonable difficulty, as a teacher I would be very suspicious if someone submitted code with `filter` or `reduce`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T15:16:46.430", "Id": "426319", "Score": "1", "body": "@JollyJoker - yeah I did consider suggesting the OP remove that; I have gone ahead and added that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T15:17:50.923", "Id": "426320", "Score": "1", "body": "@ChatterOne Would you not also be very suspicious if someone submitted code with code suggested in one of the other answers? I have added a preface to that last paragraph." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:55:20.550", "Id": "426413", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Honestly yes, but this goes down a somewhat \"depends on the person\" kind of path. Maybe the teacher accepts it even knowing that it's copy-pasted from internet, if the students can clearly show they understand how it works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T15:53:49.417", "Id": "426961", "Score": "0", "body": "@ChatterOne I'm not sure what else I could say that would be merit-worthy here, but FWIW there are a few relevant Meta posts where topics like this are discussed, like [_The ethics of answering a homework question before it is handed in_](https://codereview.meta.stackexchange.com/q/9154/120114) and [_Homework Questions_](https://codereview.meta.stackexchange.com/q/62/120114)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T16:31:17.020", "Id": "220577", "ParentId": "220575", "Score": "28" } }, { "body": "<p>An alternative route is to use <code>string.replace()</code> and Regular Expressions to strip everything but the vowels from the string. Then count the length of the resulting string. This avoids iteration altogether.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const vowelCount = s =&gt; s.replace(/[^aeiou]/gi, '').length\n\nconsole.log(vowelCount('The quick brown fox jumps over the lazy dog'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The regex is <code>/[^aeiou]/gi</code> which means match everything that's NOT (<code>^</code>) in the set (<code>aeiou</code>), matching globally (<code>g</code> flag) and without regard to case (<code>i</code> flag). <code>string.replace()</code> then uses this pattern to replace all matching characters with a blank string. What remains are your vowels.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T02:02:52.467", "Id": "426394", "Score": "15", "body": "*This avoids iteration altogether* - well, just wanted to point out that I'm confident the `replace()` method does its own iterating internally. (Still, I do think your point is valid.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T18:32:39.087", "Id": "486952", "Score": "2", "body": "I was wondering why not just `vowelCount = str => str.match(/[aeiou]/ig).length`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T16:33:40.190", "Id": "220578", "ParentId": "220575", "Score": "39" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/users/120114/s%E1%B4%80%E1%B4%8D-on%E1%B4%87%E1%B4%8C%E1%B4%80\">Sᴀᴍ Onᴇᴌᴀ</a> <a href=\"https://codereview.stackexchange.com/a/220577/120556\">answer</a> has the right idea for small strings, but can be improved by using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a> to hold the vowels rather than an array. This reduces the overhead of <code>Array.includes</code> which will iterate each character in the vowels array for non matching characters</p>\n\n<p>You can create a set as <code>const vowels = new Set([...\"AEIOUaeiou\"]);</code></p>\n\n<p>To encapsulate the constant <code>vowels</code> use a function to scope <code>vowels</code> outside the global scope and closure to make it available to the function.</p>\n\n<pre><code>const countVowels = (() =&gt; {\n const VOWELS = new Set([...\"AEIOUaeiou\"]);\n return function(str) {\n var count = 0;\n for (const c of str) { count += VOWELS.has(c) }\n return count;\n }\n})();\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>const countVowels = (() =&gt; {\n const VOWELS = new Set([...\"AEIOUaeiou\"]);\n return str =&gt; [...str].reduce((count, c) =&gt; count += VOWELS.has(c), 0);\n})();\n</code></pre>\n\n<h2>UNICODE vowels</h2>\n\n<p>Of course the first snippet is the better as it is <span class=\"math-container\">\\$O(1)\\$</span> storage and as it uses a <code>Set</code> (hash table) it is <span class=\"math-container\">\\$O(n)\\$</span> complexity (where <span class=\"math-container\">\\$n\\$</span> is the length of the string) rather than <span class=\"math-container\">\\$O(n*m)\\$</span> (where <span class=\"math-container\">\\$m\\$</span> is the number of vowels). This becomes more important if you are to include the full set of <a href=\"https://en.wikipedia.org/wiki/Phonetic_symbols_in_Unicode\" rel=\"nofollow noreferrer\">unicode vowels</a></p>\n\n<pre><code>const countVowels = (() =&gt; {\n // Reference https://en.wikipedia.org/wiki/Phonetic_symbols_in_Unicode\n const VOWELS = new Set([...\"AEIOUaeiouiyɨʉiyɯuɪʏeøɘɵɤoɛœɜɞʌɔaɶɑɒʊəɐæɪ̈ʊ̈IYƗɄIYƜUꞮʏEØɘƟɤOƐŒꞫɞɅƆAɶⱭⱰƱƏⱯÆꞮ̈Ʊ̈\"]);\n return function(str) {\n var count = 0;\n for (const c of str) { count += VOWELS.has(c) }\n return count;\n }\n})();\n</code></pre>\n\n<p><strong>NOTE</strong> the above snippet does not work.. see below.</p>\n\n<h2>Don't split unicode</h2>\n\n<p>If you are using Unicode it is important to release that each unicode 16 bit character does not always represent a single visual character</p>\n\n<p>For example the last two vowels \"ɪ̈ʊ̈\" require two characters to display. eg the string <code>\"\\u026A\\u0308\\u028A\\u0308\" === \"ɪ̈ʊ̈\"</code> is true. You can not just count them \nas in the expression <code>\"ɪ̈ʊ̈\".split(\"\").length</code> will evaluate to 4.</p>\n\n<p>This is even more problematic as <code>\\u026A</code> and <code>\\u028A</code> the first character codes are also vowels <code>\"ɪʊ\"</code></p>\n\n<p>To solve for the full set of vowels and keep the complexity at <span class=\"math-container\">\\$O(n)\\$</span> and storage at <span class=\"math-container\">\\$O(1)\\$</span> we can use 3 sets </p>\n\n<pre><code>const countVowels = (() =&gt; {\n const VOWELS = new Set([ ...\"AEIOUaeiouiyɨʉiyɯuʏeøɘɵɤoɛœɜɞʌɔaɶɑɒəɐæIYƗɄIYƜUʏEØɘƟɤOƐŒꞫɞɅƆAɶⱭⱰƏⱯÆ\"]);\n const VOWELS_DOUBLE = new Set([\"ɪ̈\", \"ʊ̈\", \"Ɪ̈\", \"Ʊ̈\"]);\n const VOWELS_SINGLE = new Set([...\"ʊɪƱꞮ\"]);\n return function(str) {\n var count = 0, prev;\n for (const c of str) { \n count += VOWELS.has(c);\n count += VOWELS_DOUBLE.has(prev + c) || VOWELS_SINGLE.has(prev);\n prev = c;\n }\n return count + VOWELS_SINGLE.has(prev);\n }\n})();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T07:27:21.080", "Id": "426243", "Score": "2", "body": "I was about to write a new answer, but it just a small modification to yours. Instead of `reduce`, I'd use `.filter(c => VOWELS.has(c)).length`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:28:08.863", "Id": "426255", "Score": "0", "body": "@JollyJoker My first example is the best as it is `O(1)` storage while using any of the array methods requires that the string be converted to an array that means storage is `O(n)`, on top of that using `Array.filter` to count means worst case would double the memory use" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T22:57:38.807", "Id": "486753", "Score": "0", "body": "Although what you are saying is correct and it is nice to point that a better data structure could be used, an array in this case is not really `O(n*m)`, because `m` is a constant (does not change with input) and does not impact in the asymptotical analysis Big Oh provides." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T03:01:35.663", "Id": "486767", "Score": "0", "body": "@Levon Yes I agree that for a fixed encoding the number of vowels is constant. However to quibble..The number of vowels is dependent on the character encoding used (any of an evolving set (ASCII, (ISO 8859 1-16), (unicode (UTF 8,16,32)), to name but a few)) thus in context of an indeterminate set of vowel representations `m` should be considered when defining `n`. In terms of complexity `O(n*m) == O(n)` I have not changed the Big Oh" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T14:59:56.200", "Id": "486921", "Score": "0", "body": "@Blindman67 Makes sense. Beginners will benefit from having this explicitly written :) Have a good one!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T17:39:12.563", "Id": "220582", "ParentId": "220575", "Score": "9" } }, { "body": "<p>Maybe there is a risk that the very same authority which is asking you to count vowels will soon ask you to count consonants, just to have you see how flexible your code is. </p>\n\n<p>So it could be a good idea to start with a function that takes two arguments: </p>\n\n<ol>\n<li>the string under test and </li>\n<li>the set of accepted vowels. </li>\n</ol>\n\n<p>Like function <code>countCharsFromVowelSet()</code> in the below code snippet.</p>\n\n<p>Note that deciding what exactly is an acceptable vowel is a language and country dependent decision.</p>\n\n<pre><code>const countCharsFromVowelSet = function(str, vowelSet) {\n let arr = [...str];\n let count = (arr.filter(c =&gt; vowelSet.includes(c))).length;\n return count;\n};\n\n/* auxiliary function builder function: */\nconst makeCharCounter = function(charSet) {\n return (str =&gt; countCharsFromVowelSet(str, charSet));\n};\n\nconst EnglishVowelList = \"AEIOUaeiou\";\nconst GermanVowelList = \"AEIOUYÄÖÜaeiouyäöü\";\n\nconst countEnglishVowels = makeCharCounter(EnglishVowelList);\nconst countGermanVowels = makeCharCounter(GermanVowelList);\n\ntext1 = \"William Shakespeare\";\ncount1 = countEnglishVowels(text1);\ntext2 = \"Die Schöpfung\";\ncount2 = countGermanVowels(text2);\n\nconsole.log(\"There are \" + count1.toString() + \" vowels in: \" + text1);\nconsole.log(\"There are \" + count2.toString() + \" vowels in: \" + text2);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T17:37:34.470", "Id": "426757", "Score": "0", "body": "Welcome to Code review and thanks for supplying an answer. Why use `var` for the variables inside the functions, as opposed to `let` and `const`? `Array.from(str)` could be optimized with `[...str]`. And the function returned by `makeCharCounter` could be simplified to `str => countCharsFromVowelSet(str, charSet);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T13:05:20.757", "Id": "426901", "Score": "1", "body": "@ Sᴀᴍ Onᴇᴌᴀ: yes you're right, thanks for pointing this out. I am more familiar with Python than with Javascript. My point was mostly about architecture and flexibility ; give a thought to possible specification changes. The vowel set for a given language is a piece of data to be imported from that part of the source code in charge of dealing with internationalization (i18n). You don't want to have to write the multiple OR construct for vowel-rich languages such as Russian and French." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T18:41:40.777", "Id": "220753", "ParentId": "220575", "Score": "3" } }, { "body": "<pre><code>function countVowels(str){\n let vowel_count = 0;\n str = str.toLowerCase();\n for (let i = 0; i &lt; str.length; i++) {\n if (str.charAt(i) === 'a' || str.charAt(i) === 'e' || str.charAt(i) === 'i' \n || str.charAt(i) === 'o' || str.charAt(i) === 'u'){\n vowel_count++;\n }\n }\n return vowel_count;\n}\nconsole.log(countVowels(&quot;Celebration&quot;))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T15:46:43.203", "Id": "486684", "Score": "3", "body": "Welcome. Please provide an explanation as how your code improves the existing one" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T15:11:08.133", "Id": "248466", "ParentId": "220575", "Score": "0" } } ]
{ "AcceptedAnswerId": "220578", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T16:03:30.897", "Id": "220575", "Score": "21", "Tags": [ "javascript", "strings", "homework", "ecmascript-6", "iterator" ], "Title": "Count all vowels in string" }
220575
<p>I am still learning Rust and I think I have a long way to go. This question is from <a href="https://exercism.io/my/tracks/rust#exercise-simple-linked-list" rel="noreferrer">exercism.io</a>. I am posting here to get some more reviews and suggestions to improve my code.</p> <p>Linked list aren't a good data structure but they help to learn a programming language better.</p> <p>I know I can use recursive calls for linked lists but that wouldn't be ideal since Rust doesn't do tail call optimizations.</p> <p>I see two problems in my code</p> <ol> <li><p>Repetitive - At places I think I can use functional style to remove duplication.</p></li> <li><p>Irresponsible borrows and references - Use of box, reference and indirection are not clean. I had to figure out to reach a compilable code but it makes me feel queasy. Can I make this cleaner.</p></li> </ol> <pre class="lang-rust prettyprint-override"><code>pub struct SimpleLinkedList&lt;T&gt; { head: Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt; } struct Node&lt;T&gt; { data: T, next: Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;, } impl&lt;T&gt; SimpleLinkedList&lt;T&gt; { pub fn new() -&gt; Self { SimpleLinkedList { head: None } } pub fn len(&amp;self) -&gt; usize { match &amp;self.head { None =&gt; 0, Some(node) =&gt; { let mut current: &amp;Node&lt;T&gt; = node; let mut length: usize = 1; while current.next.is_some() { current = current.next.as_ref().unwrap(); length = length + 1; }; length } } } pub fn push(&amp;mut self, _element: T) { let next: Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt; = self.head.take(); let new_node = Some(Box::new(Node { data: _element, next: next })); self.head = new_node; } pub fn pop(&amp;mut self) -&gt; Option&lt;T&gt; { let head: Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt; = self.head.take(); head.map(|x| { self.head = x.next; x.data }) } pub fn peek(&amp;self) -&gt; Option&lt;&amp;T&gt; { self.head.as_ref().map(|node| &amp;node.data) } } impl&lt;'a, T: Clone&gt; From&lt;&amp;'a [T]&gt; for SimpleLinkedList&lt;T&gt; { fn from(_item: &amp;[T]) -&gt; Self { let mut v = SimpleLinkedList::new(); _item.iter().for_each(|x| v.push(x.clone())); v } } impl&lt;T: Clone&gt; SimpleLinkedList&lt;T&gt; { pub fn rev(&amp;self) -&gt; SimpleLinkedList&lt;T&gt; { let mut ret_val = SimpleLinkedList::new(); match &amp;self.head { Some(node) =&gt; { let mut current: &amp;Node&lt;T&gt; = node; ret_val.push(current.data.clone()); while current.next.is_some() { current = current.next.as_ref().unwrap(); ret_val.push(current.data.clone()); }; ret_val } _ =&gt; ret_val, } } } impl&lt;T&gt; Into&lt;Vec&lt;T&gt;&gt; for SimpleLinkedList&lt;T&gt; { fn into(self) -&gt; Vec&lt;T&gt; { match self.head { Some(node) =&gt; { let mut v = Vec::new(); let mut current: Node&lt;T&gt; = *node; v.push(current.data); while current.next.is_some() { current = *current.next.unwrap(); v.push(current.data); } v.reverse(); v } None =&gt; vec![] } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T18:34:40.720", "Id": "427147", "Score": "1", "body": "no answers yet, maybe you can check out: [too many linked lists](http://cglab.ca/~abeinges/blah/too-many-lists/book/README.html) and\n [this book](https://www.amazon.com/Hands-Data-Structures-Algorithms-Rust/dp/178899552X/ref=sr_1_1?keywords=data+structures+in+rust&qid=1558809123&s=gateway&sr=8-1,) also this might be useful\n[docs for LinkedList](https://doc.rust-lang.org/1.28.0/std/collections/struct.LinkedList.html) you can check the source code." } ]
[ { "body": "<p>Suggestion: add an iterator. This both brings your container more into line with a standard rust container and could be used in many or your methods:</p>\n\n<ol>\n<li>len() could be implemented as <code>self.iter().count()</code></li>\n<li>rev() could be implemented as a for loop over self.iter()</li>\n<li>into() could <code>collect()</code> the iter to create the Vec&lt;>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T20:13:36.147", "Id": "429104", "Score": "0", "body": "Thanks, do lemme try that!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T00:36:13.957", "Id": "221687", "ParentId": "220576", "Score": "3" } }, { "body": "<p>As Winston said, adding an iterator will enable you to add quite a lot of functionality to this list quite easily. and can be done by wrapping your list in a tuple struct and implementing the desired traits - the <a href=\"https://rust-unofficial.github.io/too-many-lists/\" rel=\"nofollow noreferrer\">Linked List Guide</a> as recommended by lucarlig is a great resource and shows you how to do this</p>\n\n<p>A couple of other things to think about:</p>\n\n<ol>\n<li><p>Think about adding a <code>length: usize</code> property to your struct that you update privately as nodes are pushed and popped, this allows you to do a constant time lookup of your list length. Your current method of finding the length of the list requires you to iterate over the whole thing, resulting in <span class=\"math-container\">\\$O(n)\\$</span> time complexity for your length function which is quite inefficient.</p></li>\n<li><p>You could add a <code>peek_mut()</code> method quite easily to increase the functionality of the list, which is almost identical to your <code>peek()</code> method</p></li>\n<li><p>Implementing the 3 iterators (<code>into_iter() -&gt; Option&lt;T&gt;</code>, <code>iter() -&gt; Option&lt;&amp;T&gt;</code>, <code>iter_mut() -&gt; Option&lt;&amp;mut T&gt;</code>) will give you very concise implementations of things like <code>nth</code> <code>nth_mut</code> (effectively retrieving a value at index <code>x</code> - <em>although arguably if you needed to do that you shouldn't be using a linked list</em>). And as Winston said, will also allow you to convert from a <code>List&lt;T&gt; -&gt; Vec&lt;T&gt;</code> in one line - <code>self.into_iter().collect()</code></p></li>\n<li><p>Your current implementation doesn't define a <em>Drop</em> method, so will use the default recursive version that Rust derives for you <em>(I believe)</em>. So theoretically it's possible to hit the recursive depth limit. It would be safer to drop the list iteratively by implementing the drop trait with something like:</p></li>\n</ol>\n\n<pre class=\"lang-rust prettyprint-override\"><code>impl&lt;T&gt; Drop for SimpleLinkedList&lt;T&gt; {\n fn drop(&amp;mut self) {\n while self.pop().is_some() {}\n }\n}\n</code></pre>\n\n<ol start=\"5\">\n<li><p>Where you've used <code>while x.is_some() {}</code> loops, I think you could instead use a <code>while let</code> loop which is more idiomatic - <code>while let Some(data) = var { /* do something */ }</code>.</p></li>\n<li><p>You can either <code>match</code> or <code>.map</code> <code>Options</code> which can allow you to make your code slightly more concise, ie. your push and pop implementations can use the same logic you've applied to your peek implementation</p></li>\n<li><p>Just from a code readability standpoint, the compiler can <em>(I think)</em> infer all of the types you've used within your code blocks, so they don't need to be explicitly stated. However if you much prefer including them then type aliases could be useful - <code>type Link&lt;T&gt; = Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;;</code> for example.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T20:48:07.523", "Id": "236251", "ParentId": "220576", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T16:05:10.433", "Id": "220576", "Score": "5", "Tags": [ "linked-list", "rust" ], "Title": "Linked List In Rust" }
220576
<p>I have a .csv file of 8k+ rows which looks like this:</p> <pre><code> state assembly candidate \ 0 Andaman &amp; Nicobar Islands Andaman &amp; Nicobar Islands BISHNU PADA RAY 1 Andaman &amp; Nicobar Islands Andaman &amp; Nicobar Islands KULDEEP RAI SHARMA 2 Andaman &amp; Nicobar Islands Andaman &amp; Nicobar Islands SANJAY MESHACK 3 Andaman &amp; Nicobar Islands Andaman &amp; Nicobar Islands ANITA MONDAL 4 Andaman &amp; Nicobar Islands Andaman &amp; Nicobar Islands K.G.DAS party votes 0 Bharatiya Janata Party 90969 1 Indian National Congress 83157 2 Aam Aadmi Party 3737 3 All India Trinamool Congress 2283 4 Communist Party of India (Marxist) 1777 </code></pre> <p>The end dataframe I wanted to get was one which contains all the states as rows and two columns - one which has votes received by a particular party (<code>"Bhartiya Janata Party"</code>, in this case) in that row's state and another which has the total votes from the state. Like this: </p> <pre><code> State Total Votes BJP Votes Andaman &amp; Nicobar Islands 190328 90969.0 Andhra Pradesh 48358545 4091876.0 Arunachal Pradesh 596956 275344.0 Assam 15085883 5507152.0 Bihar 35885366 10543023.0 </code></pre> <p>My code works but I'm pretty sure there's a much better way to get this done using fewer lines of code and without creating too many dataframes. Here's my code:</p> <pre><code>dff = df.groupby(['party'])[['votes']].agg('sum') dff = dff.sort_values('votes') BJP_df = df[df["party"]=="Bharatiya Janata Party"] #print(BJP_df.head()) group = BJP_df.groupby(['state'])[['votes']].agg('sum') state = df.groupby(['state'])[['votes']].agg('sum') result = pd.concat([state, group], axis = 1, sort=False) result.columns = ["Total Votes","BJP Votes"] </code></pre> <p>Any tips, suggestions, pointers would be very much appreciated. </p>
[]
[ { "body": "<p>Here is one way using <strong><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html\" rel=\"nofollow noreferrer\"><code>df.pivot_table()</code></a></strong>:</p>\n\n<p>Replace any other party except <code>Bharatiya Janata Party</code> as <code>Others</code> using <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html\" rel=\"nofollow noreferrer\"><code>np.where()</code></a> and then use <code>pivot_table</code>, finally get <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sum.html\" rel=\"nofollow noreferrer\"><code>sum()</code></a> across <code>axis=1</code> for sum of votes.</p>\n\n<pre><code>df1=(df.assign(party=np.where(df.party.ne('Bharatiya Janata Party'),'Others',df.party)).\npivot_table(index='state',columns='party',values='votes',aggfunc='sum'))\n</code></pre>\n\n<hr>\n\n<p>Another method with <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html\" rel=\"nofollow noreferrer\"><code>crosstab()</code></a> similar to <code>pivot_table</code>:</p>\n\n<pre><code>df1=pd.crosstab(df.state,np.where(df.party.ne('Bharatiya Janata Party'),'Others',df.party)\n,df.votes,aggfunc='sum')\n</code></pre>\n\n<hr>\n\n<p>Finally, getting the Total and <code>reset_index()</code>:</p>\n\n<pre><code>df1=df1.assign(Total=df1.sum(axis=1)).reset_index().rename_axis(None,axis=1)\n</code></pre>\n\n<hr>\n\n<p><strong>Output:</strong> (<em>Note: I had added dummy <code>Andhra Pradesh</code> rows for testing</em>)</p>\n\n<pre><code> state Bharatiya Janata Party Others Total\n0 Andaman &amp; Nicobar Islands 90969 90954 181923\n1 Andhra Pradesh 100 85 185\n</code></pre>\n\n<p>You can opt to delete the <code>Others</code> column later : <code>df1=df1.drop('Others',1)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T11:55:54.700", "Id": "431563", "Score": "1", "body": "Almost thought this question was lost in the depths of Code Review. Thanks for the answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T12:08:31.853", "Id": "431565", "Score": "0", "body": "@Abhishek My pleasure. :) i started contributing to this community starting today. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T09:40:49.207", "Id": "222856", "ParentId": "220580", "Score": "1" } }, { "body": "<p>In all your code was not too bad. You can groupby on 2 items:</p>\n\n<pre><code>votes_per_state = df.groupby([\"state\", \"party\"])[\"votes\"].sum().unstack(fill_value=0)\n</code></pre>\n\n<blockquote>\n<pre><code>state Aam Aadmi Party All India Trinamool Congress Bharatiya Janata Party Communist Party of India (Marxist) Indian National Congress other\nAndaman &amp; Nicobar Islands 3737 2283 90969 1777 83157 0\nAndhra Pradesh 0 0 85 0 0 100\n</code></pre>\n</blockquote>\n\n<p>Then you can define which party you're interested in, and manually assemble a DataFrame</p>\n\n<pre><code>party_of_interest = \"Bharatiya Janata Party\"\nresult = pd.DataFrame(\n {\n party_of_interest: votes_per_state[party_of_interest],\n \"total\": votes_per_state.sum(axis=1),\n }\n)\n</code></pre>\n\n<blockquote>\n<pre><code>state Bharatiya Janata Party total\nAndaman &amp; Nicobar Islands 90969 181923\nAndhra Pradesh 85 185\n</code></pre>\n</blockquote>\n\n<p>If you want you can even add a percentage:</p>\n\n<pre><code>result = pd.DataFrame(\n {\n party_of_interest: votes_per_state[party_of_interest],\n \"total\": votes_per_state.sum(axis=1),\n \"pct\": (\n votes_per_state[party_of_interest]\n / votes_per_state.sum(axis=1)\n * 100\n ).round(1),\n }\n)\n</code></pre>\n\n<blockquote>\n<pre><code>state Bharatiya Janata Party total pct\nAndaman &amp; Nicobar Islands 90969 181923 50.0\nAndhra Pradesh 85 185 45.9\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T13:04:01.357", "Id": "431570", "Score": "0", "body": "I know that my code worked. I was just looking for something to improve efficiency as well as be more Pythonic. Seems like every project I work on ends up with me creating over 10-12 different dataframes. Don't know if that's just me. Thank you for your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T12:21:47.573", "Id": "222865", "ParentId": "220580", "Score": "2" } } ]
{ "AcceptedAnswerId": "222856", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T17:01:13.360", "Id": "220580", "Score": "4", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Grouping a Pandas Dataframe by two parameters" }
220580
<p>I am using <strong>Entity Framework Core</strong> as <strong>ORM</strong> in my <strong>ASP.NET Core 2.1 project</strong>. I want to perform <strong>server-side pagination</strong> in <strong>Career Controller</strong> for getting list of careers. I have a model which looks like:</p> <pre><code> public class Career { private string _title, _description; [Key] public long career_id { get; set; } [Required] [MaxLength(50)] public string title { get =&gt; _title; set { if (string.IsNullOrWhiteSpace(value)) { throw new NonEmptyValueException("Title is required."); } _title = value; } } [Required] public DateTime opening_date { get; set; } = DateTime.Now; public DateTime? closing_date { get; set; } [Required] [MaxLength(2000)] public string description { get =&gt; _description; set { if (string.IsNullOrWhiteSpace(value)) { throw new NonEmptyValueException("Description is required."); } _description = value; } } [MaxLength(70)] public string image_name { get; set; } public bool is_closed { get; set; } = false; public void markClosed() { is_closed = true; closing_date = DateTime.Now; } public void markUnclosed() { is_closed = false; closing_date = null; } } </code></pre> <p>This is how my <strong>DbContext</strong> looks like:</p> <pre><code> public class AppDbContext : DbContext { public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : base(options) { } public DbSet&lt;Career&gt; careers { get; set; } } </code></pre> <p>Currently, I am doing this way to perform server side pagination in Controller:</p> <pre><code>public IActionResult Index(CareerFilter filter = null) { try { var careers = _careerRepo.getQueryable(); if (!string.IsNullOrWhiteSpace(filter.title)) { careers = careers.Where(a =&gt; a.title.Contains(filter.title)); } careers = careers.Where(a =&gt; a.opening_date &gt;= filter.from_date &amp;&amp; a.opening_date &lt;= filter.to_date); ViewBag.pagerInfo = _paginatedMetaService.GetMetaData(careers.Count(), filter.page, filter.number_of_rows); careers = careers.Skip(filter.number_of_rows * (filter.page - 1)).Take(filter.number_of_rows); return View(careers.ToList()); } catch (Exception ex) { AlertHelper.setMessage(this, ex.Message, messageType.error); return Redirect("/admin"); } } </code></pre> <p>This is how my <strong>getQueryable()</strong> method in repository looks like:</p> <pre><code>public IQueryable&lt;Career&gt; getQueryable() { return _appDbContext.Set&lt;Career&gt;(); } </code></pre> <p>I am personally not satisfied with the way I am exposing queryable and performing all conditional query concatenation in Controller. Controllers looked messy with increase in number of conditions. Please suggest me a better way to perform same action. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T18:53:15.900", "Id": "426223", "Score": "2", "body": "I would only expose IQueryable for CQRS endpoints. In a system, I would prefer to create a DataLayer that exposes IEnumerable to upper layers. The filters would be performed in this layer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T21:47:34.710", "Id": "426228", "Score": "0", "body": "Why not just use OData to support paging against your web api. https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options and https://www.youtube.com/watch?v=ZCDWUBOJ5FU are good places to read up on it. Also with @dfhwze that if going to expose IQueryable then go the CQRS route. You don't have to use a framework you can build a simple one yourself if you don't want to take on extra dependency right now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:54:21.570", "Id": "426350", "Score": "0", "body": "One other remark I have: if you have a lot of operations with the same functionality in the try-catch block, you might want to consider AOP https://msdn.microsoft.com/en-us/magazine/dn574804.aspx for intercepting exceptions for all operations." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T18:47:35.447", "Id": "220585", "Score": "2", "Tags": [ "c#", "design-patterns", "asp.net-core", "entity-framework-core" ], "Title": "Querying based on condition" }
220585
<blockquote> <p>Implement a MapSum class with insert, and sum methods.</p> <p>For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.</p> <p>For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix.</p> <pre><code>Example 1: Input: insert("apple", 3), Output: Null Input: sum("ap"), Output: 3 Input: insert("app", 2), Output: Null Input: sum("ap"), Output: 5 </code></pre> </blockquote> <p>Please comment on performance and style</p> <pre><code>using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TrieQuestions { [TestClass] public class TrieMapSum { [TestMethod] public void MapSumTest() { MapSum mapSum = new MapSum(); mapSum.Insert("apple", 3); Assert.AreEqual(3, mapSum.Sum("ap")); mapSum.Insert("app", 2); Assert.AreEqual(5, mapSum.Sum("ap")); } } public class MapSum { private TrieMSNode Head; /** Initialize your data structure here. */ public MapSum() { Head = new TrieMSNode(); } public void Insert(string key, int val) { var current = Head; foreach (var letter in key) { if (!current.Edges.ContainsKey(letter)) { current.Edges.Add(letter, new TrieMSNode()); } current = current.Edges[letter]; } current.IsTerminal = true; current.Value = val; } public int Sum(string prefix) { int sum = 0; var current = Head; foreach (var letter in prefix) { if (!current.Edges.ContainsKey(letter)) { return sum; } current = current.Edges[letter]; } // we use dfs for each edges of the trie; return DFS(current); } private int DFS(TrieMSNode current) { if (current == null) { return 0; } int sum = current.IsTerminal ? current.Value : 0; foreach (var edge in current.Edges.Values) { sum += DFS(edge); } return sum; } } internal class TrieMSNode { public Dictionary&lt;char, TrieMSNode&gt; Edges { get; set; } public bool IsTerminal; public int Value; public TrieMSNode() { Edges = new Dictionary&lt;char, TrieMSNode&gt;(); IsTerminal = false; Value = 0; } } } </code></pre>
[]
[ { "body": "<p>In <code>Insert(...)</code> you should use <code>TryGetValue</code> instead of <code>ContainsKey</code>for efficiency:</p>\n\n<pre><code> foreach (var letter in key)\n {\n if (!current.Edges.TryGetValue(letter, out var edge))\n {\n edge = current.Edges[letter] = new TrieMSNode();\n }\n current = edge;\n }\n</code></pre>\n\n<hr>\n\n<p>Name your methods after what they do, not after their implementation:</p>\n\n<blockquote>\n <p><code>DFS(...)</code></p>\n</blockquote>\n\n<p>could be <code>GetSumFrom(...)</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code>public int Sum(string prefix)\n{\n int sum = 0;\n var current = Head;\n foreach (var letter in prefix)\n {\n if (!current.Edges.ContainsKey(letter))\n {\n return sum;\n }\n current = current.Edges[letter];\n }\n</code></pre>\n</blockquote>\n\n<p>Here the <code>sum</code> variable is redundant because it is never changed so you could just return <code>0</code> from the loop</p>\n\n<p>Again the loop can be optimized:</p>\n\n<pre><code> foreach (char letter in prefix)\n {\n if (!current.Edges.TryGetValue(letter, out current))\n return 0;\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>DFS()\n</code></pre>\n</blockquote>\n\n<p>can be simplified using LINQ:</p>\n\n<pre><code> private int GetSumFrom(TrieMSNode current)\n{\n if (current == null)\n {\n return 0;\n }\n\n return current.Edges.Aggregate(current.Value, (sum, kvp) =&gt; sum + GetSumFrom(kvp.Value));\n}\n</code></pre>\n\n<p>You really don't have to check for <code>IsTerminal</code> because you know that only terminal nodes have a values different from <code>0</code>.</p>\n\n<p>You should test this LINQ-approach against your own plain <code>foreach</code>-loop, and you'll maybe find the latter fastest. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T06:57:40.970", "Id": "426238", "Score": "1", "body": "I've upvoted because you make some good points, but I don't understand the reasoning in the first point. Surely the edge is the `KeyValuePair<char, TrieMSNode>`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T07:02:33.077", "Id": "426240", "Score": "1", "body": "@PeterTaylor: You're right, my misinterpretation of the Dictionary concept" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T06:23:59.130", "Id": "220607", "ParentId": "220586", "Score": "8" } }, { "body": "<p>I don't have much to add to Henrik's answer at a low level, but I think you've missed the point of the exercise at a high level.</p>\n\n<p>The spec could be implemented as simply as</p>\n\n<pre><code>public class MapSum\n{\n private readonly IDictionary&lt;string, int&gt; data = new Dictionary&lt;string, int&gt;();\n\n public void Insert(string key, int val) =&gt; data[key] = val;\n\n public int Sum(string prefix) =&gt; data.Sum(kvp =&gt; kvp.Key.StartsWith(prefix) ? kvp.Value : 0);\n}\n</code></pre>\n\n<p>The reason you instead used a trie was to avoid looping over all of the entries in <code>Sum</code>. But in the worst case <code>DFS</code> will do <em>exactly that</em>. The efficient solution is to add a field to <code>TrieMSNode</code> which caches the sum of the entire subtree rooted at that node. Updating it doesn't affect the asymptotic cost of <code>Insert</code>, just the constant. And returning it allows you to ditch <code>DFS</code> entirely, so that <code>Sum</code> is guaranteed to run in time linear in the length of the prefix.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T08:09:19.647", "Id": "426246", "Score": "0", "body": "Isn't your `sum()` implementation rather time-expensive (O(m*n)) and your storage rather memory-expensive?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:47:56.487", "Id": "426258", "Score": "0", "body": "@HenrikHansen, I'm not proposing that OP use the code I posted. Or was your point just that the trie is actually already not quite as bad, because its `Sum()` is only \\$O(n)\\$?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:02:10.283", "Id": "426306", "Score": "0", "body": "Just pondering but wouldn't an ordered dictionary be faster in the average case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:23:54.977", "Id": "426312", "Score": "0", "body": "@MD-Tech, faster than what at which operation? But anyway, I doubt it: hashmaps are very fast for insertion of random data and for iteration, and they're the slowest overall implementation mentioned so far." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:32:50.993", "Id": "426313", "Score": "0", "body": "@PeterTaylor I was thinking about the prefixed sum actually. As I said I'm only pondering aloud." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:58:50.110", "Id": "426351", "Score": "0", "body": "Peter Taylor it is part of the TRIE excercixes in leetcode explore data structures." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T07:28:20.430", "Id": "220611", "ParentId": "220586", "Score": "8" } }, { "body": "<p>The time complexity of <code>Sum</code> is <span class=\"math-container\">\\$O(m n)\\$</span>,\nbecause in the worst case it may need to enumerate all nodes.</p>\n\n<p>An <span class=\"math-container\">\\$O(m)\\$</span> implementation is possible with <span class=\"math-container\">\\$O(n)\\$</span> extra space, and a bit of extra work in <code>Insert</code>:</p>\n\n<ul>\n<li>Add a <code>Dictionary&lt;string, int&gt;</code> to track the current values of the keys, let's call it <code>values</code>.</li>\n<li>Use <code>TrieMSNode.Value</code> to store the sum of all values below each node</li>\n<li>When inserting:\n\n<ul>\n<li>First check if the key replaces an existing key. Let's store in <code>int prev</code> the previous value of the key, or 0 if there was no previous value (the key is new). </li>\n<li>Traverse the trie letter by letter as before, and for each node traversed, subtract <code>prev</code> and add <code>val</code>.</li>\n<li>Set the new value in <code>values</code>.</li>\n</ul></li>\n</ul>\n\n<p>Notice that the added work in <code>Insert</code> does not increase the time or space complexity.</p>\n\n<pre><code>public void Insert(string key, int val)\n{\n var prev = values.ContainsKey(key) ? values[key] : 0;\n values[key] = val;\n\n var current = Head;\n foreach (var letter in key)\n {\n if (!current.Edges.ContainsKey(letter))\n {\n current.Edges.Add(letter, new TrieMSNode(val));\n }\n else\n {\n current.Edges[letter].Value -= prev;\n current.Edges[letter].Value += val;\n }\n current = current.Edges[letter];\n }\n}\n</code></pre>\n\n<p>And now, the implementation of <code>Sum</code> can become simpler and faster:</p>\n\n<pre><code>public int Sum(string prefix)\n{\n var current = Head;\n foreach (var letter in prefix)\n {\n if (!current.Edges.TryGetValue(letter, out current))\n {\n return 0;\n }\n }\n return current.Value;\n}\n</code></pre>\n\n<p>Also notice that in this implementation the <code>TrieMSNode.IsTerminal</code> is no longer necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:22:28.080", "Id": "220668", "ParentId": "220586", "Score": "2" } } ]
{ "AcceptedAnswerId": "220607", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T20:20:26.037", "Id": "220586", "Score": "5", "Tags": [ "c#", "programming-challenge", "trie" ], "Title": "Leetcode: Map Sum Pairs C#" }
220586
<p>I have a set of files in folder <code>my_dir</code>, which is <strong>not</strong> the folder where my Python script resides. Sample content of <code>my_dir</code>:</p> <blockquote> <pre><code> foo.bar ba.bar moog_0001.h5 moog_0007.h5 moog_0020.h5 moog_0027.h5 moog_0032.h5 moog_0039.h5 moog_0041.h5 moog_0053.h5 moog_0060.h5 </code></pre> </blockquote> <p>I need to:</p> <blockquote> <ul> <li>find the files with extension <code>.h5</code></li> <li>for each such file, extract the 4 digits in the filename which follow the underscore <code>_</code>. <strong>Note</strong>: if a file has the extension <code>.h5</code>, its filename <strong>always</strong> contains a substring <code>_dddd</code>. There <strong>can</strong> be other digit groups in the full pathname of the file, but none starts with a <code>_</code>, followed by 4 digits, and ends with a <code>.</code></li> <li>if the resulting integer is <strong>not</strong> divisble by 20, delete the corresponding file</li> </ul> </blockquote> <p>According to these rules, after running the script the content of the folder <code>my_dir</code> must be:</p> <blockquote> <pre><code> foo.bar ba.bar moog_0020.h5 moog_0060.h5 </code></pre> </blockquote> <p>My solution:</p> <pre><code>import os import re MY_DIR = "/tmp/logs/20190519T1032" root, dirs, files = next(os.walk(MY_DIR, topdown=True)) files = [ os.path.join(root, f) for f in files ] print(files) files = [ file for file in files if file.endswith(".h5") ] for file in files: match = re.search(r'_\d{4}', file).group(0) match = match[1:] digits = int(match) if digits % 20 != 0: print("remove file " + file ) os.remove(file) else: print("skip file " + file) </code></pre> <p>Any suggestions? I was told to put the content of the <code>for</code> block in a function, in order to substitute the <code>for</code> block with a list comprehension, but I don't know if it would be significantly faster (the number of files is O(10<sup>3</sup>), tops). Also, the resulting function wouldn't do only one thing: at the very least, it would extract the 4 digits <strong>and</strong> delete those files for which the corresponding integer is not divisible by 20. I think that most functions should only one thing.</p>
[]
[ { "body": "<p><strong>Requirements</strong></p>\n\n<p>The requirements are somewhat imprecise because they rely on untold assumptions about the filenames we should expect. Before implementing anything, we should try to think about the different inputs we can have and how we should handle them.</p>\n\n<p>In our case, this could correspond to:</p>\n\n<ul>\n<li>what if the regexp does not match (no underscore or less than 3 numbers) ?</li>\n<li>what if we have more than 4 numbers ? Should we consider only the first 4 ?</li>\n<li>what if the pattern appears more than once ?</li>\n</ul>\n\n<p>In order to tests tests, I've defined the following list of file names from my invention.</p>\n\n<pre><code>files = [\n '.h5',\n '_.h5',\n 'foo_.h5',\n 'foo_123.h5',\n 'foo_1234.h5',\n 'foo_1240.h5',\n 'foo_12345.h5',\n 'foo_12340.h5',\n 'foo_12340.h5',\n 'foo_12400.h5',\n 'foo_12403.h5',\n 'foo_123_bar.h5',\n 'foo_1234_bar.h5',\n 'foo_1240_bar.h5',\n 'foo_12345_bar.h5',\n 'foo_12340_bar.h5',\n 'foo_12400_bar.h5',\n 'foo_12403_bar.h5',\n 'foo_1234_bar_1240.h5',\n 'foo_1240_bar_1234.h5',\n]\n</code></pre>\n\n<p>From here, changes in the code may be considered wrong as they could change the way the code behaves (on some of the inputs above) but I do not know what the expected behavior is.</p>\n\n<p><strong>Improving the code</strong></p>\n\n<p>The first thing we could do is try to be more robust when the pattern does not match.</p>\n\n<p>Usually after a call to <code>re.search</code>, the next step is \"if match\" (or \"if match is None\").</p>\n\n<p>Taking this chance to define variables with better names (\"digits\" instead of re-using \"match\" for the string of 4 digits, \"n\" instead of \"digits\" from the corresponding integer), we'd have something like:</p>\n\n<pre><code>\nfor f in files:\n match = re.search(r'_\\d{4}', f)\n if match is not None:\n digits = match.group(0)[1:]\n n = int(digits)\n if n % 20 != 0:\n print(\"remove file \" + f + \" (\" + digits + \")\")\n continue\n print(\"skip file \" + f)\n</code></pre>\n\n<p><strong>Removing the need for modulo</strong></p>\n\n<p>Division by 20 is simple enough so that the corresponding logic can be moved into the regexp.</p>\n\n<p><em>Disclaimer:</em> This may not correspond to something we usually want to do but it is fun and interesting so let's do it anyway :)</p>\n\n<p>A number is divisible by 20 if and only if:</p>\n\n<ul>\n<li><p>last digits is a 0</p></li>\n<li><p>the digit before that is divisible by 2</p></li>\n</ul>\n\n<p>We could write:</p>\n\n<pre><code>for f in files:\n match = re.search(r'_\\d\\d[02468]0', f)\n if match is None:\n print(\"remove file \" + f)\n else:\n print(\"skip file \" + f)\n</code></pre>\n\n<p><strong>Organisation</strong></p>\n\n<p>It would indeed be worth defining small functions to make your code easier to understand. We could imagine having a function \"def file_must_be_deleted(filename)\" return a boolean.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:04:28.713", "Id": "426262", "Score": "0", "body": "The \"untold assumptions\" seemed to me self-evident, given the example, but I may be wrong, thus I made them explicit. BTW, using a regexp to check for divisibility makes the code less readable than re-using variable names (which I agree is bad practice, and thank you for suggesting better names)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T08:14:01.937", "Id": "431163", "Score": "0", "body": "@DeltaIV: About readability: regex are not a tool to perform numeric tests in general, but in your case it's very simple to do. If you are afraid your code becomes less readable (and note that this is only a point of view), nothing forbids to add a comment in the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T14:33:12.843", "Id": "431210", "Score": "0", "body": "@CasimiretHippolyte having to add a comment to explain one line of code is a surefire proof that the code is unreadable. [Good code should be mostly self-documenting](https://stackoverflow.com/questions/209015/what-is-self-documenting-code-and-can-it-replace-well-documented-code). It's way better to kick out the regexp and use the boolean test." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T22:20:33.853", "Id": "220596", "ParentId": "220589", "Score": "2" } } ]
{ "AcceptedAnswerId": "220596", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T20:44:15.483", "Id": "220589", "Score": "4", "Tags": [ "python", "python-3.x", "regex", "file-system" ], "Title": "Find filenames with 4 digits which are not divisible by 20 and delete them" }
220589
<p>I'm building a "sliding puzzle" game. This is the animation code for when you click a Tile.</p> <p>This "loop" function is running all the time.</p> <p>When you click a tile, if it's available to move, I set the "isAnimating" property to true and then set the target left position, and the step (calculated with the starting and end position). The step is just an integer (negative or positive, depending on if the movement is to the left or to the right).</p> <pre><code>procedure TForm3.Loop(sender: tobject); var i : integer; begin for I := 0 to Tiles.Count - 1 do begin if(tiles[i].isAnimating) then begin if(tiles[i].animateProperty = 'left') then begin if(tiles[i].step &gt; 0) then begin if tiles[i].left &lt; tiles[i].animateTo - tiles[i].step then begin tiles[i].Left := tiles[i].Left + tiles[i].step; end else begin emptyTile.Left := tempX; emptyTile.Visible := true; tiles[i].isAnimating := false; tiles[i].Left := tiles[i].animateTo; end; end else begin if tiles[i].left &gt; tiles[i].animateTo - tiles[i].step then begin tiles[i].Left := tiles[i].Left + tiles[i].step; end else begin emptyTile.Left := tempX; emptyTile.Visible := true; tiles[i].isAnimating := false; tiles[i].Left := tiles[i].animateTo; end; end; end else begin if(tiles[i].step &gt; 0) then begin if tiles[i].top &lt; tiles[i].animateTo - tiles[i].step then begin tiles[i].top := tiles[i].top + tiles[i].step; end else begin emptyTile.top := tempY; emptyTile.Visible := true; tiles[i].isAnimating := false; tiles[i].top := tiles[i].animateTo; end; end else begin if tiles[i].top &gt; tiles[i].animateTo - tiles[i].step then begin tiles[i].top := tiles[i].top + tiles[i].step; end else begin emptyTile.top := tempy; emptyTile.Visible := true; tiles[i].isAnimating := false; tiles[i].top := tiles[i].animateTo; end; end; end; end; end; end; </code></pre> <p>This is how it works:</p> <ol> <li><p>Go through each tile, and check if the isAnimating property is true;</p></li> <li><p>If it is, check if the animation is a left or top one.</p></li> <li><p>If it's left, check if the step is greater than 0 (move to the right) or less than 0 (move to the left).</p></li> <li><p>If it's less than 0, check if the current left position is lower than the target (animateTo) position.</p></li> <li><p>If it is, then keep animating, if not, then stop the animation (and do a couple more things.</p></li> </ol> <p>The problem is there's a lot of repeating code but I can't seem to find a way to refactor it so that I avoid repeating myself.</p> <p>Of course I could use procedures for the same actions but I feel like there's a better way to do it than the way I do it (the animation).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T21:26:30.997", "Id": "426226", "Score": "0", "body": "Consdider using a local procedure definition with an appropriate callable function variable." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T21:11:17.217", "Id": "220592", "Score": "4", "Tags": [ "animation", "delphi", "sliding-tile-puzzle" ], "Title": "Animation loop for a sliding puzzle game" }
220592
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/add-strings/" rel="nofollow noreferrer">leetcode</a></p> <blockquote> <p>Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.</p> <p><strong>Note</strong>:</p> <ul> <li><p>The length of both num1 and num2 is &lt; 5100.</p></li> <li><p>Both num1 and num2 contains only digits 0-9.</p></li> <li><p>Both num1 and num2 does not contain any leading zero.</p></li> <li><p>You must not use any built-in BigInteger library or convert the inputs to integer directly.</p></li> </ul> </blockquote> <p><strong>My solution 1</strong></p> <pre><code>/** * @param {string} num1 * @param {string} num2 * @return {string} */ var addStrings = function(num1, num2) { let result = ''; let carry = 0; const LEN1 = num1.length - 1; const LEN2 = num2.length - 1; for (let i = 0, L = Math.max(LEN1, LEN2); i &lt;= L; i++ ) { const numb1 = num1[LEN1 - i] ? num1[LEN1 - i] | 0 : 0; const numb2 = num2[LEN2 - i] ? num2[LEN2 - i] | 0 : 0; const tmp = numb1 + numb2 + carry; carry = tmp &gt; 9 ? 1 : 0; result = `${tmp % 10}${result}`; } return carry &gt; 0 ? 1 + result : result; }; </code></pre> <p><strong>My solution 2</strong></p> <pre><code>/** * @param {string} num1 * @param {string} num2 * @return {string} */ var addStrings = function(num1, num2) { let result = ''; let carry = i = 0; const LEN1 = num1.length - 1; const LEN2 = num2.length - 1; while(num1[LEN1 - i] || num2[LEN2 - i]) { const numb1 = num1[LEN1 - i] ? num1[LEN1 - i] | 0 : 0; const numb2 = num2[LEN2 - i] ? num2[LEN2 - i] | 0 : 0; const tmp = numb1 + numb2 + carry; carry = tmp &gt; 9; result = tmp % 10 + result; i++; } return carry &gt; 0 ? 1 + result : result; }; </code></pre>
[]
[ { "body": "<h2>WARNING</h2>\n<p>Never do a double assignment in a variable declaration.</p>\n<pre><code>&quot;use strict&quot;;\nlet carry = i = 0; // throws i is not defined\n</code></pre>\n<p>Without strict mode there is no error and <code>i</code> is then declared in the global scope.</p>\n<p>Should be either</p>\n<pre><code>let carry, i;\ncarry = i = 0;\n</code></pre>\n<p>or</p>\n<pre><code>let carry = 0, i = 0;\n</code></pre>\n<p>or</p>\n<pre><code>let i = 0, carry = i;\n</code></pre>\n<h2>General</h2>\n<p>You can simplify some of the code.</p>\n<ul>\n<li><p>Rather than test for a character test the position <code>num1[LEN1 - i]</code> can be <code>(LEN1 - i) &gt;= 0</code></p>\n</li>\n<li><p>Rather than have <code>LEN1</code> and <code>LEN2</code> as constants use them as indexes saving the need to subtract <code>i</code> each time</p>\n</li>\n<li><p>Put the test for the last carry in the while loop to save the need to do the final test on return.</p>\n</li>\n<li><p>Shortening the variable name length lets you put the addition in one line. Generally I use <code>a</code>, <code>b</code> or <code>A</code> ,<code>B</code> for unspecific maths operations.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>I keep <code>carry</code> as a Number, JS optimizers don't like variables changing type. The benefit is tiny but on mass worth keeping in mind.</p>\n<p>Moved <code>tmp</code> to function scope to keep the inner loop free of tokens (noise)</p>\n<pre><code>function addStrings(a, b) {\n var la = a.length, lb = b.length, res = &quot;&quot;, carry = 0, tmp;\n while (la &gt; 0 || lb &gt; 0 || carry) {\n tmp = (la-- &gt; 0 ? +a[la] : 0) + (lb-- &gt; 0 ? +b[lb] : 0) + carry;\n carry = tmp / 10 | 0;\n res = tmp % 10 + res;\n }\n return res;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:51:02.087", "Id": "426410", "Score": "0", "body": "Wouldn’t it be more safe to have tmp as a constant the loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:13:16.077", "Id": "426437", "Score": "0", "body": "@thadeuszlay Safe? There are 7 lines of code!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:16:22.087", "Id": "426438", "Score": "0", "body": "Consistency of style? I’d personally always try to use const instead of car/let. Bứt that’s just my opinion" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T05:58:30.307", "Id": "220606", "ParentId": "220594", "Score": "2" } } ]
{ "AcceptedAnswerId": "220606", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T22:05:13.203", "Id": "220594", "Score": "3", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6" ], "Title": "Addition of Strings" }
220594
<p>I wrote this code in Haskell (instead of Python) for the educational benefit. Can anyone suggest ways to improve this code?</p> <p>I'm guessing that I'm using <code>fromIntegral</code> inefficiently.</p> <p>It takes two commandline arguments. The first is a path to a symmetric distance matrix. The second is a threshold. The program interprets vertices to be adjacent if their distance is less than the threshold. Then the program counts the number of connected components and the number of vertices in each connected component and prints this information. </p> <pre class="lang-hs prettyprint-override"><code>import System.Environment import Data.Matrix hiding (flatten) import qualified Data.Vector as V import Data.Graph import Data.Tree -- Turns a distance matrix to an adjacency matrix using a threshold, then prints the number -- and size of the connected components. -- Usage: run `stack run location_of_distance_matrix threshold` -- Output is in the form (number of bins, [number of vertices in each bin]). main :: IO () main = do args &lt;- getArgs contents &lt;- readFile $ args !! 0 let dmat = fromLists $ (map ((map (read :: String -&gt; Float)) . words) (lines contents)) amat = amatFromDmat dmat $ read (args !! 1) (g,_,_) = graphFromEdges (map (\n -&gt; (n, n, neighbours n amat)) [(1 :: Integer)..(fromIntegral $ ncols amat)]) comp = components g putStrLn $ show $ (length comp, map (length . flatten) comp) -- Transforms a distance matrix into an adjacency matrix using a threshold. amatFromDmat :: Matrix Float -&gt; Float -&gt; Matrix Bool amatFromDmat m e = matrix (nrows m) (ncols m) threshold where threshold (i,j) | i == j = False | m ! (i,j) &lt; e = True | otherwise = False -- Outputs the list of neighbours of a vertex in a graph, taking an adjacency -- matrix. -- The addition and subtraction of 1 are here because vectors are 0-indexed but -- I made my graph vertices 1-indexed. neighbours :: Integer -&gt; Matrix Bool -&gt; [Integer] neighbours n mat = map (fromIntegral . (1+)) $ filter (\m -&gt; row V.! m) [0..(ncols mat)-1] where row = getRow (fromIntegral n) mat </code></pre> <p>Edit: I found a bug and improved the code a little bit. </p>
[]
[ { "body": "<p>I haven't done a detailed review of Haskell code in a while, so I suspect my advice could structured better. Anyway, here's a mix of general and specific advice:</p>\n\n<ol>\n<li>\"Functional core, imperative shell\": Move more code out of <code>main</code> (and out of <code>IO</code>) into separate (pure) functions. The type signatures on the extracted functions will help with readability.</li>\n<li>Use types to model your domain. Haskell makes it easy to define expressive types, you should make use of that feature! :) For example, you could define <code>type AdjacencyMatrix = Matrix Float</code>.</li>\n<li>The <code>Int &lt;-&gt; Integer</code> conversions look unnecessary to me. Just stick to <code>Int</code> since the <code>Data.Matrix</code> API forces you to use it anyway.</li>\n<li>In general, it's a good idea to use as few partial functions as possible. (I see <code>(!!)</code>, <code>(Data.Vector.!)</code>, <code>read</code>, <code>getRow</code> and <code>fromInteger</code>) Since this is a script, using <code>read</code> for parsing is acceptable. Instead of indexing with <code>(Data.Vector.!)</code> and <code>getRow</code>, I'd try to map, fold or zip instead, which usually are total operations. Instead of extracting the command line arguments with (<code>!!</code>), you could write <code>[filename, threshold] &lt;- getArgs</code>.</li>\n<li><code>amatFromDmat</code> smells functorial to me, mostly because the input and output matrices have the same dimensions. Maybe try to implement it in terms of <code>fmap</code>. (Hint: If the input is a true distance matrix, the elements on the diagonal are the only ones that are <code>0</code>.)</li>\n<li>Use qualified imports or import lists to make it more clear, where functions are coming from. (I personally prefer qualified imports)</li>\n<li><code>Tree</code> has a <code>Foldable</code> instance and <code>length</code> is a method of <code>Foldable</code>. That means you can simply use <code>length</code> to get the size of the connected components. You don't need <code>flatten</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T22:25:32.260", "Id": "426384", "Score": "0", "body": "What is it about the `[filename, threshold] <- getArgs` option that avoids a total operation?\n\nAnd I'm very excited by your functoriality suggestion--I'm studying category theory on the math side and I want to see how to bring it to bear on my programming!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T22:52:55.440", "Id": "426386", "Score": "1", "body": "Yeah, that's not a great example. You could argue that replacing `(!)` with a partial pattern in IO (which would trigger `fail`) you move the partiality out of pure code, and into a `MonadFail` where failures happen anyway. In these circumstances it doesn't really matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T01:08:38.430", "Id": "426392", "Score": "1", "body": "Just implemented `amatFromDmat` using `fmap`. My mind is like:\nhttps://media.giphy.com/media/THFoDqDi4M92w/giphy.gif" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:05:02.077", "Id": "220660", "ParentId": "220595", "Score": "2" } } ]
{ "AcceptedAnswerId": "220660", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T22:10:12.140", "Id": "220595", "Score": "5", "Tags": [ "haskell", "graph", "matrix" ], "Title": "3-function program computing connected components of a point cloud given a distance matrix" }
220595
<p>This is the first little project I've made that didn't feel it was complete gibberish. But I couldn't tell.</p> <p>The biggest problem I had with this was using the <code>BoardValue</code> <code>enum</code> working like I wanted to. I understand that classes should have a level of abstraction to them and I suspect that the way I implemented the <code>at(int)</code> returning a <code>char</code> over a <code>BoardValue</code> took away from that. However, I though having to convert the return from <code>at(int)</code> to a char if it returned a <code>BoardValue</code> would be redundant. For example, using a statement like this:</p> <pre><code>char print_char = Board.at(some_index) == BoardValue::o ? 'O' : 'X'; </code></pre> <p>I hope I've done a decent job describing my dilemma.</p> <p>Overall, I'm hoping for some overall general code style tips and pointers on how to write better code from here.</p> <p><strong>tictactoe.h</strong></p> <pre><code>#ifndef TICTACTOE #define TICTACTOE #include &lt;array&gt; #include &lt;iostream&gt; enum BoardValue : char{ none = ' ', o = 'O', x = 'X' }; class Board { public: Board() { for(auto begin = board.begin(),end = board.end();begin != end; ++begin) *begin = BoardValue::none; } char at(int index) const{ return board.at(index); } inline bool check_win(BoardValue) const; bool place(int, BoardValue); private: bool check_diagonals(BoardValue) const; bool check_horizontals(BoardValue) const; bool check_verticals(BoardValue) const; std::array&lt;char, 9&gt; board{}; }; inline bool Board::check_win(BoardValue check) const { if(check == BoardValue::none) throw "Trying to check_win for check == BoardValue::none!"; return check_diagonals(check) || check_horizontals(check) || check_verticals(check); } #endif </code></pre> <p><strong>tictactoe.cpp</strong></p> <pre><code>#include "tictactoe.h" #include &lt;iostream&gt; //returns false if index is occupied bool Board::place(int index, BoardValue value) { if(board.at(index) != BoardValue::none) return false; board.at(index) = value; return true; } bool Board::check_diagonals(BoardValue check) const { //if middle is not check no diagnols will pass if(board.at(4) != check) return false; //backward diagonal '\' if(board.at(0) == check &amp;&amp; board.at(4) == check) return true; //forward diaganol '/' if(board.at(2) == check &amp;&amp; board.at(6) == check) return true; return false; } bool Board::check_horizontals(BoardValue check) const { for(int row = 0; row &lt; 3; ++row){ if(board.at(row) == check &amp;&amp; board.at(row + 3) == check &amp;&amp; board.at(row + 6) == check) return true; } return false; } bool Board::check_verticals(BoardValue check) const { for(int col = 0; col &lt; 3; ++col){ if(board.at(col * 3) == check &amp;&amp; board.at(col * 3 + 1) == check &amp;&amp; board.at(col * 3 + 2 ) == check) return true; } return false; } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include "tictactoe.h" #include &lt;iostream&gt; int ask_input(char player, bool retry = false) { if(!retry) std::cout &lt;&lt; "It's " &lt;&lt; player &lt;&lt; "'s turn. Where do you want to go(e.g. A1 B3 C2)? "; else std::cout &lt;&lt; "No, no, no " &lt;&lt; player &lt;&lt; "! Input a letter followed bt a number: "; std::string input; std::cin &gt;&gt; input; if(input.size() &lt; 2) return ask_input(player, true); int col_input{}; switch(*input.begin()) { case 'A': case 'a': col_input = 0; break; case 'B': case 'b': col_input = 1; break; case 'C': case 'c': col_input = 2; break; default: return ask_input(player, true); } int row_input = *(input.begin() + 1) - '0'; //convers char '1' to int 1 --row_input; return col_input * 3 + row_input; } BoardValue ask_turn() //ask whos first if return true O goes first { BoardValue turn; std::string input; std::cout &lt;&lt; "Who goes first(X or O)? "; for(bool valid_input{false}; !valid_input;) { std::cin &gt;&gt; input; switch(input.front()) //input cannot be null at this point { case 'x': case 'X': valid_input = true; turn = BoardValue::x; break; case '0': case 'o': case 'O': valid_input = true; turn = BoardValue::x; break; default: std::cout &lt;&lt; "Invalid input! Try X or O :"; } } return turn; } std::ostream &amp;print_board(std::ostream &amp;os,const Board &amp;board) { os &lt;&lt; " |A|B|C\n"; for(int row = 0; row &lt; 3; ++row) { os &lt;&lt; std::string( 8, '-') &lt;&lt; '\n'; os &lt;&lt; row + 1 &lt;&lt; '|'; for(int col = 0; col &lt; 3; ++col) { char follow_char{ col == 2 ? '\n' : '|' }; os &lt;&lt; board.at(col * 3 + row) &lt;&lt; follow_char; } } os &lt;&lt; std::endl; return os; } int main(){ Board board{}; BoardValue turn{ ask_turn() }; //turn will be set back to appropriate value at start of game loop turn = turn == BoardValue::o ? BoardValue::x : BoardValue::o; int turn_count{0}; while(board.check_win(turn) == false) { turn = turn == BoardValue::o ? BoardValue::x : BoardValue::o; print_board(std::cout, board); bool input_valid{false}; while(input_valid == false) { int input; input = ask_input(turn); input_valid = board.place(input, turn); if( input_valid == false ) std::cout &lt;&lt; "That place is take! Try again..\n"; } if(++turn_count == 9) //max amount of turns game is tie break; } print_board(std::cout, board); if(turn_count == 9)//game is tie std::cout &lt;&lt; "Looks like its a tie...\n"; else std::cout &lt;&lt; (char)turn &lt;&lt; " wins!\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T02:09:39.997", "Id": "426396", "Score": "2", "body": "This is pretty damn good for a new programmer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T09:52:43.723", "Id": "426430", "Score": "1", "body": "I did a little Tic-Tac-Toe program of my own a little while back. I considered using bitwise operations but I think it's overly complex with regards to readability. The best approach I came up with is keeping a score for each row, column and diagonal, and updating it after each move, then checking if the score is equal to a winning score on any of the rows, columns or diagonals. If you assign 'O' a score of 3 and 'X' a score of 4, then a winning score would be 9 for 'OOO' and 12 for 'XXX' and there's no way to get to those scores without 3 of the same symbols. Fast, clean and easy to follow." } ]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Use the required <code>#include</code>s</h2>\n\n<p>The code uses <code>std::string</code> which means that it should <code>#include &lt;string&gt;</code>. It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n\n<h2>Have you run a spell check on comments?</h2>\n\n<p>If you run a spell check on your comments, you'll find a number of things such as \"diagnols\" and \"diaganol\" instead of \"diagonals\" and \"diagonal.\" Since your code is nicely commented, it's worth the extra step to eliminate spelling errors.</p>\n\n<h2>Be wary of recursive calls</h2>\n\n<p>The <code>ask_input</code> routine has a subtle flaw. In particular, because it is recursive, it may be possible for a malicious user to crash the program by exhausting the stack. All that would be required would be to continue to input improperly formatted data. For this reason, as well as to make the code more understandable, I'd suggest instead to make <code>retry</code> a local variable and use that, as in a <code>while</code> loop, to re-ask if needed.</p>\n\n<h2>Fix the bug</h2>\n\n<p>The <code>ask_input</code> has a not-so-subtle flaw as well. It checks the letter, but not the number, so a user could input <code>C9</code> or <code>A0</code> and the program would attempt to use that! </p>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n\n<h2>Be judicious with the use of <code>inline</code></h2>\n\n<p>If a function is small and time critical, it makes sense to declare it <code>inline</code>. However, the <code>check_win</code> function is not really time critical, so I would say that there's no reason to make it <code>inline</code>.</p>\n\n<h2>Consider using a stream inserter</h2>\n\n<p>The existing <code>print_board</code> function is written exactly as one would write as one would write a stream inserter. The only thing that would change would be the declaration:</p>\n\n<pre><code>std::ostream &amp;operator&lt;&lt;(std::ostream&amp; os, const Board&amp; board) { /* ... */ }\n</code></pre>\n\n<h2>Simplify your constructor</h2>\n\n<p>The <code>Board</code> constructor is currently defined like this:</p>\n\n<pre><code>Board()\n{\n for(auto begin = board.begin(),end = board.end();begin != end; ++begin)\n *begin = BoardValue::none;\n}\n</code></pre>\n\n<p>There are at least three ways to simplify it. One would be to use a \"range-for\" syntax:</p>\n\n<pre><code>Board()\n{\n for(auto&amp; space : board) {\n space = BoardValue::none;\n }\n}\n</code></pre>\n\n<p>Another would be use <a href=\"https://en.cppreference.com/w/cpp/container/array/fill\" rel=\"noreferrer\"><code>fill</code></a>:</p>\n\n<pre><code>Board() {\n board.fill(BoardValue::none);\n}\n</code></pre>\n\n<p>A third way would allow you omit the constructor entirely. Do that by using <a href=\"https://en.cppreference.com/w/cpp/language/aggregate_initialization\" rel=\"noreferrer\">aggregate initialization</a> in the declaration of <code>board</code>:</p>\n\n<pre><code>std::array&lt;char, 9&gt; board{\n ' ',' ',' ',\n ' ',' ',' ',\n ' ',' ',' ',\n};\n</code></pre>\n\n<h2>Think carefully about the class design</h2>\n\n<p>The structure of the code is not bad, but some things to think about are what things should be the responsibility of the <code>Board</code> class and which are not. For example, I think it might make more sense for <code>Board</code> to keep track of the number of turns.</p>\n\n<h2>Simplify the code</h2>\n\n<p>This line is not easy to read or understand:</p>\n\n<pre><code>turn = turn == BoardValue::o ? BoardValue::x : BoardValue::o;\n</code></pre>\n\n<p>I would suggest instead having <code>turn</code> be a <code>bool</code> that represents <code>O</code>. Then flipping back and forth would simply be <code>turn = !turn;</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T03:02:54.420", "Id": "426233", "Score": "3", "body": "`inline` has exactly one effect left: It allows the symbol to be supplied, with identical definition, by multiple translation-units. As compilers can only inline what they can see, without lto the candidate must be in the same TU." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:51:20.667", "Id": "426259", "Score": "0", "body": "`for (auto space : board)` should be `for (auto& space : board)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:05:15.907", "Id": "426263", "Score": "0", "body": "@Deduplicator: my advice on `inline` parallels that of the [C++ guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-inline)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:05:46.663", "Id": "426264", "Score": "0", "body": "@L.F. You're right; I've corrected my answer. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:58:58.067", "Id": "426317", "Score": "1", "body": "`inline check_win` is probably actually *detrimental* to performance if the compiler makes the wrong decision: it turns one non-inline function call into 3, to `check_diagonals`, `check_horizontals`, and `check_verticals`. What you want is for all 3 of those to inline into `check_win` so they can all optimize together and keep reused data (especially the centre) in registers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T15:04:30.723", "Id": "426318", "Score": "0", "body": "Of course `check_win` becomes performance-critical if you implement an AI move-decision algorithm that simply recurses down the possible moves to find forced wins and avoid forced losses. (A tic-tac-toe *playing* program in C is the only first-year computer science assignment I still remember. I even added a mode where it makes random legal moves until there's a forced win or forced loss possible on the very next turn, then it plays to win or block. For move input, I used numbers from 1 to 9, i.e. from the numpad. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T02:06:03.957", "Id": "426395", "Score": "0", "body": "As the code currently structured, inline specifier is required for `check_win` because it is defined in a header file. As @Deduplicator alluded to, without inline specifier it could cause ODR violation. Of couse the definition of `check_win` could be moved into the class definition where it is implicitly inlined. With regards to the actual performance, what is important is actually bench marking it instead of theorizing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:00:12.887", "Id": "426511", "Score": "0", "body": "@wooooooooosh: yes, of course you can't *just* remove the `inline` keyword without making other changes. You have to move the definition to the `.cpp`. Re: benchmarking: with the current surrounding code, it's not easy. And surrounding code *always* matters, esp. for inlining decisions. I wouldn't entirely discount theorizing, though, when done by someone who understands compilers work, and how modern out-of-order execution x86 CPUs run code. (check my Stack Overflow profile: gold badges in `[performance]`, `[cpu-architecture]`, and `[gcc]` tags, etc). I *could* be wrong, but I'm often not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:27:13.963", "Id": "426527", "Score": "0", "body": "I think that all would agree that with compilers as in auto racing, the *stopwatch* is the ultimate arbiter. I agree that theorizing is fine and useful when appropriately applied, which is when it augments rather than supplants measurement." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T01:05:47.523", "Id": "220599", "ParentId": "220597", "Score": "25" } }, { "body": "<p>In addition to Edwards answer, there is a bug in <code>check_diagonals</code>. The first check for the <code>'\\'</code> diagonal should check for positions <code>0</code> and <code>8</code>.</p>\n\n<p>I think you also switched up the names for <code>check_horizontal</code> and <code>check_vertical</code>, since <code>check_vertical</code> effectively checks the rows and <code>check_horziontal</code> checks columns.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:25:36.667", "Id": "426560", "Score": "1", "body": "I think horizontal and vertical are correct as written. The 9-character array could be interpreted as row-major (the more common interpretation), but look how print_board looks up a location: `col * 3 + row`. This array is being interpreted as column-major, transposed 90 degrees from how you are used to mapping 2D grids to 1D arrays, so `check_vertical` is indeed checking the columns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T13:56:01.243", "Id": "426683", "Score": "0", "body": "@amalloy In that case, `check_diagonals` has weird commentary, since they check for the `'\\'` diagonal by checking 0, 4 and 8 (or at least they meant to) and they check for `'/'` by checking 2, 4, and 6. I have assumed row major notation after reading that comment." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:16:39.003", "Id": "220623", "ParentId": "220597", "Score": "8" } }, { "body": "<p>This is a code inspection so it's my role to raise questions, not to answer them. I haven't run your code. Did you check your end condition? It appears to me that the first player, let's say it's x, goes on turn_count 0, 2, 4, 6, 8. In the loop when turn_count is 8 you will accept input from x, place it on the board, then increment turn_count to 9 and break out of the loop. The end condition then checks that count is nine and concludes it's a tie. Thus any game that fills the board is classed a draw, without checking it.</p>\n\n<p>The best solution for that is to move the turn count check into the while condition, testing it second, and saving the result of the win checking in a variable for testing outside the loop.</p>\n\n<p>You can also turn the while-do into a do-while since neither a win nor an exceeded turn count can occur at the beginning.</p>\n\n<p>Then make sure you test a game with a player winning with a full board.</p>\n\n<p>And please, even if you can't spell-check your comments as the current best answer suggests, at the very least ensure that all your printed output is spelled correctly! If you start working for a company producing real code those typos are simply an embarrassing proof that the code was never reviewed or thoroughly tested.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T19:34:00.697", "Id": "220669", "ParentId": "220597", "Score": "5" } }, { "body": "<p>A company I used to work for asked candidates to code a quick Tic Tac Toe implementation as part of the interview process. We used these to sanity check a candidate's basic ability to code. Based on that experience, I have two pieces of general feedback.</p>\n\n<ol>\n<li><p>Stylistically, this code strikes me as workable but a bit windy / verbose. You're using \"object orientation\" but there's no real sophistication in the OOP, nor any need for it over such a simple domain, so your objects are just containers with friendly names. You're writing explicit code to check columnar and row state (<code>CheckVerticals</code>, <code>CheckHorizontals</code>, <code>CheckDiagonals</code>) which is easily normalized. This code may work, but it's not a joy to read and doesn't seem to have a cohesive shape beyond OOP-by-default. That said, it's still better than the majority of TTT samples I've looked at.</p></li>\n<li><p>What would give your code a more cohesive shape? One way would be: rewrite your code <a href=\"https://codepen.io/labiej/post/using-bit-logic-to-keep-track-of-a-tic-tac-toe-game\" rel=\"nofollow noreferrer\">using bitwise operations to represent board state and detect win conditions</a>. This would shorten and tighten your logic, and in particular, those cumbersome explicit checks for various win conditions would melt away.</p></li>\n</ol>\n\n<p>All in all, your code is good enough I would feel comfortable, in a formal code review, pushing you to produce something tighter and a bit more opinionated. If you can produce the above code, you can produce the above code with tighter logic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T03:38:30.847", "Id": "220691", "ParentId": "220597", "Score": "4" } }, { "body": "<p>Some little things not mentioned yet:</p>\n\n<p>If you are using C++11 or higher consider using the more safe <code>enum class</code> instead of the plain <code>enum</code> inherited from C. See: <a href=\"https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum\">https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum</a></p>\n\n<p>Always use Brackets. Its more safe. See: <a href=\"https://softwareengineering.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no\">https://softwareengineering.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no</a></p>\n\n<p>This:</p>\n\n<p><code>std::ostream &amp;print_board(std::ostream &amp;os,const Board &amp;board)</code></p>\n\n<p>Should be formated like this:</p>\n\n<p><code>std::ostream&amp; print_board(std::ostream&amp; os,const Board&amp; board)</code></p>\n\n<p>Atleast in the C++ style its more common to add Pointer <code>*</code> or reference <code>&amp;</code> to the type, not to the variable name (In C code the other is more common).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T05:55:02.560", "Id": "220698", "ParentId": "220597", "Score": "2" } } ]
{ "AcceptedAnswerId": "220599", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T23:30:16.750", "Id": "220597", "Score": "21", "Tags": [ "c++", "tic-tac-toe" ], "Title": "First Program Tic-Tac-Toe" }
220597
<p>A Fibonacci sequence is the integer sequence of <code>0, 1, 1, 2, 3, 5, 8....</code>.</p> <p>The first two terms are <code>0</code> and <code>1</code>. All the other terms are obtained by adding the preceding two terms.</p> <p>Here is my code:</p> <pre><code>def recur_fibonacci(n): if n &lt;= 1: return n else: return(recur_fibonacci(n - 1) + recur_fibonacci(n - 2)) nterms = int(input("How many terms? ")) if nterms &lt;= 0: print("Please enter a positive integer!") else: print("Fibonacci sequence:") for i in range(nterms): print(recur_fibonacci(i)) </code></pre> <p>So I would like to know whether I could make this program shorter and more efficient.</p> <p>Any help would be highly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T19:27:02.490", "Id": "426369", "Score": "2", "body": "Your biggest issue here is algorithmic, but several of the answers comment on code style/PEP (and yet leave the fundamental problem unaddressed). This un-memoised algorithm solves the same subproblem many times; in fact try fib(1000) and you will see you will not be able to run it. You need to cache the results of subproblems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T22:04:25.273", "Id": "426382", "Score": "1", "body": "I will also note that you are talking about computing the Fibonacci *sequence* recursively, but you actually compute Fibonacci *numbers* recursively and use a loop to compute the Fibonacci *sequence*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T09:04:41.943", "Id": "426427", "Score": "1", "body": "@Tommy There are un-memoised fibonacci implementations that run in O(n). They just don’t use the naïve algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:36:30.820", "Id": "426443", "Score": "1", "body": "For people viewing this question, take a look at [Konrad Rudolph's answer](https://codereview.stackexchange.com/questions/220600/python-program-for-fibonacci-sequence-using-a-recursive-function/220713#220713), which provides a very good answer to my question (alongside other questions), too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:42:37.003", "Id": "426446", "Score": "1", "body": "@Justin, uptonogood's answer is the best by far. The others focus in on the trees and don't see the forest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T03:26:45.010", "Id": "426597", "Score": "0", "body": "For people viewing this question, take a look at [user513093's answer](https://codereview.stackexchange.com/questions/220600/python-program-for-fibonacci-sequence-using-a-recursive-function/220760#220760), which provides a very good answer to my question by addressing algorithm." } ]
[ { "body": "<p>After a quick pass, this is what I have for you:</p>\n\n<p><strong>If/Else:</strong> </p>\n\n<p>For a recursive function, you don't usually need to specify the else. Just <code>return</code> if the base case is true.</p>\n\n<p><strong>Validating User Input</strong></p>\n\n<p>To make sure the user enters the correct input, have it in a <code>while True:</code> loop. Then you can break when the user enters an input that satisfies the program.</p>\n\n<p><strong>Main</strong></p>\n\n<p>Use <code>if __name__ == __main__</code>. This ensures that it can't be run externally, and only from that file.</p>\n\n<p><strong>Updated Code, should you choose to use it:</strong></p>\n\n<pre><code>def recur_fibonacci(n):\n if n &lt;= 1:\n return n\n return(recur_fibonacci(n-1) + recur_fibonacci(n-2))\n\ndef main():\n while True:\n nterms = int(input(\"How many terms? \"))\n\n if nterms &lt;= 0:\n print(\"Please enter a positive integer!\")\n else:\n print(\"Fibonacci sequence:\")\n for i in range(nterms):\n print(recur_fibonacci(i))\n break\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T13:12:14.143", "Id": "426297", "Score": "5", "body": "Since you already recommended using a `while True` loop, why not add a `try...except ValeuError` to catch the user entering a string that cannot be interpreted as an integer?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T03:36:56.593", "Id": "220601", "ParentId": "220600", "Score": "5" } }, { "body": "<p>Some ideas:</p>\n\n<ul>\n<li>A recursive solution is only as efficient as the equivalent iterative solution if the compiler/interpreter is smart enough to unroll it into an iterative solution. I'd love to be corrected, but I don't believe the Python interpreter is able to unroll recursive algorithms such as this one. If that is so, an iterative solution will be more efficient. An intermediate solution would be to create a cache of values returned so far to avoid having to recompute every value at every step.</li>\n<li><p>This code, like basically any Python code, could benefit from a run through Black, flake8 and mypy with a strict configuration like this:</p>\n\n<pre><code>[flake8]\nexclude =\n .git,\n __pycache__\nmax-complexity = 4\nignore = W503,E203\n\n[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n<li>Taking user input interactively is bad, because it means your code can't be included in non-interactive code. Use <code>argparse</code> to get a value when starting the program.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T15:58:49.287", "Id": "426325", "Score": "1", "body": "@Jasper It's not tail recursion. The compiler has to a) call `recur_fibonacci(n - 1)` and save the return value; b) call `recur_fibonacci(n - 2)`; c) add the saved value from the previous call to the returned value from this call; d) return the sum. The need for the addition after both calls means there is no opportunity for tail recursion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T16:06:35.163", "Id": "426326", "Score": "4", "body": "@Jasper Python doesn't and will never optimize tail recursion: https://stackoverflow.com/questions/13591970/does-python-optimize-tail-recursion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T16:26:55.887", "Id": "426328", "Score": "1", "body": "@Jasper: an easy way to spot tail calls and tail recursion is to write the `return` expression in function call form. (Kind of like Lisp.) In this case, it would look something like this: `plus(recur_fibonacci(n - 1), recur_fibonacci(n - 2))`. Now, it becomes immediately obvious that the tail call is to `plus` and not to `recur_fibonacci`, and thus `recur_fibonacci` is not tail-recursive. Also, as was pointed out in another comment, Guido van Rossum has more or less explicitly forbidden TCO for any Python implementation. (Which makes zero sense, but that's how it is.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T02:51:43.057", "Id": "426398", "Score": "2", "body": "I would never recommend `argparse` or `optparse` anymore. [`click`](https://click.palletsprojects.com/) is vastly simpler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T07:38:34.580", "Id": "426421", "Score": "1", "body": "@MartinBonner Good catch. It has been too long since I was taught about tail recursion and I was thinking about it too simply." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T09:31:13.153", "Id": "426428", "Score": "1", "body": "@mephistolotl Never say never. Guido is no longer BDFL, and he has in the past changed his mind on fundamentals, notably the importance of type annotations. Tail call optimisation may never be a priority for Python but I wouldn’t be too surprised if a future version of the main Python execution engine performed it anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T17:53:09.310", "Id": "426544", "Score": "1", "body": "@KonradRudolph: TCO is not really useful, since it is an implementation-specific private internal implementation detail. Proper Tail Calls in the Language Specification would be interesting, though, because then you can write code that relies on them, knowing that whatever implementation your code runs on, it will *always* work. Of course, implementation buy-in is important, too, otherwise, you end up with a situation like ECMAScript. The spec has proper tail calls, but the implementors refuse to implement them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T10:00:43.040", "Id": "426650", "Score": "0", "body": "@JörgWMittag I disagree. First off, TCO, even though it’s “just” an optimisation *could* be officially specified in the future (unlikely). Secondly, TCO is also implementation-specific in other languages such as C++ but it works reliably, and consequently gets used in practice by algorithms implementors. It’s eminently useful in C++." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T03:39:00.727", "Id": "220602", "ParentId": "220600", "Score": "11" } }, { "body": "<p>Since other answers have focused on the code quality itself, I'll focus on performance.</p>\n\n<p>Recursive Fibonacci by itself is <span class=\"math-container\">\\$O(2^n)\\$</span> time.</p>\n\n<p>Memoized fibonacci is linear time (check out <code>functools.lru_cache</code> for a quick and easy one). This is because fibonacci only sees a linear number of inputs, but each one gets seen many times, so caching old input/output pairs helps a lot.</p>\n\n<p>Golden-ratio based solutions are approximately <span class=\"math-container\">\\$O(\\log(n))\\$</span>, using <span class=\"math-container\">\\$\\text{Fib}(n) = \\frac{\\phi^n - (1 - \\phi)^n}{\\sqrt 5}\\$</span>, where <span class=\"math-container\">\\$\\phi\\$</span> is the golden number. Note that without arbitrary precision numbers, this approach becomes inaccurate at large values of n. With increased precision, note that the cost of a multiplication increases as well, making the whole process a bit slower than log(n).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T21:06:44.540", "Id": "426377", "Score": "4", "body": "Since \\$(1 - \\phi) < 0.5\\$ the second term can be ignored. You can just round \\$\\frac{\\phi^n}{\\sqrt 5}\\$ to the nearest integer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T06:29:36.793", "Id": "220608", "ParentId": "220600", "Score": "14" } }, { "body": "<p>If your question is whether the recursive function could be made shorter, then the following is a way to rephrase your function in a more compact form:</p>\n\n<pre><code>def recur_fibonacci(n):\n return n if n &lt;= 1 else recur_fibonacci(n-1) + recur_fibonacci(n-2)\n</code></pre>\n\n<p>This is assuming you must have a recursive solution. As others have already pointed out, the solution could be made more time-efficient by using a simple linear loop instead of recursion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T12:33:59.803", "Id": "426289", "Score": "4", "body": "Welcome to Code Review! Users asking for feedback on their code usually want exactly that, feedback. At the moment, your code is a mere alternative solution. Please at least explain your reasoning. I also invite you to read [How do I write a good answer?](https://codereview.stackexchange.com/help/how-to-answer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T12:51:24.363", "Id": "426296", "Score": "3", "body": "@AlexV: I added some more textual context." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T12:02:58.843", "Id": "220627", "ParentId": "220600", "Score": "2" } }, { "body": "<p>Building on @Snakes and Coffee's answer a bit:</p>\n\n<p>The purpose of the program is to print out the sequence fib(0) to fib(n) - in which case, I would argue that a recursive solution is not the most appropriate.</p>\n\n<p>Currently, when the code goes to calculate fib(5), it starts by calculating the value fib(4) - it actually did this already when it printed out fib(4) in the previous iteration, but this value is not reused and so the work is done again needlessly.</p>\n\n<p>An alternative solution could be to build the list [fib(0), fib(1), fib(2) ... fib(n)]. This is not wasteful as every item in the list is used for calculation, as well as printed out. It also means that once fib(x) has been calculated, the value can be reused for free.</p>\n\n<p>Were the Fibonacci function only being used a handful of times, a recursive solution would make more sense in terms of memory and elegance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:44:11.580", "Id": "426447", "Score": "2", "body": "In terms of implementation, a generator would be appropriate for this use case." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T13:04:03.590", "Id": "220637", "ParentId": "220600", "Score": "6" } }, { "body": "<p>A few people mentioned that your implementation is inefficient. To emphasise just <em>how</em> inefficient it is, try calculating <code>recur_fibonacci(35)</code>, and then <code>recur_fibonacci(40)</code>:</p>\n\n<p>On my computer, the former takes about a second, while the latter takes almost a minute. <code>recur_fibonacci(41)</code> will take more than twice as long.</p>\n\n<p>However, contrary to what some people think <strong>recursion is not the problem here</strong>. Rather, the problem is algorithmic: For every Fibonacci number you calculate, you first calculate <em>all</em> previous Fibonacci numbers, and you do this again for each previous number, without remembering intermediate results.</p>\n\n<p>This can be fixed by maintaining a “memory” of previous results — a process called <em>memoisation</em>. However, an alternative way of calculating Fibonacci numbers doesn’t require memoisation, and instead calculates a pair of adjacent Fibonacci numbers, rather than a single Fibonacci number. By doing this, the function never needs to re-calculate previous terms, it only need to calculate each pair once. This makes the algorithm’s runtime linear.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def fib_pair(n):\n if n &lt; 1: return (0, 1)\n a, b = fib_pair(n - 1)\n return (b, a + b)\n\n\ndef fib(n):\n return fib_pair(n)[0]\n</code></pre>\n\n<p>This runs in microseconds even for large <code>n</code> (although it will at some point overflow the stack).</p>\n\n<p>You might be reluctant to write two functions since you probably never actually need a <em>pair</em> of Fibonacci numbers. A trick is to store this pair as function arguments instead of the return value:<sup>1</sup></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def fib2(n, current = 0, next = 1):\n if n == 0: return current\n return fib2(n - 1, next, current + next)\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup> A nice side-effect of this is that it results in a tail recursive function, which is a desirable property in recursive functions because it is isomorphic to iteration (to the point that some computer scientists call this type of recursion “iteration”), and can be trivially transformed, either via trampolines or by optimising compilers (Python implementations don’t currently do this).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:49:07.927", "Id": "426463", "Score": "2", "body": "I never thought I would see a good way to optimize a recursive fibonacci implementation. Very nice!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T15:06:08.743", "Id": "426706", "Score": "1", "body": "I would suggest splitting pair into a, b. I think it would make it a little nicer to read.\n a, b = fib_pair(n - 1)\n return b, a + b" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T15:16:11.423", "Id": "426715", "Score": "0", "body": "@spyr03 That was my first version and I agree that it’s better but unfortunately pylint doesn’t like it and posting code that fails linting on a review site is a bit questionable. That said, I think we can agree that pylint is wrong here, and even the name `n` fails it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T10:09:36.370", "Id": "220713", "ParentId": "220600", "Score": "4" } }, { "body": "<blockquote>\n <p>So I would like to know whether I could make this program shorter and more efficient.</p>\n</blockquote>\n\n<p>Others have addressed style, but I will address algorithm.</p>\n\n<p>The memoized recursion is a decent solution:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import functools\n\n@functools.lru_cache(maxsize=None)\ndef fib(n):\n if n &lt;= 1:\n return n\n else:\n return fib(n-1) + fib(n-2).\n</code></pre>\n\n<p>This memoization method allows you basically type in the recurrence relation <span class=\"math-container\">\\$F_n = F_{n-1} + F_{n-2}\\$</span> and all of the work of organizing the order of evaluating the functions is automatically done for you.</p>\n\n<p>However, in the case of Fibonacci, you really only need to be storing two values, because you can always use the pair <span class=\"math-container\">\\$(F_{n-1}, F_n)\\$</span> to compute the \"next\" pair <span class=\"math-container\">\\$(F_n, F_{n+1})\\$</span>. For this reason, the following solution works, and is faster than above (fewer function calls). It also has the advantage of never causing stack overflows and using a constant amount of memory.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def fib(n):\n a, b = 0, 1\n for _ in range(n):\n a, b = b, a+b\n return a\n</code></pre>\n\n<p>Now, if you are computing some seriously huge numbers, you can exploit some interesting properties of matrix algebra to get an even faster solution. The basic property that we want to exploit is that\n<span class=\"math-container\">\\$\n\\begin{pmatrix} 1 &amp; 1 \\\\ 1 &amp; 0 \\end{pmatrix}^n\n= \\begin{pmatrix} F_{n+1} &amp; F_n \\\\ F_n &amp; F_{n-1} \\end{pmatrix}.\n\\$</span></p>\n\n<p>Try this out yourself by computing this matrix times itself, times itself, etc. You should see that it boils down to the previous solution. But now we can apply <a href=\"https://en.wikipedia.org/wiki/Exponentiation_by_squaring*\" rel=\"nofollow noreferrer\">exponentiation by squaring</a> (with matrices rather than numbers) to get a faster solution. In particular, if we label \n<span class=\"math-container\">\\$\nA = \\begin{pmatrix}1 &amp; 1 \\\\ 1 &amp; 0\\end{pmatrix}, \n\\$</span></p>\n\n<p>then we known that</p>\n\n<p><span class=\"math-container\">\\$\nA^n = \\begin{cases}\\left(A^{n/2}\\right)^2 &amp;\\text{if n is even}\\\\ A\\left(A^{\\lfloor n/2\\rfloor}\\right)^2 &amp;\\text{if n is odd}\\end{cases}\n\\$</span></p>\n\n<p>This suggests the following implementation:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def matrix_square(a,b,c,d):\n return a*a+b*c, b*(a+d), c*(a+d), d*d+b*c\n\ndef matrix_times_A(a,b,c,d):\n return a+b, a, c+d, c\n\ndef fib_matrix(n):\n if n == 0:\n # identity matrix\n return 1, 0, 0, 1\n half_power = fib_matrix(n//2)\n even_power = matrix_square(*half_power)\n if n % 2 == 1:\n return matrix_times_A(*even_power)\n else:\n return even_power\n\ndef fib(n):\n return fib_matrix(n)[1]\n\n</code></pre>\n\n<p>This is already noticeably faster than the other methods for <code>n=500_000</code>. Plenty of further optimizations can be made here, and I'll leave those as an exercise. You might be able to figure out how to make this iterative rather than recursive.</p>\n\n<p>Even further speed can be gained if you use the \"fast doubling\" recurrence shown \n<a href=\"https://www.nayuki.io/page/fast-fibonacci-algorithms\" rel=\"nofollow noreferrer\">here</a>. That site looks like it also contains some implementations.</p>\n\n<p>The last thing I'd like to add is that if your application does not require exact integer precision, you can use <a href=\"http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html\" rel=\"nofollow noreferrer\">Binet's Formula</a>. In fact, this formula can be derived by diagonalizing the matrix from above (a good exercise if you want to practice some linear algebra). Note that because <span class=\"math-container\">\\$|(1-\\sqrt{5})/2|&lt;1\\$</span>, the second term becomes insignificant, and is unnecessary to compute. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:39:35.023", "Id": "220760", "ParentId": "220600", "Score": "3" } }, { "body": "<p>While memoization can result in impressive performance improvements, it's not really appropriate for this task, when a trivial loop would do what you want</p>\n\n<pre><code>def fib(n):\n res = [0, 1]\n if n &lt; 2:\n return res[0:n]\n for i in range(2, n):\n res.append(res[i - 1] + res[i - 2])\n\n return res\n</code></pre>\n\n<p>But the answers all depend on the problem domain. This is linear and has no memory overhead. The memoised ones have memory overhead but if you're repeatedly generating fibonacci sequences, would eventually have improved performance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:34:37.390", "Id": "220797", "ParentId": "220600", "Score": "1" } } ]
{ "AcceptedAnswerId": "220608", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T03:19:10.253", "Id": "220600", "Score": "10", "Tags": [ "python", "performance", "python-3.x", "fibonacci-sequence" ], "Title": "Python program for fibonacci sequence using a recursive function" }
220600
<p>An assignment at school required me to write a program for this task using Kadane's algorithm (<a href="https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane&#39;s_algorithm" rel="nofollow noreferrer">explained here</a>):</p> <blockquote> <ol> <li>Define the function <code>find_max_subarray</code> that takes a list as an argument and two indices, start and end. It finds the maximum subarray in the range <code>[start, end – 1]</code>.</li> <li>The function <code>find_max_subarray</code> returns the tuple <code>(l, r, m)</code> where <code>l</code> and <code>r</code> are the left and right indices of the maximum subarray and <code>m</code> is its sum.</li> <li>The function uses a loop to keep track of the maximum subarray ending at index <code>i</code>. That is, the maximum subarray that has the element at index <code>i</code> as its last element.</li> <li>Then the maximum subarray will simply be the maximum of all these subarrays.</li> <li>The maximum subarray ending at index <code>i + 1</code> is given by <code>max(list[i]</code> + maximum sum of subarray ending at <code>i, list[i])</code>.</li> <li>The function keeps track of the maximum sum of the subarray seen so far and its left and right indices as the loop iterates.</li> </ol> </blockquote> <p>Here is my solution to this task (using Python):</p> <pre><code>def find_max_subarray(alist, start, end): max_ending_at_i = max_seen_so_far = alist[start] max_left_at_i = max_left_so_far = start max_right_so_far = start + 1 for i in range(start + 1, end): if max_ending_at_i &gt; 0: max_ending_at_i += alist[i] else: max_ending_at_i = alist[i] max_left_at_i = i if max_ending_at_i &gt; max_seen_so_far: max_seen_so_far = max_ending_at_i max_left_so_far = max_left_at_i max_right_so_far = i + 1 return max_left_so_far, max_right_so_far, max_seen_so_far alist = input('Enter the list of numbers: ') alist = alist.split() alist = [int(x) for x in alist] start, end, maximum = find_max_subarray(alist, 0, len(alist)) print('The maximum subarray starts at index {}, ends at index {} and has sum {}.'.format(start, end - 1, maximum)) </code></pre> <p>Here are some example outputs:</p> <pre><code>Enter the list of numbers: 3 -2 4 -6 7 8 -10 4 The maximum subarray starts at index 4, ends at index 5 and has sum 15. Enter the list of numbers: 4 5 -2 0 -5 15 The maximum subarray starts at index 0, ends at index 5 and has sum 17. Enter the list of numbers: 3 The maximum subarray starts at index 0, ends at index 0 and has sum 3. </code></pre> <p>So I would like to know whether I could make this program shorter and more efficient.</p> <p>Any help would be highly appreciated.</p>
[]
[ { "body": "<p>You should always handle edge cases. For instance, if one were to provide an empty list (or <code>None</code>) to your <code>find_max_subarray()</code> function, <code>alist[start]</code> would throw an <code>IndexError</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T16:48:25.710", "Id": "426330", "Score": "0", "body": "Upvoted! Thanks, I will keep this in mind." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T16:44:39.677", "Id": "220648", "ParentId": "220603", "Score": "3" } } ]
{ "AcceptedAnswerId": "220648", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T04:10:05.223", "Id": "220603", "Score": "2", "Tags": [ "python", "performance", "algorithm", "python-3.x", "homework" ], "Title": "Python program to find the subarray with maximum sum" }
220603
<p>I wrote this script to download images from Reddit. I would like to hear from others on how can I improve this script.</p> <pre><code>import requests as _requests import os as _os class Redpy: def __init__(self, user): """Enter a user agent""" print("hello") self.user = user def download(self, subreddit, number=5, sort_option=None): """Downloads images from subreddit. subreddit="Name of subreddit" number=Number of images to be downloaded sort_option=new/hot/top """ subreddit.strip('/') if sort_option == None: sort_option = '' self.url = 'https://www.reddit.com/r/' + subreddit + '/'+ sort_option + '.json' self.user = {'user-agent':self.user} res = _requests.get(self.url, headers=self.user) if res.status_code != 200: print("Could not download") print(res.status_code) return self._DownloadFiles(res.json(), number) def _DownloadFiles(self, jsonfile, number_of_files): image_links = self._getImages(jsonfile, number_of_files) if not self.createFolder(): print("Error creating folder") return index = 0 #used to name the files for image_link in image_links: image_link = image_link.replace('amp;', '') f = _requests.get(image_link) if f.status_code==200: media_file = open(f'{_os.getcwd()}/red_media/{index}.jpg', 'wb') for chunk in f.iter_content(100000): media_file.write(chunk) media_file.close() print("Downloaded") index+=1 print("Download complete") global flag flag=1 def _getImages(self, jsonfile, number_of_files): images = [] #contains links of images for index in range(number_of_files): try: images.append(jsonfile['data']['children'][index]['data']['preview']['images'][0]['source']['url']) except Exception as e: print(e) return images @staticmethod def createFolder(): try: if not _os.path.exists(f'{_os.getcwd()}\\red_media'): _os.mkdir(f'{_os.getcwd()}\\red_media') return True return True except Exception as e: print(e) return False </code></pre> <p>Things I would like to know:</p> <ul> <li>Is there anything that I can do to improve the performance of the code</li> <li>What can I do to improve the code styling. I have tried to follow the PEP standards as much as I could.</li> <li>Anything else to improve the code.</li> </ul>
[]
[ { "body": "<p>A few suggestions for general code quality:</p>\n\n<ul>\n<li>If your class only does one thing and it doesn't store any values, it should be a function. <code>Redpy</code> only downloads images from reddit and stores values to achieve exactly this, which you could do in a function. Using a class can have unforeseen consequences.</li>\n<li>Choose descriptive names for variables and functions. <code>_getImages</code> does not actually get the images, it returns a list of links of images. In this method, you have <code>images = [] #contains links of images</code>. The comment could have been avoided if you would have chosen <code>image_links</code> as name.</li>\n<li>If you split your code up into methods or functions, everything belonging to one task should be inside it. The removal of <code>'amp;'</code> in every <code>image_link</code> does not belong in <code>_DownloadFiles</code>, it should be in <code>_getImages</code>. <code>download</code> gets unnecessarily separated into <code>_DownloadFiles</code> and <code>_DownloadFiles</code> doesn't generally download files, but it could if some of its functionality got relocated elsewhere.</li>\n<li>Clean up your code: there are unnecessary line breaks after <code>_DownloadFiles</code> and a redundant <code>return True</code> in <code>createFolder</code>.</li>\n<li>Don't catch general Exceptions, be more specific. In <code>_getImages</code>, you should just look out for <code>KeyError</code>s. Exceptions in <code>request.get</code> on the other hand are not handled although they possibly should be.</li>\n<li>The pattern of looping over a list with a counter (<code>index</code> in your code) in <code>_DownloadFiles</code> can be simplified with <a href=\"http://book.pythontips.com/en/latest/enumerate.html\" rel=\"noreferrer\">enumerate</a>.</li>\n<li>When working with files, it is more elegant to use a <a href=\"http://book.pythontips.com/en/latest/context_managers.html\" rel=\"noreferrer\">context manager</a>.</li>\n</ul>\n\n<p>Possible bugs:</p>\n\n<ul>\n<li><code>subreddit.strip('/')</code> just returns a new string that you would have to assign to a new variable. In your code, the value of <code>subreddit</code> remains unchanged.</li>\n<li><code>self.user</code> gets updated every time <code>download</code> is called. If this happens multiple times, <code>self.user</code> becomes a dict encapsulating a dict encapsulated a dict...</li>\n<li>If something goes wrong when extracting links in <code>_getImages</code>, less links than expected get returned.</li>\n<li>If your folder already contains images, they will be overwritten.</li>\n</ul>\n\n<p>Concerning PEP8:</p>\n\n<ul>\n<li>A few of your lines are longer than 80 characters. Try to split them up, either by implementing the same logic over multiple lines or by <a href=\"https://stackoverflow.com/questions/53162/how-can-i-do-a-line-break-line-continuation-in-python\">breaking the line up</a>.</li>\n<li>In PEP8, functions and methods are in <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"noreferrer\">snake_case</a>.</li>\n</ul>\n\n<p>Nit-picky stuff:</p>\n\n<ul>\n<li>You could just use an empty string as default argument for <code>sort_option</code>. Strings are immutable, so you don't have the problem of <a href=\"https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments\" rel=\"noreferrer\">mutable default arguments</a>.</li>\n<li>I don't see why you would import <code>requests as _requests</code> and <code>os as _os</code></li>\n<li>There is no need to construct an absolute file path. <code>f'{_os.getcwd()}/red_media/{index}.jpg'</code> could become <code>f'red_media/{index}.jpg'</code></li>\n</ul>\n\n<hr>\n\n<p>Here is my attempt at solving this problem:</p>\n\n<pre><code>import requests\nimport os\n\n\ndef get_image_links(json, N):\n '''returs a list of the first &lt;N&gt; links to reddit images found in &lt;json&gt;'''\n try:\n children = json['data']['children']\n except KeyError:\n return []\n\n # append links from children until N are found\n image_links = []\n for child in children:\n try:\n image_link = child['data']['preview']['images'][0]['source']['url']\n except KeyError:\n continue\n\n image_link = image_link.replace('amp;', '')\n image_links.append(image_link)\n\n if len(image_links)==N:\n break\n\n return image_links\n\ndef download_files(file_links, folder_name='data', file_extension='jpeg'):\n '''downloads files from &lt;file_links&gt; into subfolder ./&lt;folder_name&gt;/'''\n\n # create subfolder if it does not exist\n if not os.path.exists(folder_name):\n os.mkdir(folder_name)\n\n # download files\n for i, file_link in enumerate(file_links):\n try:\n res = requests.get(file_link)\n except requests.exceptions.RequestException:\n print(f\"Unable to download {file_link}\")\n continue\n if not res.ok:\n print(f\"Error {res.status_code} when requesting {file_link}\")\n continue\n\n file_path = os.path.join(folder_name, f'{i}.{file_extension}')\n with open(file_path, 'wb') as file:\n for chunk in res.iter_content(100000):\n file.write(chunk)\n\ndef download_reddit_images(user, subreddit, N=5, sort_by='',\n folder_name='red_media'):\n '''\n downloads the first &lt;N&gt; images of &lt;subreddit&gt; sorted by &lt;sort_by&gt;\n (''/'new'/'hot'/'top') into subfolder ./&lt;folder_name&gt;/\n '''\n\n json_url = ('https://www.reddit.com/r/' + subreddit.strip('/') + '/'\n + sort_by + '.json')\n\n try:\n res = requests.get(json_url, headers={'user-agent':user})\n except requests.exceptions.RequestException:\n print(f\"Unable to get {json_url}\")\n return\n\n if not res.ok:\n print(f\"Error {res.status_code} when requesting {json_url}\")\n return\n\n image_links = get_image_links(res.json(), N)\n if not len(image_links):\n print(\"Unable to find any images\")\n return\n\n download_files(image_links, folder_name=folder_name, file_extension='jpeg')\n\n\nif __name__=='__main__':\n download_reddit_images('', 'all')\n</code></pre>\n\n<p>The problem of overwriting existing images persists. A solution would be to use the original filename from reddit that is included in the url.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:31:01.907", "Id": "426456", "Score": "1", "body": "Thanks a lot for your answer. Your answer was the most comprehensive and detailed analysis of the code. I had updated the code after following some PEP 8 guidelines. Here it is https://github.com/prashantsengar/RedPy ...\nI will update the code again based on your suggestions. \nI have a question though, how can using a class have unforeseen consequences. I want to know more about it. And thanks again for your valuable input" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:28:09.087", "Id": "426530", "Score": "1", "body": "By unforeseen consequences I meant bugs like the one with `self.user`, since you wouldn't expect the code execution to be dependant on previous calls. The problem with using a class here is that it makes the code more complex than it has to be, while a function would work just fine. With the class, it also takes more lines to access the functionality of your code, since you have to create a `Redpy` object and then call `download`, whereas the only thing you gain is not having to enter `user` multiple times. For more information see [this talk](https://youtu.be/o9pEzgHorH0)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T17:38:16.733", "Id": "426542", "Score": "1", "body": "Thanks again for explaining so nicely @reeetooo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T10:03:48.727", "Id": "427078", "Score": "1", "body": "I would probably make a `download_file` function that just downloads a file to a destination and do the iterating over the links directly in `download_reddit_images`. But otherwise a very nice first review, welcome to Code Review!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T21:46:26.097", "Id": "220678", "ParentId": "220610", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T07:01:12.740", "Id": "220610", "Score": "5", "Tags": [ "python", "python-3.x", "reddit" ], "Title": "Script to download images from Reddit" }
220610
<p>An assignment at school required me to write a program for this task:</p> <blockquote> <ol> <li>Create a <code>class</code> and define two methods in the class.</li> <li>Method <code>f1</code> is used to pass an empty list and the sorted list is taken from the user to method <code>f2</code>.</li> <li>Method <code>f2</code> is used to compute all possible subsets of the list.</li> <li>Then the result is returned from the function and printed.</li> <li>Exit</li> </ol> </blockquote> <p>Here is my solution to this task, using Python:</p> <pre><code>class sub: def f1(self, s1): return self.f2([], sorted(s1)) def f2(self, current, s1): if s1: return self.f2(current, s1[1:]) + self.f2(current + [s1[0]], s1[1:]) return [current] a = [] n = int(input("Enter number of elements of list: ")) for i in range(0,n): b = int(input("Enter element: ")) a.append(b) print ("Subsets: ") print (sub().f1(a)) </code></pre> <p>NOTE - Method <code>f2</code> is a recursive function.</p> <p>Here are some example inputs and outputs:</p> <pre><code>Enter number of elements of list: 2 Enter element: 4 Enter element: 5 Subsets: [[], [5], [4], [4, 5]] Enter number of elements of list: 4 Enter element: 3 Enter element: 5 Enter element: 7 Enter element: 28 Subsets: [[], [28], [7], [7, 28], [5], [5, 28], [5, 7], [5, 7, 28], [3], [3, 28], [3, 7], [3, 7, 28], [3, 5], [3, 5, 28], [3, 5, 7], [3, 5, 7, 28] </code></pre> <p>So, I would like to know whether I could make this program shorter and more efficient.</p> <p>Any help would be highly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T08:12:18.303", "Id": "426248", "Score": "0", "body": "Sorry if you've felt passed over when I removed the performance tag. Performance is **not** an issue in your case, this tag is meant for code where the runtime is critical and/or should be reduced." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T08:17:21.317", "Id": "426250", "Score": "0", "body": "@AlexV - Ohh... Now I know. Removed it. Thank you :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T08:26:49.320", "Id": "426251", "Score": "0", "body": "Just so that you've heard about it: There is a [tag wiki](https://codereview.stackexchange.com/tags/performance/info) for each tag (I guess - have not checked them all) describing precisely what the tag is about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T10:11:57.737", "Id": "434697", "Score": "0", "body": "Never do this in production code. A function is [more than sufficient](https://stackoverflow.com/q/1482308/1394393). OOP is just clutter for generating a power set. Be aware that whatever you got this from is teaching you un-Pythonic patterns and going against the normal idioms of the language." } ]
[ { "body": "<p><code>I.</code> This chunk of code:</p>\n\n<pre><code>a = []\nn = int(input(\"Enter number of elements of list: \"))\nfor i in range(0,n):\n b = int(input(\"Enter element: \"))\n a.append(b)\n</code></pre>\n\n<p>is mostly C-like (or Pascal-like etc). You can replace it with more Pythonic:</p>\n\n<p><code>a = input('Enter elements splitted by \":\" ').split(' ')</code></p>\n\n<p><code>II.</code> Here:</p>\n\n<p><code>print (sub().f1(a))</code></p>\n\n<p>You are creating a <code>sub</code> instance within the <code>print</code> function. It is a bad idea because it will disappear after print. You should create it before you print something (and, yes, classes names in Python are in CamelCase):</p>\n\n<pre><code>waka = Sub()\nprint(waka.f1(a))\n</code></pre>\n\n<p><code>III.</code> I prefer to create <code>__init__()</code> function each time I create a class. It is not really necessary but in most cases, it is the first one is creating in the new class:</p>\n\n<pre><code>class Sub(object):\n def __init__(self):\n pass\n</code></pre>\n\n<p><code>IV.</code> If it is your homework you should do with recursion, the code is pretty OK. In another case, I recommend you to use Python <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\">itertools</a> module (you should avoid recursion as much as possible):</p>\n\n<pre><code> def f2(self, current, s1): \n return [\n e\n for e in itertools.chain.from_iterable([\n [sorted(l) for l in itertools.combinations(s1, length)]\n for length in range(1, len(s1))\n ])\n ]\n</code></pre>\n\n<p>So here is the result code for recursion version:</p>\n\n<pre><code>class Sub(object):\n def __init__(self):\n pass\n\n def f1(self, s1): \n return self.f2([], sorted(s1)) \n\n def f2(self, current, s1): \n if s1: \n return self.f2(current, s1[1:]) + self.f2(current + [s1[0]], s1[1:]) \n return [current]\n\na = input('Enter elements splitted by \" \": ').split(' ')\nwaka = Sub()\nprint(waka.f1(a))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T15:30:51.993", "Id": "426323", "Score": "0", "body": "Upvoted! Thanks for the very detailed response! Some really good stuff in here!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T21:54:10.467", "Id": "426381", "Score": "0", "body": "I don't think the outer `[]` are needed within the `chain.from_iterable`, and `list(...)` instrad of `[e for e in... ]`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T15:25:14.450", "Id": "220645", "ParentId": "220612", "Score": "3" } } ]
{ "AcceptedAnswerId": "220645", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T07:42:20.270", "Id": "220612", "Score": "3", "Tags": [ "python", "python-3.x", "object-oriented", "homework" ], "Title": "Get all possible subsets from a set of distinct integers using OOP" }
220612
<p>The most basic code(i guess so) to find all the factors of a number</p> <p>Note:factors include 1 and the number itself</p> <p>Here's the code:</p> <pre><code>c=0 x=int(input("Enter number:")) for i in range(1,x+1): if x%i==0: print("factor",c+1,":",i) c=c+1 print("Total number of factors:",c) </code></pre> <p>Please make this code efficient.....ie: Help to reduce the number of iterations</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T07:20:16.600", "Id": "426419", "Score": "2", "body": "What range of numbers are you interested in? The best approach for `x` on the order of \\$10^{8}\\$ is not the same as the best approach for `x` on the order of \\$10^{80}\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T09:44:28.190", "Id": "426645", "Score": "0", "body": "i may need like 10^40s to 10^60s" } ]
[ { "body": "<p>Divisors come in pairs. Since 2*50 = 100, both 2 and 50 are divisors to 100. You don't need to search for both of these, because once you've found that 100 is divisible by 2, you can do 100 / 2 to find 50, which is the other divisor. So for every divisor you find, use division to find its \"partner\" at the same time. That way you don't need to look further than the square root of x:</p>\n\n<pre><code>for i in range(1, int(math.sqrt(x)) + 1):\n if x % i == 0:\n divisor1 = i\n divisor2 = x // i\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T08:44:33.150", "Id": "426424", "Score": "0", "body": "If you are really very concerned about speed, since you only need the sqrt to define a limit, you could use a faster, more approximate sqrt method. As long as it convergences from above the true sqrt, you won't go below the limit (and maybe miss a divisor)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T10:35:15.187", "Id": "426434", "Score": "0", "body": "The sqrt method is only called once though. There's not a lot of time to save there. @HoboProber" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:52:39.857", "Id": "426508", "Score": "0", "body": "So we need sqrt(n)+1?...won't this contain all the divisors....of course this one reduced my time by half....so far so good...is it possible to reduce further?...like suppose 100...the factor 50 has 2,5 already in it right....so with that we can say 10 is a factor...is it possible to implement such logic in our code?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:25:15.687", "Id": "220617", "ParentId": "220614", "Score": "3" } }, { "body": "<p>Just to have a more readable (than the <a href=\"https://codereview.stackexchange.com/a/220618/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/195671/justin\">@Justin</a>) and complete (than the <a href=\"https://codereview.stackexchange.com/a/220617/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/201168/sedsarq\">@Sedsarq</a>) version of the algorithm presented in the other answers, here is a version that keeps the factors in a <code>set</code> and uses the fact that factors always come in pairs:</p>\n\n<pre><code>from math import sqrt\n\ndef get_factors(n):\n \"\"\"Returns a sorted list of all unique factors of `n`.\"\"\"\n factors = set()\n for i in range(1, int(sqrt(n)) + 1):\n if n % i == 0:\n factors.update([i, n // i])\n return sorted(factors)\n</code></pre>\n\n<p>Compared to your code this has the added advantage that it is encapsulated in a function, so you can call it repeatedly and give it a clear name and docstring describing what the function does.</p>\n\n<p>It also follows Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which programmers are encouraged to follow.</p>\n\n<p>With regards to which code is fastest, I'll let this graph speak for itself:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aVney.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aVney.png\" alt=\"enter image description here\"></a></p>\n\n<p>For the <code>op</code> function I used this code which has your checking of all factors up to <code>x</code>:</p>\n\n<pre><code>def op(x):\n factors = []\n for i in range(1,x+1):\n if x%i==0:\n factors.append(i)\n return factors\n</code></pre>\n\n<p>And the <code>factors</code> function is from the <a href=\"https://codereview.stackexchange.com/a/220618/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/195671/justin\">@Justin</a>.</p>\n\n<hr>\n\n<p>If all you really want is the number of factors, the best way is probably to use the prime factor decomposition. For this you can use a list of primes together with the algorithm in the <a href=\"https://codereview.stackexchange.com/a/220727/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/9452/josay\">@Josay</a>:</p>\n\n<pre><code>from math import sqrt\nfrom functools import reduce\nfrom operators import mul\n\ndef prime_sieve(limit):\n prime = [True] * limit\n prime[0] = prime[1] = False\n\n for i, is_prime in enumerate(prime):\n if is_prime:\n yield i\n for n in range(i * i, limit, i):\n prime[n] = False\n\ndef prime_factors(n):\n primes = prime_sieve(int(sqrt(n) + 1))\n for p in primes:\n c = 0\n while n % p == 0:\n n //= p\n c += 1\n if c &gt; 0:\n yield p, c\n if n &gt; 1:\n yield n, 1\n\ndef prod(x):\n return reduce(mul, x)\n\ndef number_of_factors(n)\n return prod(c + 1 for _, c in prime_factors(n))\n</code></pre>\n\n<p>Comparing this with just taking the <code>len</code> of the output of the <code>get_factors</code> function and this function which implements your algorithm as <code>op_count</code>:</p>\n\n<pre><code>def len_get_factors(n):\n return len(get_factors(n))\n\ndef op_count(n):\n c = 0\n for i in range(1, n + 1):\n if n % i == 0:\n c = c + 1\n return c\n</code></pre>\n\n<p>The following timings result (note the increased range compared to the previous plot):</p>\n\n<p><a href=\"https://i.stack.imgur.com/YaTnu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YaTnu.png\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T13:59:45.800", "Id": "426305", "Score": "0", "body": "But doesn't it depend on the workability of the solutions too? The code you provided for the op function doesn't give the right answer for factors of `30` - `[30, 30, 30, 30, 30, 30, 30, 30]` and Sedsarq's answer only gives two factors - `(5, 6)`, meanwhile both of our answer's give the right solution - `[1, 2, 3, 5, 6, 10, 15, 30]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:03:59.767", "Id": "426308", "Score": "0", "body": "@Justin Well, it does emulate the behavior in the OP, which just prints the factor instead of saving it in a list. So what you are actually saying is the code provided in the question is not working (which would make it off-topic)? I did not include any code from sedsarq's answer because it is not complete enough, as you say." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:06:03.613", "Id": "426309", "Score": "0", "body": "@Justin Nevermind, my `op` function gave the wrong answer for all numbers, because I saved `x` and not `i`... This should not change the runtime, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:38:49.620", "Id": "426406", "Score": "0", "body": "The code I shared was not intended as a full solution, but simply to clarify the text. My answer just aimed to present an idea to use for improvement (and that idea is also used by the other solutions given here). @Justin" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:56:26.607", "Id": "426509", "Score": "0", "body": "Thanks buddy...I want to make it more concise though...I'm greedy....suppose consider 100......50 is one of its factor....but 50 already contains 2 and 5 so we can say 10 is also a factor...this logic will reduce the runtime much more...but how to implement this?..any ideas?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:19:24.963", "Id": "426517", "Score": "0", "body": "@THEEPICGUY For this you would need to start at the number itself and go down (otherwise you would already have found both 2 and 5 before getting to 50). It would also mean you have to check every number as well as factorize every number, since you might otherwise miss a prime factor. Factorizing is a lot harder than finding out if the number divides `n`, as you should know since that is the problem you are solving. This would also probably be a recursive solution, which are usually not the best solutions in Python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:22:38.197", "Id": "426521", "Score": "0", "body": "@THEEPICGUY Where you can gain is if you only care about the prime factors. Then you just take a list of all prime factors below `sqrt(n) + 1` and try them all. This is a lot more efficient than trying every number below the sqrt bound, obviously, by at least a factor two (there is only one even prime, 2)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T09:30:03.847", "Id": "426641", "Score": "0", "body": "@Graipher The problem of \"sqrt(n) + 1\" is that suppose consider the number 666(lol just for fun)....the \"sqrt(666) + 1\" is 26.8 so if we find all the factors of 26.8...We are missing the number '37' which is also a factor of 666 (37*18) so this method is wrong and pointless...any better methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T09:44:34.567", "Id": "426646", "Score": "0", "body": "@THEEPICGUY See the answer by Josay, which basically implements this. They also stop at sqrt(x). They could use a list of primes instead of trying every `d`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T09:50:55.750", "Id": "426647", "Score": "0", "body": "@Graipher Yet it doesn't give all the factors of the given number!! Even he is wrong...the sqrt(n)+1 is can only be used to check whether a number is prime or not....it can't be used to give all the factors of the given number :( ...But decompostion to primes seems like a nice idea...yet i can't find a way to implement...i'm trying though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T09:52:24.257", "Id": "426649", "Score": "0", "body": "@THEEPICGUY It is possible to get the number of factors from the prime factor decomposition (see comment under their answer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T10:05:57.123", "Id": "426651", "Score": "0", "body": "@THEEPICGUY See updated answer. I verified that the algorithm does get the prime factors of 666 correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T12:43:09.577", "Id": "426895", "Score": "0", "body": "@Graipher....yes your updated prime decomposition is epic...but can u use an explicit for loop instead of the reduce function (cause the function is currently deprecated) and it slows the algorithm.... Yeah....but this is actually the solution I needed....thanks though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T12:48:56.637", "Id": "426896", "Score": "0", "body": "@THEEPICGUY While the Python 2 built-in `reduce` was deprecated and removed in Python 3, using `functools.reduce` is fine, if needed. IMO the `prod` function is the one and only place where it is still widely used and it is justified there. If your really need to, just change it to a `for` loop in your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T13:01:55.330", "Id": "426899", "Score": "0", "body": "Can u add one more feature....checks josay's replies....I specified I needed that extra feature...that may make my code even faster...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T13:39:18.060", "Id": "426912", "Score": "0", "body": "@THEEPICGUY I don't understand what you mean. I already only use the primes needed. If you have a pre-existing list of primes (guarenteed to be large enough), just use `itertools.takewhile(lambda n: n < limit, primes)` to restrict it to the ones you need." } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T12:17:34.843", "Id": "220632", "ParentId": "220614", "Score": "6" } }, { "body": "<p>All answers provided are great and offer suggestions with a complexity in <code>O(sqrt(n))</code> instead of the original <code>O(n)</code> by using the trick to stop at <code>sqrt(n)</code>.</p>\n\n<p>On big inputs, we can go for an even faster solution by using the decomposition in prime numbers:</p>\n\n<ul>\n<li><p>the decomposition in prime numbers can be computed in a time proportional to the square root of the biggest prime divisor if its multiplicity is one (the actually complexity is actually a bit more tricky than this)</p></li>\n<li><p>the decomposition can be reused to generate all possible divisors (for each prime <code>p</code> with multiplicity <code>n</code>, you take <code>p ^ m</code> with <code>0 &lt;= m &lt;= n</code>.</p></li>\n</ul>\n\n<p>I can provide the following piece of code for the first task but I do not have a snippet for the second task (yet?)</p>\n\n<pre><code>def prime_factors(n):\n \"\"\"Yields prime factors of a positive number.\"\"\"\n assert n &gt; 0\n d = 2\n while d * d &lt;= n:\n while n % d == 0:\n n //= d\n yield d\n d += 1\n if n &gt; 1: # to avoid 1 as a factor\n assert d &lt;= n\nyield n\n</code></pre>\n\n<p>Edit: I tried to implement the second step and got something which is not highly tested but seems to work:</p>\n\n<pre><code>def mult(iterable, start=1):\n \"\"\"Returns the product of an iterable - like the sum builtin.\"\"\"\n return functools.reduce(operator.mul, iterable, start)\n\n\ndef yield_divisors(n):\n \"\"\"Yields distinct divisors of n.\"\"\"\n elements = [[p**power for power in range(c + 1)] for p, c in collections.Counter(prime_factors(n)).items()]\n return [mult(it) for it in itertools.product(*elements)]\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:46:30.157", "Id": "426505", "Score": "0", "body": "This sounds interesting...but suppose if a number can be broken into p^x *q^y...where p and q are primes then number of factors are just permutation of x and y....but how do we permute them? Any ideas?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:49:07.873", "Id": "426506", "Score": "1", "body": "I guess the itertools module can be very useful here. Maybe itertools.product..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T09:51:04.953", "Id": "426648", "Score": "0", "body": "@Josay You don't even need the permutations, you just need to count how often each prime occurs: https://www.quora.com/What-is-the-relationship-between-prime-factors-and-total-number-of-factors-of-a-number" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T11:33:12.893", "Id": "426657", "Score": "0", "body": "@Graipher To get the number of factors, this is indeed much easier. You can use nb_divisors from my code in https://github.com/SylvainDe/ProjectEulerPython/blob/master/prime.py . Getting the different divisors is slightly more complicated" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T15:24:37.593", "Id": "426718", "Score": "0", "body": "@Graipher I've also implemented the generation of the different divisors, you can have a look at my updated answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T12:33:34.970", "Id": "426889", "Score": "0", "body": "Wow...this is much faster...great algorithm.... Yet can you make a small change (I tried and I couldn't do it)...like....already there are some 100 first primes stored in the list which I'll use rather than generating each time...but if the prime factors exceed the list then I'll use the function to give some more primes and append in the list.... Can u try this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T16:45:58.593", "Id": "426981", "Score": "0", "body": "@THEEPICGUY I think would make a much more complicated implementation... I am not sure I want to go that way." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:00:28.277", "Id": "220727", "ParentId": "220614", "Score": "3" } }, { "body": "<p>Since you say in a comment that you may need to find the divisors of a number <span class=\"math-container\">\\$n\\$</span> up to <span class=\"math-container\">\\$10^{60}\\$</span>, trial division is not practical, even if performed only up to <span class=\"math-container\">\\$\\sqrt n\\$</span> . The only option is to find the prime factorisation and then reconstruct the divisors from the prime factorisation.</p>\n\n<p>There are quite a few <a href=\"https://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms\" rel=\"nofollow noreferrer\">algorithms to find the prime factorisation</a>. For the size of numbers that interest you, the <a href=\"https://en.wikipedia.org/wiki/Quadratic_sieve\" rel=\"nofollow noreferrer\">quadratic sieve</a> is probably the best option.</p>\n\n<p>Given the prime factorisation, reconstruction of the divisors is just a matter of taking some Cartesian products. Generating them in order is slightly trickier: I reproduce here some code which I wrote for an earlier answer to a similar question. It assumes that <code>primeFactors</code> gives output in the form <code>[(prime, power) ...]</code> in ascending order of primes.</p>\n\n<pre><code>import heapq\n\ndef divisors(n):\n primes = [(1, 1)] + list(primeFactors(n))\n q = [(1, 0, 1)]\n while len(q) &gt; 0:\n # d is the divisor\n # i is the index of its largest \"prime\" in primes\n # a is the exponent of that \"prime\"\n (d, i, a) = heapq.heappop(q)\n yield d\n if a &lt; primes[i][1]:\n heapq.heappush(q, (d * primes[i][0], i, a + 1))\n if i + 1 &lt; len(primes):\n heapq.heappush(q, (d * primes[i + 1][0], i + 1, 1))\n # The condition i &gt; 0 is to avoid duplicates arising because\n # d == d // primes[0][0]\n if i &gt; 0 and a == 1:\n heapq.heappush(q, (d // primes[i][0] * primes[i + 1][0], i + 1, 1))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T12:31:45.170", "Id": "426888", "Score": "0", "body": "Yeah...this is what I wanted...but can u simplify without using heapq...(idk what it does...and I don't want to use unnecessary functions).... I kinda found the code till I get the prime factors and their respective powers and stored them in separate lists...now I just need the code for Cartesian product...ie:permuting the powers of the primes....can u help me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T13:05:35.117", "Id": "426903", "Score": "1", "body": "This site is code *review*, not a code writing service. Supplying improved code is already going above and beyond expectations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T16:58:33.033", "Id": "426984", "Score": "0", "body": "lol...agreed...anyways...thanks for informing...i just joined stack overflow recently..my bad" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T10:25:14.437", "Id": "220813", "ParentId": "220614", "Score": "1" } } ]
{ "AcceptedAnswerId": "220632", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T08:54:20.583", "Id": "220614", "Score": "4", "Tags": [ "python", "performance", "algorithm", "python-3.x" ], "Title": "Find all the factors of a given number" }
220614
<p>After doing the Snake Game I decided to go more crazy and made an Arkanoid Clone:</p> <p><a href="https://i.stack.imgur.com/7u1mk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7u1mk.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/mRlkP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mRlkP.png" alt="enter image description here"></a></p> <p>Currently this only runs on Windows. I tested it under MSVC2017 with Windows 7. If you want to get it to run on Linux or Mac you have to implement the Part in <code>Console.cpp</code>.</p> <p>I organized the code as following:</p> <ul> <li><p><strong>GameObject</strong>: This class is the base for all objects in the game. It handles all the movements and also collisions between two <code>GameObjects</code>.</p></li> <li><p><strong>Platform</strong>: Derived from <code>GameObject</code>. The only thing new here is that it can be reset to the init position. Used when a level is restarted.</p></li> <li><p><strong>Wall</strong>: Derived from <code>GameObject</code>. Not moveable. Can be passed to <code>Ball</code> or <code>Platform</code> to handle collisions between each other</p></li> <li><p><strong>Ball</strong>: Derived from <code>GameObject</code>. Can be deactivated so it does not move. This is used before the user hits spacebar to start the game. The move routine is override to add a gravity force on the <code>Ball</code></p></li> <li><p><strong>Brick</strong>: Derived from <code>GameObject</code>. Not moveable. Has hitpoints and can be flaged destroyed. This is used to not have the need to delete the Brick from the field it just becomes invisible. The init hitpoints are stored as well to be used for different scorings</p></li> <li><p><strong>Level</strong>: Handles everything which happens in one played Level. It can take a collection of Bricks to load different levels.</p></li> <li><p><strong>Game</strong>: This routine calls the different levels and announces Game Over if it occurs</p></li> <li><p><strong>Grid</strong>: Used to display on the console. In the Background everything like Positions of the ball gets calculated with floating point operations. Since the console has very big pixels we only show whole sizes so 10.5 becomes 10 etc.</p></li> <li><p><strong>Console</strong>: Currently only supporting Windows. Commands to manipulate the console and check for keys pressed</p></li> <li><p><strong>MathHelper</strong>: Some defines and functions to convert from degree to radient. For readability in the GameObject calculations and debug purposes.</p></li> <li><p><strong>Time</strong>: Handles the recording of the passed time between two points for the calculations of the movements and also provides a wait function.</p></li> <li><p><strong>NearlyEqual</strong>: Function to compare double equal with delta similar to ints.</p></li> </ul> <p>Let me know what can be improved. I want to add more features but first i want to know how is the state of the current code.</p> <p>Some questions which maybe help to review</p> <ul> <li>Is it well organized?</li> <li>Would you have organized it different?</li> <li>How about the math of the collisions. Can it be improved?</li> <li>Are there any bad practices?</li> <li>Is stuff done to complicated</li> <li>Can you understand the code or is it hard to read through it?</li> </ul> <p>Let me know. If you not have the time to read all pick a part and let me know what you think of it.</p> <p>The Code:</p> <p><strong>main.cpp</strong></p> <pre><code>#include "Game.h" #include &lt;iostream&gt; int main() try { while (arkanoid::runGame()); } catch (const std::out_of_range&amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; "\n"; std::cin.get(); } catch (const std::invalid_argument&amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; "\n"; std::cin.get(); } catch (...) { std::cerr &lt;&lt; "unknown error " &lt;&lt; "\n"; std::cin.get(); } </code></pre> <p><strong>Game.h</strong></p> <pre><code>#ifndef GAME_H #define GAME_H namespace arkanoid { bool runGame(); bool userInputGameOver(long long score); } #endif </code></pre> <p><strong>Game.cpp</strong></p> <pre><code>#include "Game.h" #include "Console.h" #include "Level.h" #include &lt;iostream&gt; namespace arkanoid { bool runGame() { console::resize(500, 453); static constexpr auto startScore = 0; static constexpr auto startLives = 3; long long score = startScore; int lives = startLives; int level{ 0 }; for (;;) { Level level1{ score, lives, ++level, makeBricksLevel1() }; level1.run(); score = level1.score(); lives = level1.lives(); if (level1.isGameOver()) { return userInputGameOver(score); } Level level2{ level1.score(), level1.lives(), ++level, makeBricksLevel2() }; level2.run(); score = level1.score(); lives = level1.lives(); if (level2.isGameOver()) { return userInputGameOver(score); } } } bool userInputGameOver(long long score) { console::clearScreen(); std::cout &lt;&lt; "Game Over!!!\n" &lt;&lt; "SCORE:" &lt;&lt; score&lt;&lt;'\n' &lt;&lt; "Press R To Try again or ESC to Quit\n"; for (;;) { if (console::rKeyHoldDown()) { return true; } if (console::escKeyHoldDown()) { return false; } } console::clearScreen(); } } // namespace arkanoid </code></pre> <p><strong>Level.h</strong></p> <pre><code>#ifndef LEVEL_H #define LEVEL_H #include "Ball.h" #include "Brick.h" #include "Platform.h" #include "Wall.h" #include &lt;vector&gt; namespace arkanoid { class Wall; class Brick; class Platform; class Level { public: Level(long long score, int lives, int level, std::vector&lt;Brick&gt; bricks); ~Level() = default; void run(); long long score() const; int lives() const; bool isGameOver() const; private: void handleBallMovementsAndCollisions(double elapsedTimeInMS); void printToConsole(); Platform makePlatform(); Ball makeBall(); static constexpr int boardWidth{ 26 }; static constexpr int boardHeight{ 18 }; static constexpr auto plattformWidth{ 5.0 }; static constexpr auto wallThickness{ 1.0 }; static constexpr auto pointsPerBrick{ 100 }; long long mScore; int mLives; const int mLevel; std::vector&lt;Brick&gt; mBricks; const Wall mLeftWall; const Wall mRightWall; const Wall mTopWall; Platform mPlatform; Ball mBall; bool mIsGameOver; }; void movePlatformBetweenWalls( Platform&amp; platform, const Wall&amp; leftWall, const Wall&amp; rightWall, double elapsedTimeInMS); Point calculatePlattformInitPosition( double plattformSize, double boardWidth, double boardHeight); Point calculateBallInitPosition(double boardWidth, double boardHeight); bool allBricksAreDestroyed(const std::vector&lt;Brick&gt;&amp; bricks); std::vector&lt;Brick&gt; makeBricksLevel1(); std::vector&lt;Brick&gt; makeBricksLevel2(); } // namespace arkanoid #endif </code></pre> <p><strong>Level.cpp</strong></p> <pre><code>#include "Level.h" #include "Console.h" #include "Grid.h" #include "Time.h" #include &lt;algorithm&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; namespace arkanoid { Level::Level(long long score, int lives, int level, const std::vector&lt;Brick&gt; bricks) : mScore{score}, mLives{lives}, mLevel{level}, mBricks{bricks}, mLeftWall{ Point{0,0}, wallThickness, boardHeight }, mRightWall{ Point{boardWidth - wallThickness, 0}, wallThickness, boardHeight }, mTopWall{ Point{wallThickness, 0}, boardWidth - 2.0 * wallThickness, wallThickness }, mPlatform{makePlatform()}, mBall{makeBall()}, mIsGameOver{false} { } void Level::run() { std::chrono::time_point&lt;std::chrono::high_resolution_clock&gt; t1; std::chrono::time_point&lt;std::chrono::high_resolution_clock&gt; t2; double elapsedTimeInMS{ 0.0 }; for (;;) { t1 = getCurrentTime(); if (!mBall.isActive() &amp;&amp; console::spaceKeyHoldDown()) { mBall.activate(); } movePlatformBetweenWalls( mPlatform, mLeftWall, mRightWall, elapsedTimeInMS); if (mBall.isActive()) { handleBallMovementsAndCollisions(elapsedTimeInMS); } if (allBricksAreDestroyed(mBricks)) { return; } if (mIsGameOver) { return; } printToConsole(); t2 = getCurrentTime(); elapsedTimeInMS = arkanoid::getElapsedTime(t1, t2); } } long long Level::score() const { return mScore; } int Level::lives() const { return mLives; } bool Level::isGameOver() const { return mIsGameOver; } void Level::handleBallMovementsAndCollisions(double elapsedTimeInMS) { if (mBall.reflectIfHit(mRightWall)) { ; } else if (mBall.reflectIfHit(mLeftWall)) { ; } else if (mBall.reflectIfHit(mTopWall)) { ; } else if (mBall.reflectIfHit(mPlatform)) { ; } else if (mBall.bottomRight().y &gt;= boardHeight) { wait(std::chrono::milliseconds{ 1000 }); --mLives; if (mLives == 0) { mIsGameOver = true; } mBall.deactivate(); mPlatform.setToInitPosition(); return; } for (auto&amp; brick : mBricks) { if (brick.isDestroyed()) { continue; } if (mBall.reflectIfHit(brick)) { brick.decreaseHitpoints(); if (brick.isDestroyed()) { mScore += pointsPerBrick * brick.startHitpoints(); } break; } } mBall.move(elapsedTimeInMS); } void Level::printToConsole() { console::putCursorToStartOfConsole(); Grid grid( static_cast&lt;int&gt;(boardWidth), static_cast&lt;int&gt;(boardHeight) ); grid.add(mBall); grid.add(mPlatform); grid.add(mLeftWall); grid.add(mRightWall); grid.add(mTopWall); for (const auto&amp; brick : mBricks) { grid.add(brick); } console::putCursorToStartOfConsole(); std::cout &lt;&lt; "Score:" &lt;&lt; std::setw(15) &lt;&lt; mScore &lt;&lt; " " &lt;&lt; "Lives:" &lt;&lt; std::setw(4) &lt;&lt; mLives &lt;&lt; " " &lt;&lt; "Level:" &lt;&lt; std::setw(4) &lt;&lt; mLevel &lt;&lt; '\n' &lt;&lt; grid &lt;&lt; '\n'; //std::cout &lt;&lt; std::setw(5) &lt;&lt; mBall.topLeft().x &lt;&lt; " " // &lt;&lt; std::setw(5) &lt;&lt; mBall.topLeft().y &lt;&lt; " " // &lt;&lt; std::setw(10) &lt;&lt; radientToDegrees(mBall.angle()) // &lt;&lt; std::setw(10) &lt;&lt; radientToDegrees(mBall.quadrantAngle()) // &lt;&lt; std::setw(3) &lt;&lt; static_cast&lt;int&gt;(mBall.quadrant()) + 1 &lt;&lt; '\n'; //std::cout &lt;&lt; std::setw(5) &lt;&lt; mPlatform.topLeft().x &lt;&lt; " " // &lt;&lt; std::setw(5) &lt;&lt; mPlatform.topLeft().y &lt;&lt; " " // &lt;&lt; std::setw(10) &lt;&lt; radientToDegrees(mPlatform.angle()) // &lt;&lt; std::setw(10) &lt;&lt; radientToDegrees(mPlatform.quadrantAngle()) // &lt;&lt; std::setw(3) &lt;&lt; static_cast&lt;int&gt;(mPlatform.quadrant()) + 1 &lt;&lt; '\n'; } Platform Level::makePlatform() { return Platform{ calculatePlattformInitPosition( plattformWidth, boardWidth, boardHeight), static_cast&lt;double&gt;(boardWidth), plattformWidth, }; } Ball Level::makeBall() { return Ball{ calculateBallInitPosition(boardWidth, boardHeight), static_cast&lt;double&gt;(boardWidth), static_cast&lt;double&gt;(boardHeight) }; } void movePlatformBetweenWalls( Platform&amp; platform, const Wall&amp; leftWall, const Wall&amp; rightWall, double elapsedTimeInMS) { if (console::rightKeyHoldDown()) { platform.setAngle(0.0); platform.move(elapsedTimeInMS); } else if (console::leftKeyHoldDown()) { platform.setAngle(deg_180); platform.move(elapsedTimeInMS); } if (platform.reflectIfHit(rightWall)) { ; } else if (platform.reflectIfHit(leftWall)) { ; } } Point calculatePlattformInitPosition( double plattformSize, double boardWidth, double boardHeight) { return Point{ boardWidth / 2.0 - plattformSize / 2.0, boardHeight - 3.0 }; } Point calculateBallInitPosition(double boardWidth, double boardHeight) { return Point{ boardWidth / 2.0 - 1, boardHeight - 4.0 }; } bool allBricksAreDestroyed(const std::vector&lt;Brick&gt;&amp; bricks) { return std::find_if(bricks.begin(), bricks.end(), [](const Brick&amp; b) { return !b.isDestroyed(); }) == bricks.end(); } std::vector&lt;Brick&gt; makeBricksLevel1() { constexpr auto brickLength = 3.0; constexpr auto brickHeight = 1.0; return std::vector&lt;Brick&gt; { Brick{ Point{4,2},brickLength,brickHeight,1 }, Brick{ Point{7,2},brickLength,brickHeight,1 }, Brick{ Point{10,2},brickLength,brickHeight,1 }, Brick{ Point{13,2},brickLength,brickHeight,1 }, Brick{ Point{16,2},brickLength,brickHeight,1 }, Brick{ Point{19,2},brickLength,brickHeight,1 }, Brick{ Point{4,3},brickLength,brickHeight,1 }, Brick{ Point{19,3},brickLength,brickHeight,1 }, Brick{ Point{4,4},brickLength,brickHeight,1 }, Brick{ Point{10,4},brickLength,brickHeight,2 }, Brick{ Point{13,4},brickLength,brickHeight,2 }, Brick{ Point{19,4},brickLength,brickHeight,1 }, Brick{ Point{4,5},brickLength,brickHeight,1 }, Brick{ Point{19,5},brickLength,brickHeight,1 }, Brick{ Point{4,6},brickLength,brickHeight,1 }, Brick{ Point{7,6},brickLength,brickHeight,1 }, Brick{ Point{10,6},brickLength,brickHeight,1 }, Brick{ Point{13,6},brickLength,brickHeight,1 }, Brick{ Point{16,6},brickLength,brickHeight,1 }, Brick{ Point{19,6},brickLength,brickHeight,1 }, }; } std::vector&lt;Brick&gt; makeBricksLevel2() { constexpr auto brickLength = 3.0; constexpr auto brickHeight = 1.0; return std::vector&lt;Brick&gt; { // draw a C Brick{ Point{4,2},brickLength,brickHeight,1 }, Brick{ Point{7,2},brickLength,brickHeight,1 }, Brick{ Point{10,2},brickLength,brickHeight,1 }, Brick{ Point{13,2},brickLength,brickHeight,1 }, Brick{ Point{4,3},brickLength,brickHeight,1 }, Brick{ Point{4,4},brickLength,brickHeight,1 }, Brick{ Point{4,5},brickLength,brickHeight,1 }, Brick{ Point{4,6},brickLength,brickHeight,1 }, Brick{ Point{4,7},brickLength,brickHeight,1 }, Brick{ Point{4,8},brickLength,brickHeight,1 }, Brick{ Point{4,9},brickLength,brickHeight,1 }, Brick{ Point{4,10},brickLength,brickHeight,1 }, Brick{ Point{7,10},brickLength,brickHeight,1 }, Brick{ Point{10,10},brickLength,brickHeight,1 }, Brick{ Point{13,10},brickLength,brickHeight,1 }, // draw first + Brick{ Point{13,6},brickHeight,brickHeight,2 }, Brick{ Point{14,6},brickHeight,brickHeight,3 }, Brick{ Point{15,4},brickHeight,brickHeight,2 }, Brick{ Point{15,5},brickHeight,brickHeight,3 }, Brick{ Point{15,6},brickHeight,brickHeight,4 }, Brick{ Point{15,7},brickHeight,brickHeight,3 }, Brick{ Point{15,8},brickHeight,brickHeight,2 }, Brick{ Point{16,6},brickHeight,brickHeight,3 }, Brick{ Point{17,6},brickHeight,brickHeight,2 }, // draw second + Brick{ Point{19,6},brickHeight,brickHeight,5 }, Brick{ Point{20,6},brickHeight,brickHeight,6 }, Brick{ Point{21,4},brickHeight,brickHeight,5 }, Brick{ Point{21,5},brickHeight,brickHeight,3 }, Brick{ Point{21,6},brickHeight,brickHeight,7 }, Brick{ Point{21,7},brickHeight,brickHeight,6 }, Brick{ Point{21,8},brickHeight,brickHeight,5 }, Brick{ Point{22,6},brickHeight,brickHeight,6 }, Brick{ Point{23,6},brickHeight,brickHeight,5 }, }; } } // namespace arkanoid </code></pre> <p><strong>GameObject.h</strong></p> <pre><code>#ifndef GAMEOBJECT_H #define GAMEOBJECT_H #include "Point.h" namespace arkanoid { enum class Quadrant { I, II, III, IV }; class GameObject { public: GameObject( Point topLeft, double maxPositioX, double maxPositionY, double width, double height, double velocity, double angle); virtual ~GameObject() = 0; Point topLeft() const; void setTopLeft(Point topLeft); Point bottomRight() const; double velocity() const; void setVelocity(double velocity); double angle() const; void setAngle(double angle); double quadrantAngle() const; Quadrant quadrant() const; double width() const; double height() const; virtual void move(double elapsedTimeInMS); bool reflectIfHit(const GameObject&amp; obj); private: void reflectFromQuadrantOneIfHit(const GameObject&amp; obj); void reflectFromQuadrantTwoIfHit(const GameObject&amp; obj); void reflectFromQuadrantThreeIfHit(const GameObject&amp; obj); void reflectFromQuadrantFourIfHit(const GameObject&amp; obj); void reflectToQuadrantFourIfIntersectsWithX(const GameObject&amp; obj); void reflectToQuadrantTwoIfIntersectsWithY(const GameObject&amp; obj); void reflectToQuadrantThreeIfIntersectsWithX(const GameObject&amp; obj); void reflectToQuadrantOneIfIntersectsWithY(const GameObject&amp; obj); void reflectToQuadrantTwoIfIntersectsWithX(const GameObject&amp; obj); void reflectToQuadrantFourIfIntersectsWithY(const GameObject&amp; obj); void reflectToQuadrantOneIfIntersectsWithX(const GameObject&amp; obj); void reflectToQuadrantThreeIfIntersectsWithY(const GameObject&amp; obj); void toQuadrantOne(); void toQuadrantTwo(); void toQuadrantThree(); void toQuadrantFour(); Point mTopLeft; const double mMaxPositionX; const double mMaxPositionY; const double mWidth; const double mHeight; double mVelocity; Quadrant mQuadrant; double mQuadrantAngle; }; bool isInQuadrantOne(double angle); bool isInQuadrantTwo(double angle); bool isInQuadrantThree(double angle); bool isInQuadrantFour(double angle); bool interectsWithRightX(const GameObject&amp; a, const GameObject&amp; b); void putBeforeIntersectsWithRightX(GameObject&amp; a, const GameObject&amp; b); bool interectsWithLeftX(const GameObject&amp; a, const GameObject&amp; b); void putBeforeIntersectsWithLeftX(GameObject&amp; a, const GameObject&amp; b); bool interectsWithBottomY(const GameObject&amp; a, const GameObject&amp; b); void putBeforeIntersectsWithBottomY(GameObject&amp; a, const GameObject&amp; b); bool interectsWithTopY(const GameObject&amp; a, const GameObject&amp; b); void putBeforeIntersectsWithTopY(GameObject&amp; a, const GameObject&amp; b); bool isInsideWithY(const GameObject&amp; a, const GameObject&amp; b); bool isInsideWithX(const GameObject&amp; a, const GameObject&amp; b); bool intersectsFromRigthWithX(const GameObject&amp; a, const GameObject&amp; b); bool intersectsFromLeftWithX(const GameObject&amp; a, const GameObject&amp; b); bool intersectsFromTopWithY(const GameObject&amp; a, const GameObject&amp; b); bool intersectsFromBottomWithY(const GameObject&amp; a, const GameObject&amp; b); Point calcDelta(double quadrantAngle, Quadrant quadrant, double sideC); double calcTraveldWay(double deltaTimeMS, double velocityInS); double calcAlphaIfOver360(double alpha); Quadrant calcQuadrant(double alpha); double angleToQuadrantAngle(double angle, Quadrant quadrant); double qudrantAngleToAngle(double quadrantAngle, Quadrant quadrant); double increaseAngle(double quadrantAngle); double decreaseAngle(double quadrantAngle); double mirror(double quadrantAngle); } // namespace arkanoid #endif </code></pre> <p><strong>GameObject.cpp</strong></p> <pre><code>#include "GameObject.h" #include "MathHelper.h" #include "NearlyEqual.h" #include &lt;algorithm&gt; #include &lt;stdexcept&gt; #include &lt;tuple&gt; namespace arkanoid { GameObject::GameObject(Point topLeft, double maxPositioX, double maxPositionY, double width, double height, double velocity, double angle) :mTopLeft{ topLeft }, mMaxPositionX(maxPositioX), mMaxPositionY(maxPositionY), mWidth{ width }, mHeight{ height }, mVelocity{ velocity }, mQuadrant{ calcQuadrant(angle) }, mQuadrantAngle{ angleToQuadrantAngle(angle, mQuadrant) } { } GameObject::~GameObject() = default; Point GameObject::topLeft() const { return mTopLeft; } void GameObject::setTopLeft(Point topLeft) { mTopLeft = topLeft; } Point GameObject::bottomRight() const { return Point{ mTopLeft.x + mWidth , mTopLeft.y + mHeight }; } double GameObject::velocity() const { return mVelocity; } void GameObject::setVelocity(double velocity) { mVelocity = velocity; } double GameObject::angle() const { return qudrantAngleToAngle(mQuadrantAngle, mQuadrant); } void GameObject::setAngle(double angle) { angle = calcAlphaIfOver360(angle); mQuadrant = calcQuadrant(angle); mQuadrantAngle = angleToQuadrantAngle(angle, mQuadrant); } double GameObject::quadrantAngle() const { return mQuadrantAngle; } Quadrant GameObject::quadrant() const { return mQuadrant; } double GameObject::width() const { return mWidth; } double GameObject::height() const { return mHeight; } void GameObject::move(double elapsedTimeInMS) { auto distance = calcTraveldWay(elapsedTimeInMS, mVelocity); auto traveldWay = calcDelta(mQuadrantAngle, mQuadrant, distance); mTopLeft.x += traveldWay.x; mTopLeft.y += traveldWay.y; auto maxX = mTopLeft.x + mWidth; mTopLeft.x = std::clamp(maxX, mWidth, mMaxPositionX) - mWidth; auto maxY = mTopLeft.y + mHeight; mTopLeft.y = std::clamp(maxY, mHeight, mMaxPositionY) - mHeight; } bool GameObject::reflectIfHit(const GameObject&amp; obj) { auto oldQuadrant = mQuadrant; switch (mQuadrant) { case Quadrant::I: reflectFromQuadrantOneIfHit(obj); break; case Quadrant::II: reflectFromQuadrantTwoIfHit(obj); break; case Quadrant::III: reflectFromQuadrantThreeIfHit(obj); break; case Quadrant::IV: reflectFromQuadrantFourIfHit(obj); break; } return mQuadrant != oldQuadrant; } void GameObject::reflectFromQuadrantOneIfHit(const GameObject&amp; obj) { if (interectsWithBottomY(*this, obj)) { reflectToQuadrantFourIfIntersectsWithX(obj); } else if (interectsWithRightX(*this, obj)) { reflectToQuadrantTwoIfIntersectsWithY(obj); } } void GameObject::reflectFromQuadrantTwoIfHit(const GameObject&amp; obj) { if (interectsWithLeftX(*this, obj)) { reflectToQuadrantOneIfIntersectsWithY(obj); } else if (interectsWithBottomY(*this, obj)) { reflectToQuadrantThreeIfIntersectsWithX(obj); } } void GameObject::reflectFromQuadrantThreeIfHit(const GameObject&amp; obj) { if (interectsWithLeftX(*this, obj)) { reflectToQuadrantFourIfIntersectsWithY(obj); } else if (interectsWithTopY(*this, obj)) { reflectToQuadrantTwoIfIntersectsWithX(obj); } } void GameObject::reflectFromQuadrantFourIfHit(const GameObject&amp; obj) { if (interectsWithRightX(*this, obj)) { reflectToQuadrantThreeIfIntersectsWithY(obj); } else if (interectsWithTopY(*this, obj)) { reflectToQuadrantOneIfIntersectsWithX(obj); } } void GameObject::reflectToQuadrantFourIfIntersectsWithX( const GameObject&amp; obj) { if (isInsideWithX(*this, obj)) { toQuadrantFour(); } else if (intersectsFromRigthWithX(*this, obj) || intersectsFromLeftWithX(*this, obj)) { toQuadrantFour(); mQuadrantAngle = increaseAngle(mQuadrantAngle); } else { return; } putBeforeIntersectsWithBottomY(*this, obj); } void GameObject::reflectToQuadrantTwoIfIntersectsWithY( const GameObject&amp; obj) { if (isInsideWithY(*this, obj)) { toQuadrantTwo(); } else if (intersectsFromTopWithY(*this, obj) || intersectsFromBottomWithY(*this, obj)) { toQuadrantTwo(); mQuadrantAngle = increaseAngle(mQuadrantAngle); } else { return; } putBeforeIntersectsWithRightX(*this, obj); } void GameObject::reflectToQuadrantThreeIfIntersectsWithX( const GameObject&amp; obj) { if (isInsideWithX(*this, obj)) { toQuadrantThree(); } else if (intersectsFromRigthWithX(*this, obj) || intersectsFromLeftWithX(*this, obj)) { toQuadrantThree(); mQuadrantAngle = decreaseAngle(mQuadrantAngle); } else { return; } putBeforeIntersectsWithBottomY(*this, obj); } void GameObject::reflectToQuadrantOneIfIntersectsWithY( const GameObject&amp; obj) { if (isInsideWithY(*this, obj)) { toQuadrantOne(); } else if (intersectsFromTopWithY(*this, obj) || intersectsFromBottomWithY(*this, obj)) { toQuadrantOne(); mQuadrantAngle = decreaseAngle(mQuadrantAngle); } else { return; } putBeforeIntersectsWithLeftX(*this, obj); } void GameObject::reflectToQuadrantTwoIfIntersectsWithX( const GameObject&amp; obj) { if (isInsideWithX(*this, obj)) { toQuadrantTwo(); } else if (intersectsFromRigthWithX(*this, obj) || intersectsFromLeftWithX(*this, obj)) { toQuadrantTwo(); mQuadrantAngle = increaseAngle(mQuadrantAngle); } else { return; } putBeforeIntersectsWithTopY(*this, obj); } void GameObject::reflectToQuadrantFourIfIntersectsWithY( const GameObject&amp; obj) { if (isInsideWithY(*this, obj)) { toQuadrantFour(); } else if (intersectsFromTopWithY(*this, obj) || intersectsFromBottomWithY(*this, obj)) { toQuadrantFour(); mQuadrantAngle = increaseAngle(mQuadrantAngle); } else { return; } putBeforeIntersectsWithLeftX(*this, obj); } void GameObject::reflectToQuadrantOneIfIntersectsWithX( const GameObject&amp; obj) { if (isInsideWithX(*this, obj)) { toQuadrantOne(); } else if (intersectsFromRigthWithX(*this, obj) || intersectsFromLeftWithX(*this, obj)) { toQuadrantOne(); mQuadrantAngle = decreaseAngle(mQuadrantAngle); } else { return; } putBeforeIntersectsWithTopY(*this, obj); } void GameObject::reflectToQuadrantThreeIfIntersectsWithY( const GameObject&amp; obj) { if (isInsideWithY(*this, obj)) { toQuadrantThree(); } else if (intersectsFromTopWithY(*this, obj) || intersectsFromBottomWithY(*this, obj)) { toQuadrantThree(); mQuadrantAngle = decreaseAngle(mQuadrantAngle); } else { return; } putBeforeIntersectsWithRightX(*this, obj); } void GameObject::toQuadrantOne() { mQuadrant = Quadrant::I; mQuadrantAngle = mirror(mQuadrantAngle); } void GameObject::toQuadrantTwo() { mQuadrant = Quadrant::II; mQuadrantAngle = mirror(mQuadrantAngle); } void GameObject::toQuadrantThree() { mQuadrant = Quadrant::III; mQuadrantAngle = mirror(mQuadrantAngle); } void GameObject::toQuadrantFour() { mQuadrant = Quadrant::IV; mQuadrantAngle = mirror(mQuadrantAngle); } bool isInQuadrantOne(double angle) { return angle &gt;= deg_0 &amp;&amp; angle &lt;= deg_90; } bool isInQuadrantTwo(double angle) { return angle &gt; deg_90 &amp;&amp; angle &lt;= deg_180; } bool isInQuadrantThree(double angle) { return angle &gt; deg_180 &amp;&amp; angle &lt;= deg_270; } bool isInQuadrantFour(double angle) { return angle &gt; deg_270 &amp;&amp; angle &lt;= deg_360; } bool interectsWithRightX(const GameObject&amp; a, const GameObject&amp; b) { return a.bottomRight().x &gt;= b.topLeft().x &amp;&amp; a.topLeft().x &lt; b.topLeft().x; } void putBeforeIntersectsWithRightX(GameObject&amp; a, const GameObject&amp; b) { Point p = a.topLeft(); p.x = b.topLeft().x - a.width(); a.setTopLeft(p); } bool interectsWithLeftX(const GameObject&amp; a, const GameObject&amp; b) { return a.topLeft().x &lt;= b.bottomRight().x &amp;&amp; a.bottomRight().x &gt; b.bottomRight().x; } void putBeforeIntersectsWithLeftX(GameObject&amp; a, const GameObject&amp; b) { Point p = a.topLeft(); p.x = b.bottomRight().x; a.setTopLeft(p); } bool interectsWithBottomY(const GameObject&amp; a, const GameObject&amp; b) { return a.bottomRight().y &gt;= b.topLeft().y &amp;&amp; a.topLeft().y &lt; b.topLeft().y; } void putBeforeIntersectsWithBottomY(GameObject&amp; a, const GameObject&amp; b) { Point p = a.topLeft(); p.y = b.topLeft().y - a.height(); a.setTopLeft(p); } bool interectsWithTopY(const GameObject&amp; a, const GameObject&amp; b) { return a.topLeft().y &lt;= b.bottomRight().y &amp;&amp; a.bottomRight().y &gt; b.bottomRight().y; } void putBeforeIntersectsWithTopY(GameObject&amp; a, const GameObject&amp; b) { Point p = a.topLeft(); p.y = b.bottomRight().y; a.setTopLeft(p); } bool isInsideWithY(const GameObject&amp; a, const GameObject&amp; b) { return a.topLeft().y &gt;= b.topLeft().y &amp;&amp; a.bottomRight().y &lt;= b.bottomRight().y; } bool isInsideWithX(const GameObject&amp; a, const GameObject&amp; b) { return a.topLeft().x &gt;= b.topLeft().x &amp;&amp; a.bottomRight().x &lt;= b.bottomRight().x; } bool intersectsFromRigthWithX(const GameObject&amp; a, const GameObject&amp; b) { return a.bottomRight().x &gt;= b.topLeft().x &amp;&amp; a.bottomRight().x &lt;= b.bottomRight().x &amp;&amp; a.topLeft().x &lt; b.topLeft().x; } bool intersectsFromLeftWithX(const GameObject&amp; a, const GameObject&amp; b) { return a.topLeft().x &gt;= b.topLeft().x &amp;&amp; a.topLeft().x &lt;= b.bottomRight().x &amp;&amp; a.bottomRight().x &gt; b.bottomRight().x; } bool intersectsFromTopWithY(const GameObject&amp; a, const GameObject&amp; b) { return a.bottomRight().y &gt;= b.topLeft().y &amp;&amp; a.bottomRight().y &lt;= b.bottomRight().y &amp;&amp; a.topLeft().y &lt; b.topLeft().y; } bool intersectsFromBottomWithY(const GameObject&amp; a, const GameObject&amp; b) { return a.topLeft().y &gt;= b.topLeft().y &amp;&amp; a.topLeft().y &lt;= b.bottomRight().y &amp;&amp; a.bottomRight().y &gt; b.bottomRight().y; } Point calcDelta(double quadrantAngle, Quadrant quadrant, double sideC) { if (nearlyEqual(sideC, 0.0)) { return Point{ 0,0 }; } auto sideA = sin(quadrantAngle) * sideC; auto sideB = cos(quadrantAngle) * sideC; Point ret; switch (quadrant) { case Quadrant::I: ret.x = sideB; ret.y = sideA; break; case Quadrant::II: ret.x = -sideA; ret.y = sideB; break; case Quadrant::III: ret.x = -sideB; ret.y = -sideA; break; case Quadrant::IV: ret.x = sideA; ret.y = -sideB; break; } return ret; } double calcTraveldWay(double deltaTimeMS, double velocityInS) { return deltaTimeMS / 1000.0 * velocityInS; } double calcAlphaIfOver360(double alpha) { if (alpha &gt; deg_360) { alpha -= deg_360; } return alpha; } Quadrant calcQuadrant(double alpha) { if (isInQuadrantOne(alpha)) { return Quadrant::I; } if (isInQuadrantTwo(alpha)) { return Quadrant::II; } if (isInQuadrantThree(alpha)) { return Quadrant::III; } return Quadrant::IV; } double angleToQuadrantAngle(double angle, Quadrant quadrant) { return angle - deg_90 * static_cast&lt;int&gt;(quadrant); } double qudrantAngleToAngle(double quadrantAngle, Quadrant quadrant) { return quadrantAngle + deg_90 * static_cast&lt;int&gt;(quadrant); } double increaseAngle(double quadrantAngle) { quadrantAngle *= 1.03; return std::clamp(quadrantAngle, 0.0, deg_60); } double decreaseAngle(double quadrantAngle) { return quadrantAngle * 0.97; } double mirror(double quadrantAngle) { return deg_90 - quadrantAngle; } } // namespace arkanoid </code></pre> <p><strong>Ball.h</strong></p> <pre><code>#ifndef BALL_H #define BALL_H #include "GameObject.h" #include "MathHelper.h" namespace arkanoid { class Ball : public GameObject { public: Ball(Point topLeft, double maxPositionX, double maxPositionY); ~Ball() override = default; bool isActive(); void activate(); void deactivate(); void move(double elapsedTimeInMS) override; private: const Point mInitPosition; bool mIsActive; static constexpr auto startAngle{ deg_135 }; static constexpr auto startVelocity{ 9.0 }; static constexpr auto gravityVelocity{ 2.5 }; static constexpr auto width{ 1 }; static constexpr auto height{ 1 }; }; } // namespace arkanoid #endif </code></pre> <p><strong>Ball.cpp</strong></p> <pre><code>#include "Ball.h" #include &lt;algorithm&gt; namespace arkanoid { Ball::Ball(Point topLeft, double maxPositionX, double maxPositionY) :GameObject(topLeft, maxPositionX, maxPositionY, width, height, 0.0, 0.0), mInitPosition{ topLeft }, mIsActive{false} { } bool Ball::isActive() { return mIsActive; } void Ball::deactivate() { mIsActive = false; setAngle(0.0); setVelocity(0.0); setTopLeft(mInitPosition); } void Ball::activate() { mIsActive = true; setAngle(startAngle); setVelocity(startVelocity); } void Ball::move(double elapsedTimeInMS) { auto distanceY = calcTraveldWay(elapsedTimeInMS, gravityVelocity); auto p = topLeft(); p.y += distanceY; setTopLeft(p); GameObject::move(elapsedTimeInMS); } } // namespace arkanoid </code></pre> <p><strong>Brick.h</strong></p> <pre><code>#ifndef BRICK_H #define BRICK_H #include "GameObject.h" namespace arkanoid { class Brick : public GameObject { public: Brick(Point topLeft, double width, double height, std::size_t hitpoints); ~Brick() override = default; double velocity() const = delete; void setVelocity(double velocity) = delete; double angle() const = delete; void setAngle(double angle) = delete; void move(const Point&amp; delta) = delete; std::size_t startHitpoints() const; std::size_t hitpoints() const; void decreaseHitpoints(); bool isDestroyed() const; private: const std::size_t mStartHitpoints; std::size_t mHitpoints; }; } // namespace arkanoid #endif </code></pre> <p><strong>Brick.cpp</strong></p> <pre><code>#include "Brick.h" namespace arkanoid { Brick::Brick(Point topLeft, double width, double height, std::size_t hitpoints) :GameObject(topLeft, topLeft.x + width, topLeft.y + height, width, height, 0, 0), mHitpoints(hitpoints), mStartHitpoints(hitpoints) { } std::size_t Brick::startHitpoints() const { return mStartHitpoints; } std::size_t Brick::hitpoints() const { return mHitpoints; } void Brick::decreaseHitpoints() { --mHitpoints; } bool Brick::isDestroyed() const { return mHitpoints == 0; } } // namespace arkanoid </code></pre> <p><strong>Platform.h</strong></p> <pre><code>#ifndef PLATFORM_H #define PLATFORM_H #include "GameObject.h" namespace arkanoid { class Platform : public GameObject { public: Platform(Point topLeft, double maxPositioX, double length); ~Platform() override = default; void setToInitPosition(); private: const Point mInitPosition; static constexpr auto mStartAngle{ 0 }; static constexpr auto mStartVelocity{ 10.0 }; }; } // namespace arkanoid #endif </code></pre> <p><strong>Platform.cpp</strong></p> <pre><code>#include "Platform.h" namespace arkanoid { Platform::Platform( Point topLeft, double maxPositioX, double length) : GameObject( topLeft, maxPositioX, topLeft.y + 1, length, 1, mStartVelocity, mStartAngle), mInitPosition{ topLeft } { } void Platform::setToInitPosition() { setTopLeft(mInitPosition); } } // namespace arkanoid </code></pre> <p><strong>Wall.h</strong></p> <pre><code>#ifndef WALL_H #define WALL_H #include "GameObject.h" namespace arkanoid { class Wall : public GameObject { public: Wall(Point topLeft, double width, double height); ~Wall() override = default; double velocity() const = delete; void setVelocity(double velocity) = delete; double angle() const = delete; void setAngle(double angle) = delete; void move(const Point&amp; delta) = delete; }; } // namespace arkanoid #endif </code></pre> <p><strong>Wall.cpp</strong></p> <pre><code>#include "Wall.h" namespace arkanoid { Wall::Wall(Point topLeft, double width, double height) :GameObject(topLeft, topLeft.x + width, topLeft.y + height, width, height, 0, 0) { } } </code></pre> <p><strong>Point.h</strong></p> <pre><code>#ifndef POINT_H #define POINT_H #include &lt;cstddef&gt; namespace arkanoid { struct Point { double x{ 0.0 }; double y{ 0.0 }; }; }// namespace arkanoid #endif </code></pre> <p><strong>Time.h</strong></p> <pre><code>#ifndef TIME_H #define TIME_H #include &lt;chrono&gt; namespace arkanoid { std::chrono::time_point&lt;std::chrono::high_resolution_clock&gt; getCurrentTime(); double getElapsedTime( const std::chrono::time_point&lt; std::chrono::high_resolution_clock&gt;&amp; first, const std::chrono::time_point&lt; std::chrono::high_resolution_clock&gt;&amp; last); void wait(const std::chrono::milliseconds&amp; milliseconds); } // namespace arkanoid #endif </code></pre> <p><strong>Time.cpp</strong></p> <pre><code>#include "Time.h" #include &lt;thread&gt; namespace arkanoid { std::chrono::time_point&lt;std::chrono::high_resolution_clock&gt; getCurrentTime() { return std::chrono::high_resolution_clock::now(); } double getElapsedTime( const std::chrono::time_point&lt; std::chrono::high_resolution_clock&gt;&amp; first, const std::chrono::time_point&lt; std::chrono::high_resolution_clock&gt;&amp; last) { return static_cast&lt;int&gt;( std::chrono::duration&lt;double, std::milli&gt;(last - first).count()); } void wait(const std::chrono::milliseconds&amp; milliseconds) { std::this_thread::sleep_for(milliseconds); } } </code></pre> <p><strong>Grid.h</strong></p> <pre><code>#ifndef GRID_H #define GRID_H #include &lt;iosfwd&gt; #include &lt;vector&gt; namespace arkanoid { class Ball; class Brick; class Platform; class Wall; class GameObject; enum class Field { ball, brick1Hits, brick2Hits, brick3Hits, brick4Hits, brick5Hits, brick6Hits, brick7Hits, brick8Hits, brick9Hits, empty, plattform, wall }; class Grid { public: Grid(std::size_t width, std::size_t height); ~Grid() = default; void add(const Ball&amp; ball); void add(const Brick&amp; brick); void add(const Platform&amp; plattform); void add(const Wall&amp; wall); private: void add(const GameObject&amp; gameObject, const Field&amp; field); std::vector&lt;std::vector&lt;Field&gt;&gt; mFields; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Grid&amp; obj); }; std::vector&lt;std::vector&lt;Field&gt;&gt; init( std::size_t width, std::size_t height); std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Grid&amp; obj); } // namespace arkanoid #endif </code></pre> <p><strong>Grid.cpp</strong></p> <pre><code>#include "Grid.h" #include "Ball.h" #include "Brick.h" #include "Platform.h" #include "Wall.h" #include &lt;algorithm&gt; #include &lt;cmath&gt; #include &lt;iostream&gt; namespace arkanoid { Grid::Grid(std::size_t width, std::size_t height) : mFields{ init(width, height) } { } void Grid::add(const Ball&amp; ball) { add(ball, Field::ball); } void Grid::add(const Brick&amp; brick) { if (brick.isDestroyed()) { return; } auto brickType = static_cast&lt;int&gt;(Field::brick1Hits); brickType = brickType + brick.hitpoints() - 1; add(brick, static_cast&lt;Field&gt;(brickType)); } void Grid::add(const Platform&amp; plattform) { add(plattform, Field::plattform); } void Grid::add(const Wall&amp; wall) { add(wall, Field::wall); } void Grid::add(const GameObject&amp; gameObject, const Field&amp; field) { auto x_begin = static_cast&lt;std::size_t&gt;(gameObject.topLeft().x); auto x_end = static_cast&lt;std::size_t&gt;(gameObject.bottomRight().x); auto y_begin = static_cast&lt;std::size_t&gt;(gameObject.topLeft().y); auto y_end = static_cast&lt;std::size_t&gt;(gameObject.bottomRight().y); for (auto y = y_begin; y &lt; y_end; ++y) { for (auto x = x_begin; x &lt; x_end; ++x) { mFields.at(y).at(x) = field; } } } std::vector&lt;std::vector&lt;Field&gt;&gt; init(std::size_t width, std::size_t height) { std::vector&lt;Field&gt; row(width, Field::empty); std::vector&lt;std::vector&lt;Field&gt;&gt; fields(height, row); return fields; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Grid&amp; obj) { auto symbolWall = "# "; auto symbolBall = "O "; auto symbolBrick = "1 "; auto symbolPlattform = "= "; auto symbolEmpty = ". "; auto symbolBrick1Hit = "1 "; auto symbolBrick2Hit = "2 "; auto symbolBrick3Hit = "3 "; auto symbolBrick4Hit = "4 "; auto symbolBrick5Hit = "5 "; auto symbolBrick6Hit = "6 "; auto symbolBrick7Hit = "7 "; auto symbolBrick8Hit = "8 "; auto symbolBrick9Hit = "9 "; auto size_y = obj.mFields.size(); auto size_x = obj.mFields.at(0).size(); for (const auto&amp; row : obj.mFields) { for (const auto&amp; field : row) { switch (field) { case Field::ball: os &lt;&lt; symbolBall; break; case Field::brick1Hits: os &lt;&lt; symbolBrick1Hit; break; case Field::brick2Hits: os &lt;&lt; symbolBrick2Hit; break; case Field::brick3Hits: os &lt;&lt; symbolBrick3Hit; break; case Field::brick4Hits: os &lt;&lt; symbolBrick4Hit; break; case Field::brick5Hits: os &lt;&lt; symbolBrick5Hit; break; case Field::brick6Hits: os &lt;&lt; symbolBrick6Hit; break; case Field::brick7Hits: os &lt;&lt; symbolBrick7Hit; break; case Field::brick8Hits: os &lt;&lt; symbolBrick8Hit; break; case Field::brick9Hits: os &lt;&lt; symbolBrick9Hit; break; case Field::empty: os &lt;&lt; symbolEmpty; break; case Field::plattform: os &lt;&lt; symbolPlattform; break; case Field::wall: os &lt;&lt; symbolWall; break; } } os &lt;&lt; '\n'; } return os; } } // namespace arkanoid </code></pre> <p><strong>Console.h</strong></p> <pre><code>#ifndef CONSOLE_H #define CONSOLE_H #include &lt;cstddef&gt; namespace console { void resize(std::size_t x, std::size_t y); void putCursorToStartOfConsole(); void clearScreen(); bool keyWasPressed(); char getKey(); bool leftKeyHoldDown(); bool rightKeyHoldDown(); bool spaceKeyHoldDown(); bool escKeyHoldDown(); bool rKeyHoldDown(); bool isKeyDown(int key_code); } // namespace console #endif </code></pre> <p><strong>Console.cpp</strong></p> <pre><code>#include "Console.h" #include &lt;cstdlib&gt; #include &lt;conio.h&gt; #include &lt;Windows.h&gt; #include &lt;WinUser.h&gt; namespace console { void resize(std::size_t x, std::size_t y) { HWND console = GetConsoleWindow(); RECT r; GetWindowRect(console, &amp;r); //stores the console's current dimensions MoveWindow(console, r.left, r.top, x, y, true); } void putCursorToStartOfConsole() { HANDLE hOut; COORD Position; hOut = GetStdHandle(STD_OUTPUT_HANDLE); Position.X = 0; Position.Y = 0; SetConsoleCursorPosition(hOut, Position); } void clearScreen() { std::system("cls"); } bool keyWasPressed() { return static_cast&lt;bool&gt;(_kbhit()); } char getKey() { return _getch(); } bool leftKeyHoldDown() { return isKeyDown(VK_LEFT); } bool rightKeyHoldDown() { return isKeyDown(VK_RIGHT); } bool spaceKeyHoldDown() { return isKeyDown(VK_SPACE); } bool escKeyHoldDown() { return isKeyDown(VK_ESCAPE); } bool rKeyHoldDown() { return isKeyDown(0x52); } bool isKeyDown(int key_code) { return GetAsyncKeyState(key_code) &amp; -32768; } } </code></pre> <p><strong>NearlyEqual.h</strong></p> <pre><code>#ifndef NEARLYEQUAL_H #define NEARLYEQUAL_H namespace arkanoid{ bool nearlyEqual(double a, double b); bool nearlyEqual(double a, double b, int factor); } #endif </code></pre> <p><strong>NearlyEqual.cpp</strong></p> <pre><code>#include "NearlyEqual.h" #include &lt;limits&gt; #include &lt;cmath&gt; namespace arkanoid { bool nearlyEqual(double a, double b) { return std::nextafter(a, std::numeric_limits&lt;double&gt;::lowest()) &lt;= b &amp;&amp; std::nextafter(a, std::numeric_limits&lt;double&gt;::max()) &gt;= b; } bool nearlyEqual(double a, double b, int factor) { double min_a = a - (a - std::nextafter( a, std::numeric_limits&lt;double&gt;::lowest())) * factor; double max_a = a + ( std::nextafter(a, std::numeric_limits&lt;double&gt;::max()) - a) * factor; return min_a &lt;= b &amp;&amp; max_a &gt;= b; } } // namespace arkanoid </code></pre> <p><strong>MathHelper.h</strong></p> <pre><code>#ifndef MATHHELPER_H #define MATHHELPER_H #define _USE_MATH_DEFINES #include &lt;math.h&gt; #include &lt;limits&gt; namespace arkanoid { constexpr double pi = M_PI; constexpr double deg_0 = 0.0; constexpr double deg_15 = pi / 12.0; constexpr double deg_30 = 2 * deg_15; constexpr double deg_45 = pi / 4.0; constexpr double deg_60 = deg_45 + deg_15; constexpr double deg_75 = deg_60 + deg_15; constexpr double deg_90 = pi / 2.0; constexpr double deg_105 = deg_90 + deg_15; constexpr double deg_120 = deg_105 + deg_15; constexpr double deg_135 = deg_120 + deg_15; constexpr double deg_150 = deg_135 + deg_15; constexpr double deg_165 = deg_150 + deg_15; constexpr double deg_180 = pi; constexpr double deg_195 = deg_180 + deg_15; constexpr double deg_210 = deg_195 + deg_15; constexpr double deg_225 = deg_210 + deg_15; constexpr double deg_240 = deg_225 + deg_15; constexpr double deg_255 = deg_240 + deg_15; constexpr double deg_270 = 3 * deg_90; constexpr double deg_285 = deg_270 + deg_15; constexpr double deg_300 = deg_285 + deg_15; constexpr double deg_315 = deg_270 + deg_45; constexpr double deg_330 = deg_315 + deg_15; constexpr double deg_345 = deg_330 + deg_15; constexpr double deg_360 = 2 * pi; constexpr double degreesToRadient(double degree) { return degree * pi / 180.0; } constexpr double radientToDegrees(double radient) { return radient * 180.0 / pi; } } // namespace arkanoid #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:21:20.997", "Id": "426266", "Score": "0", "body": "By \"after doing the Snake Game\" do you mean https://codereview.stackexchange.com/q/219886?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:22:48.447", "Id": "426267", "Score": "0", "body": "yes i also made a qt version of it after in annother question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:24:38.187", "Id": "426269", "Score": "0", "body": "Well, https://codereview.stackexchange.com/q/220147, presumably. They seem quite good!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:41:02.510", "Id": "426273", "Score": "0", "body": "\"plattform\" --> German has kicked in ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:44:36.687", "Id": "426276", "Score": "0", "body": "i could swear i had fixed that typo everywere :(." } ]
[ { "body": "<p>Composition over inheritance. You have a base class GameObject which only does collision and bounding box type stuff. There is no need for it to be a base class that you inherit from. </p>\n\n<p>Make it a member variable instead and access it when you need to. Adding gravity to the ball and moving the platform in response to keyboard doesn't need virtual functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:50:26.740", "Id": "220643", "ParentId": "220619", "Score": "3" } }, { "body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Fix the bug</h2>\n\n<p>It might work well on your machine, but my computer apparently runs faster and so in <code>Level::run()</code> no time elapses in the main loop and therefore nothing moves. I'd suggest using a timer to drive movement rather than looping on the time.</p>\n\n<h2>Allow for portability</h2>\n\n<p>Rather than coding the display mechanics directly in the <code>Level</code> code, an improvement might be to implement a <code>console::show(std::stringstream &amp;ss)</code> that would isolate the platform-specfic code to just <code>Console.cpp</code>.</p>\n\n<h2>Use user-defined literals</h2>\n\n<p>The <code>MathHelper.h</code> has a number of lines that look like this:</p>\n\n<pre><code>constexpr double deg_255 = deg_240 + deg_15;\n</code></pre>\n\n<p>And then it defines <code>radientToDegrees()</code> which is never used. First, it's \"radian\" not \"radient\". Second, this is a good place to use a <a href=\"https://en.cppreference.com/w/cpp/language/user_literal\" rel=\"nofollow noreferrer\">user-defined literals</a>. Here's how:</p>\n\n<pre><code>constexpr long double operator\"\" _deg(long double deg) {\n return deg*M_PI/180;\n}\n</code></pre>\n\n<p>Now anywhere you need degrees, instead of <code>deg_255</code>, just use <code>255.0_deg</code> and all of those constants go away.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>There are several places, such as <code>Ball::isActive()</code> which simply report back something about the underlying object without altering it. Those should be <code>const</code> like this:</p>\n\n<pre><code>bool Ball:isActive() const { return mIsActive; }\n</code></pre>\n\n<h2>Make constructors more useful</h2>\n\n<p>The <code>Level</code> file contains code that creates a <code>vector</code> of <code>Brick</code> objects like this:</p>\n\n<pre><code> return std::vector&lt;Brick&gt;\n {\n Brick{ Point{4,2},brickLength,brickHeight,1 },\n Brick{ Point{7,2},brickLength,brickHeight,1 },\n Brick{ Point{10,2},brickLength,brickHeight,1 },\n Brick{ Point{13,2},brickLength,brickHeight,1 },\n Brick{ Point{16,2},brickLength,brickHeight,1 },\n Brick{ Point{19,2},brickLength,brickHeight,1 },\n</code></pre>\n\n<p>I'm exhausted just looking at it! Instead, make <code>brickLength</code> and <code>brickHeight</code> default values of the <code>Brick</code> constructor and then the code could look like this:</p>\n\n<pre><code> return std::vector&lt;Brick&gt;\n {\n { {4,2},1 },\n { {7,2},1 },\n { {10,2},1 },\n { {13,2},1 },\n { {16,2},1 },\n { {19,2},1 },\n</code></pre>\n\n<p>I'd probably even rearrange the constructor to put <code>hitpoints</code> just after <code>topLeft</code> and give it a default value of <code>1</code>. Also, there seems little point to having <code>makePlatform</code> and <code>makeBall</code> when all they do is call constructors anyway.</p>\n\n<h2>Eliminate redundant code</h2>\n\n<p>In <code>Level::printToConsole()</code> there is no need to call <code>console::putCursorToStartOfConsole()</code> twice. In fact, with a minor bit of restructuring and creation of a <code>console::show()</code> routine as mentioned above, that bit of code could be placed within <code>show()</code>.</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>Unused variables are a sign of poor quality code, and you don't want to write poor quality code. In this code, in <code>Grid.cpp</code>, <code>symbolBrick</code>, <code>size_y</code> and <code>size_x</code> are all unused. Your compiler is smart enough to tell you about this if you ask it nicely.</p>\n\n<h2>Eliminate unused code</h2>\n\n<p>There are several unused functions in this code including the one mentioned earlier and one of the <code>nearlyEqual</code> forms. Search and destroy them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T18:01:47.310", "Id": "428194", "Score": "0", "body": "Thanks for the many helpfull suggestions. I totally forgot about the existance of `operator\"\"` thats a nice addition in this case i guess. I did not made the bricks height and lengths default because i want to support bricks with many different shapes later." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T12:45:30.673", "Id": "221410", "ParentId": "220619", "Score": "2" } } ]
{ "AcceptedAnswerId": "221410", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:33:10.437", "Id": "220619", "Score": "9", "Tags": [ "c++", "game", "c++17" ], "Title": "Arkanoid Console Game" }
220619
<p>i've recently released a from scratch set of library <a href="https://github.com/thenameless314159/Astron" rel="nofollow noreferrer"><strong>Astron</strong></a>, and I wanted to get my memory policy logic reviewed.(you can find a little doc about it <a href="https://github.com/thenameless314159/Astron/wiki/Astron.Memory" rel="nofollow noreferrer">here</a>).</p> <p>My first goal was to provide an <strong>extandable API</strong> to allow the user to implement his own memory policy, but I've also provided some base implementations especially one that use the <code>ArrayPool&lt;byte&gt;.Shared</code> instance in order to handle the <code>IMemoryOwner&lt;byte&gt;</code> logic. Thanks to M. Gravell and <a href="https://github.com/mgravell/simplsockets/blob/master/SimplPipelines/MemoryOwner.cs" rel="nofollow noreferrer">its implementation</a>, I didn't had much work to do about it.</p> <p>According to the specifications, I first defined my memory policy interface :</p> <pre><code>public interface IMemoryPolicy { Memory&lt;T&gt; GetArray&lt;T&gt;(int size); IMemoryOwner&lt;T&gt; GetOwnedArray&lt;T&gt;(int size); } </code></pre> <p>You may have noticed that this interface can return an <a href="https://docs.microsoft.com/en-us/dotnet/api/system.buffers.imemoryowner-1?view=netstandard-2.1" rel="nofollow noreferrer"><code>IMemoryOwner&lt;T&gt;</code></a> which is an interface from the BCL, therefore I then had to implement it.</p> <p>As the memory policy may be used in a multi-threaded context, <strong>its behavior must be handled in a thread-safe way</strong>, and this is where M.Gravell's implementation come in action. He used the <code>Interlocked</code> class to implement thread-safety, which I did accordingly. So I just had to abstract its implementation to fit the specifications :</p> <pre><code> public abstract class PoolOwner&lt;T&gt; : IMemoryOwner&lt;T&gt; { private readonly int _length; private T[] _oversized; public Memory&lt;T&gt; Memory =&gt; new Memory&lt;T&gt;(GetArray(), 0, _length); protected PoolOwner(T[] oversized, int length) { if (length &gt; oversized.Length) throw new ArgumentOutOfRangeException(nameof(length)); _length = length; _oversized = oversized; } protected abstract void ReturnToPool(T[] array); protected T[] GetArray() =&gt; Interlocked.CompareExchange(ref _oversized, null, null) ?? throw new ObjectDisposedException(ToString()); public void Dispose() { var arr = Interlocked.Exchange(ref _oversized, null); if (arr != null) ReturnToPool(arr); } } </code></pre> <p>Now the user only have to implement this class with the <code>abstract void ReturnToPool(T[] array);</code> method to have a thread-safe <a href="https://docs.microsoft.com/en-us/dotnet/api/system.buffers.imemoryowner-1?view=netstandard-2.1" rel="nofollow noreferrer"><code>IMemoryOwner&lt;T&gt;</code></a>. Also, this class was unit-tested you can find the tests <a href="https://github.com/thenameless314159/Astron/blob/master/tests/Astron.Memory.Tests/PoolOwnerTests.cs" rel="nofollow noreferrer">on my repo here</a>. Then I just had to implement it and create the relative policy which make usage of my <a href="https://docs.microsoft.com/en-us/dotnet/api/system.buffers.imemoryowner-1?view=netstandard-2.1" rel="nofollow noreferrer"><code>IMemoryOwner&lt;T&gt;</code></a> implementation :</p> <pre><code> internal sealed class SharedPoolOwner&lt;T&gt; : PoolOwner&lt;T&gt; { public SharedPoolOwner(T[] oversized, int length) : base(oversized, length) { } protected override void ReturnToPool(T[] array) =&gt; ArrayPool&lt;T&gt;.Shared.Return(array); } </code></pre> <pre><code> public class HeapAllocWithSharedPoolPolicy : IMemoryPolicy { private static IMemoryOwner&lt;T&gt; EmptyOwner&lt;T&gt;() =&gt; SimpleMemoryOwner&lt;T&gt;.Empty; private static T[] Empty&lt;T&gt;() =&gt; Array.Empty&lt;T&gt;(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory&lt;T&gt; GetArray&lt;T&gt;(int size) { if (size == 0) return Empty&lt;T&gt;(); if (size &lt; 0) throw new ArgumentOutOfRangeException(nameof(size)); return new T[size]; } public IMemoryOwner&lt;T&gt; GetOwnedArray&lt;T&gt;(int size) { if (size == 0) return EmptyOwner&lt;T&gt;(); if (size &lt; 0) throw new ArgumentOutOfRangeException(nameof(size)); var arr = ArrayPool&lt;T&gt;.Shared.Rent(size); return new SharedPoolOwner&lt;T&gt;(arr, size); } } </code></pre> <p>(unit-tests <a href="https://github.com/thenameless314159/Astron/blob/master/tests/Astron.Memory.Tests/HeapAllocWithSharedPoolPolicy.cs" rel="nofollow noreferrer">here</a>)</p> <p>Finally, here are my questions :</p> <ul> <li>How relevant is the usage of the shared ArrayPool in production context ? How about implementing its own pool ? Allocating its own instance of the pool ?</li> <li>Should I had more methods to the memory policy with some constraints on T in order to handle more behaviors ? I assume this could also be used to pool objects in the future, i've made it for networking context in order to get buffers but it could also pool Socket objects</li> <li>M.Gravell is monitoring the leak count with its implementation, I don't see any point on doing that because if they're leaked they can't be unleaked then who cares ?</li> </ul> <p>Any suggestions is welcome, thanks you very much for reading me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:23:56.173", "Id": "426268", "Score": "0", "body": "Could you add some info about what such a memory-policy is good for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:46:17.583", "Id": "426277", "Score": "1", "body": "Yeah for sure, I mean, the code is pretty straightforward, what kind of info do you want me to add ? This kind of thing allow you to modify the behavior of the memory allocation as you want, also if standards array allocations are replaced by the policy, I assume the app becomes more maintainable and also this could helps on tracing. I also believe this is a good practice to have a memory policy to ensure to use of a pool, even if there is a GC or a static Shared pool" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:50:05.600", "Id": "426279", "Score": "0", "body": "_This kind of thing allow you to modify the behavior of the memory allocation as you want_ - this is exactly the piece of information I was looking for. I was't aware of that and didn't know it was possible. Maybe you even have a link to some interesting article about it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:54:58.510", "Id": "426280", "Score": "0", "body": "Sorry I didn't meant that, you can't modify the way the GC allocate on the heap you can just alter the behavior on top of that with such an implementation (also add logging, multi types of pool support according to T etc...). I don't have any link to go deeper on the subject and provide you some more behaviors the policy could handle, but if you make any don't mind publishing it ;-P" } ]
[ { "body": "<ol>\n<li>it is usually a good idea to use the shared pool to maximize re-use; however, if you're <em>specifically</em> worried about code incorrectly (or maliciously) snooping into your arrays (without even needing a memory debugger - just by \"returning\" things to the pool, but keeping a reference to them), then you might want to have your own pool; of course, this is not a true security barrier, as if someone is malicious enough, they can just use a memory debugger anyway</li>\n<li>(no opinion)</li>\n<li>for testing purposes and making sure that you aren't routinely accidentally dropping them on the floor</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:15:31.153", "Id": "426265", "Score": "0", "body": "1. By snooping code maliciously into my arrays you mean by injecting something into my app like reverse engineer do to alter the behavior within an application ? Therefore making its own pool is only relevant for security and customization ? Yeah a security is never perfect anyway :/\n3. So i should monitor them and make some checks wherever I want to use the owner to ensure nothing is lost ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:26:54.743", "Id": "426270", "Score": "0", "body": "...as if you had a script for watching SE for questions mentioning your tools ;-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:42:20.413", "Id": "426274", "Score": "0", "body": "@t3chb0t no, they emailed me..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:43:08.847", "Id": "426275", "Score": "0", "body": "@NamelessK1NG let's put it this way: if I was doing crypto, I'd probably use my own pool" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:47:14.580", "Id": "426278", "Score": "0", "body": "I wasn't expecting such a fast answer either ._. Good thing to know, thanks a lot for your time and answers !" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:05:33.133", "Id": "220621", "ParentId": "220620", "Score": "2" } } ]
{ "AcceptedAnswerId": "220621", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T09:38:06.433", "Id": "220620", "Score": "2", "Tags": [ "c#", "memory-management", ".net-core" ], "Title": "Memory policy with ArrayPool<T>.Shared" }
220620
<p>i got a college project and i'm trying to create a map for my text-based game in Java. Me and my colleague* created this code:</p> <pre><code>public class Mapsystem2 { //δημιουργία των πινάκων maps static int[][] map1= { {0,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0},{0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0},{0,3,3,0,0,0,1,1,1,1,1,1,1,1,1,1},{0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1},{0,1,1,1,1,1,1,1,1,1,2,2,2,2,1,1},{0,1,1,1,1,1,1,1,1,1,2,2,2,2,1,1},{0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1},{0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1},{0,0,0,0,0,0,1,1,2,2,0,0,0,0,0,0},{3,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0},{3,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0},{0,0,0,0,0,0,1,1,2,2,1,1,1,1,1,3},{0,0,0,0,0,0,1,1,2,2,1,1,1,1,1,3},{0,0,0,0,0,0,1,1,2,2,0,0,0,0,0,0},{0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0},{0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0}}; static int[][] map2= { {2,2,1,2,2,2,2,2,2,2,1,1},{2,2,1,2,2,2,2,2,2,2,1,1},{2,2,0,0,1,1,0,0,0,0,0,0},{2,2,0,0,1,1,0,0,0,0,0,0},{1,1,0,0,1,1,1,1,0,0,4,4},{1,1,0,0,2,2,2,2,0,0,1,1},{2,2,0,0,2,2,2,2,0,0,1,1},{2,2,0,0,2,2,2,2,0,0,2,2},{1,1,0,0,0,0,1,1,1,1,2,2},{1,1,0,0,0,0,1,1,1,1,2,2}}; static int tileCheck(int[] playerPos) { int x= playerPos[0]; int y= playerPos[1]; int a=0; //loadfile /** try (BufferedReader br = new BufferedReader(new FileReader("monsters.txt"))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } */ int[][] map = Mapsystem2.map1; if(playerPos[0]&lt;map.length || playerPos[0]&gt;0 ||playerPos[1]&lt;map.length || playerPos[1]&gt;0) { a=1; } //if ( map[x][y]==2) //{ //εδω θα καλουμε τη συναρτηση του battle system για να βγαινουν τα τερατα //} if ( map[x][y]==0) { System.out.println("you cannot go there"); a=0; } else if ( map[x][y]==1) { a=1; } /*else if ( map[x][y]==3) { //εδω θα αλλαζει το map }*/ return(a); } static int[] movement(String d,int[] playerPos) { int check=1; if ("north".equals(d)) { check=tileCheck(playerPos); if(check==1) { playerPos[1]= playerPos[1]-1; } else {System.out.println("You are getting out of the level"); } } else if("south".equals(d)) { check=tileCheck(playerPos); if(check==1) { playerPos[1]=playerPos[1]+1; } else {System.out.println("You are getting out of the level"); } } else if("west".equals(d)) { check=tileCheck(playerPos); if(check==1) { playerPos[0]=playerPos[0]-1; } else {System.out.println("You are getting out of the level"); } } else if("east".equals(d)) { check=tileCheck(playerPos); if(check==1) { playerPos[0]=playerPos[0]+1; } else {System.out.println("You are getting out of the level"); } } return(playerPos); } /** * @param args the command line arguments */ public static void main(String[] args) { //δημιουργία του map int[] playerPos={15,8}; int a= 1; String direction; int[][] map = Mapsystem2.map1; //εμφάνιση του map /**for (int i = 0; i &lt; map.length; i++) { for (int j = 0; j &lt; map[i].length; j++) { System.out.print(map[i][j]); } System.out.println(""); }*/ while (a==1) { System.out.println("Where do you want to go?"); System.out.println(""); Scanner in = new Scanner(System.in); direction = in.nextLine(); //System.out.println("You entered"+direction); playerPos=Mapsystem2.movement(direction, playerPos); //System.out.println(playerPos[0]); //System.out.println(playerPos[1]); //a= in.nextInt(); //System.out.println("You entered integer "+a); } } </code></pre> <p>But i don't think this is an efficient way to do it and it's very confusing, i would love some ideas and help. Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:08:32.750", "Id": "426451", "Score": "0", "body": "It's quite unclear why you're doing what you're doing. Does this work the way you want it to? Please take a look at the [help/on-topic]." } ]
[ { "body": "<p>From a quick review;</p>\n\n<ul>\n<li>Comments should be in English</li>\n<li>Commented code should be removed</li>\n<li><code>a</code> is not a great variable name, <code>allowed</code> would be better</li>\n<li>If <code>map[x][y]</code> really can only contain 0 or 1, then you might as well just\n<code>a = map[x][y]</code></li>\n<li>The code is not consistently indented</li>\n<li>You should call <code>check=tileCheck</code> only once before <code>if (\"north\".equals(d))</code> </li>\n<li>You should code for <code>else {System.out.println(\"You are getting out of the level\");}</code> only once before checking directions as well</li>\n<li>Pure functionality, but you should either map the keyboard directions (8 is north, 2 is south etc.) or map 1 letter direction (n,w,e,w_ or even map the wasd keys.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T12:25:59.743", "Id": "220635", "ParentId": "220622", "Score": "1" } }, { "body": "<p>Steve. Below are some thoughts on what you've provided. With respect, this code is really not at a state where it's reviewable per the guidelines in Code Review - it should be complete and working correctly. I understand why you're asking for a review, but maybe try to get the code further along?</p>\n\n<p>Class names should be CamelCase, so MapSystem2 would be preferable.</p>\n\n<p>Consistent indentation will make your code easier to read.</p>\n\n<p>Commented-out code is a code smell.</p>\n\n<p>Classes that aren't designed for extension should be declared <code>final</code>.</p>\n\n<p>Variables that shouldn't be reassigned should be marked <code>final</code>.</p>\n\n<p>Class variables should be private wherever possible. As designed, external classes can forcibly modify your maps without the knowledge of the Mapsystem2 class. That's probably not ideal.</p>\n\n<p>Use meaningful variable names. <code>d</code> is not meaningful. <code>direction</code> is much better. Avoid unnecessary abbreviations, because you can't be sure readers of your code will translate them the same way you do.</p>\n\n<p>Your maps would be easier to read if each internal array was placed on its own line.</p>\n\n<p>Most of the comments don't serve any purpose, as they just describe what the code is doing. Comments are usually used to explain why the code is doing something, not what it is doing.</p>\n\n<p>Please choose one language for your comments.</p>\n\n<p>In Java we traditionally put <code>{</code> on the same line, not a newline by itself.</p>\n\n<p>In Java we traditionally put whitespace between a control flow statement (<code>if</code>, <code>while</code>) and the opening paren, to visually differentiate them from method invocations.</p>\n\n<p>In Java we traditionally put whitespace on both sides of operators and equals signs for readability. </p>\n\n<p>You don't need () around a return value.</p>\n\n<p>Tracking location using an <code>int[]</code> is not ideal. What happens when somebody passes in an array of size 1 or 3? Either use separate variables for <code>x</code> and <code>y</code>, use an existing library class, or create your own location class.</p>\n\n<p>There is some argument on this point, but I find it much clearer to explicitly return when you know the return value, rather than storing a variable. I don't want to have to read the rest of a method just to figure out that the value doesn't change again before it gets returned.</p>\n\n<p>In <code>tileCheck</code>, you assign <code>x</code> and <code>y</code>, then don't use them in the first <code>if</code> check.</p>\n\n<p>The logic in <code>tileCheck</code> is very confusing. \"If you try to walk off the map or enter a square with a 1, return 1. If you try to enter a square with a 0, tell the user they can't go there then return 0. Otherwise, return 0.\" </p>\n\n<p>This class desperately needs documentation indicating what 0, 1, 2, 3, 4 actually mean. A reader will have no idea what they're dealing with. </p>\n\n<p>Likewise, the meaning of the return value for <code>tileCheck</code> is unclear. It looks like 0 means an invalid move from later code, which would make the return value of the first check wrong?</p>\n\n<p>Direction is best modeled with an <code>enum</code>. Using a map from input strings to directions would let you support multiple movement methods - \"N\", \"North\", \"w\" all move you north, etc. </p>\n\n<p>There's a lot of repetition in the <code>movement</code> method. Everything that appears in all four branches should be pulled out of the conditionals.</p>\n\n<p>It is counterintuitive that the north direction takes you towards the bottom of the map. I expect that's a bug.</p>\n\n<p>You're calling <code>tileCheck</code> based on the user's current position before they move. That means that they can move off the map one square, and then get stuck and can't get back on it. Also a bug.</p>\n\n<p><code>Scanner</code> should be closed when you're done using it, and you shouldn't create a new scanner every time through your loop. Use a <code>try-with-resources</code> block to handle closing it.</p>\n\n<p>Declare variables as closely as possible to where they're first used.</p>\n\n<p><code>while (a == 1)</code> is effectively <code>while (true)</code>, since <code>a</code> is never changing.</p>\n\n<p><code>map</code> is unused in <code>main</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T13:50:33.923", "Id": "220640", "ParentId": "220622", "Score": "2" } } ]
{ "AcceptedAnswerId": "220640", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:10:55.367", "Id": "220622", "Score": "0", "Tags": [ "java", "game", "hash-map" ], "Title": "Creating a Java text-based game map" }
220622
<p>Novice Java developer here. I've never really used a time/date library before and I'm curious how an experienced developer would solve this. You're given 4 ints: startHour, startMinute, endHour and endMinute. Now, check if current time is within the given timeframe. Is there a more clean way of doing this than what I've done here: </p> <pre><code>private void checkTimeframe(int startHour, int startMinute, int endHour, int endMinute) { LocalDateTime now = LocalDateTime.now(); LocalTime localTimeStart = new LocalTime(startHour, startMinute); LocalTime localTimeEnd = new LocalTime(endHour, endMinute); LocalDateTime startTime = new LocalDateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), startHour, startMinute); LocalDateTime endTime = new LocalDateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), endHour, endMinute); //Check if start/end is, for instance, 23:00 - 03:00 if (localTimeStart.isAfter(localTimeEnd) || localTimeStart.equals(localTimeEnd)) { endTime = endTime.plusDays(1); } if ( (now.equals(startTime) || now.isAfter(startTime) ) &amp;&amp; now.isBefore(endTime)) { System.out.println("Ok, we're within start/end"); } else { System.out.println("Outside start/end"); } } </code></pre>
[]
[ { "body": "<p>to me it looks like a simple check of number between range of numbers.\ndo I would do like this</p>\n\n<ol>\n<li><p>turn hour and minute into one number that is hhmm to simplify the comparison</p></li>\n<li><p>now its a simple check between range of numbers, taking into account the case of cross-date boundary</p></li>\n</ol>\n\n<p>complete code:</p>\n\n<pre><code>private static void checkTimeframe(int startHour, int startMinute, int endHour, int endMinute) {\n // \"concatanate\" hour and minute into one number\n int startHourMinute = startHour * 100 + startMinute;\n int endHourMinute = endHour * 100 + endMinute;\n LocalDateTime now = LocalDateTime.now();\n int nowHourMinute = now.getHour() * 100 + now.getMinute();\n\n // if range within date - simple between boundaries check\n if (startHourMinute &lt;= endHourMinute) {\n if (nowHourMinute &gt;= startHourMinute &amp;&amp; nowHourMinute &lt;= endHourMinute) {\n System.out.println(\"Ok, we're within start/end\");\n } else {\n System.out.println(\"Outside start/end\");\n }\n // else (cross date boundary range) - check if now date is either within range of yesterday or within range tomorrow \n } else {\n if (nowHourMinute &gt;= startHourMinute || nowHourMinute &lt;= endHourMinute) {\n System.out.println(\"Ok, we're within start/end\");\n } else {\n System.out.println(\"Outside start/end\");\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T15:27:00.587", "Id": "426322", "Score": "0", "body": "Thanks a lot, really simple and clear using ints as hhmm!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T15:01:43.040", "Id": "220644", "ParentId": "220624", "Score": "1" } }, { "body": "<p>Kotlin version of @sharon-ben-asher answer:</p>\n<pre><code>fun LocalDateTime.isInTimeFrame(startHour: Int, startMinute: Int, endHour: Int, endMinute: Int): Boolean {\n val startHourMinute = startHour * 100 + startMinute\n val endHourMinute = endHour * 100 + endMinute\n\n val nowHourMinute: Int = hour * 100 + minute\n\n return if (startHourMinute &lt;= endHourMinute) {\n // if range within date - simple between boundaries check\n nowHourMinute in startHourMinute..endHourMinute\n } else {\n // else (cross date boundary range) - check if now date is either within range of yesterday or within range tomorrow\n nowHourMinute &gt;= startHourMinute || nowHourMinute &lt;= endHourMinute\n }\n }\n</code></pre>\n<p>And use it like this:</p>\n<pre><code>LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd HH:mm:ss&quot;)).isInTimeFrame(18,0,6,0)\n</code></pre>\n<p>Is DateTime between 18:00 - 06:00 ?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T10:32:14.177", "Id": "253612", "ParentId": "220624", "Score": "0" } } ]
{ "AcceptedAnswerId": "220644", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T10:31:07.367", "Id": "220624", "Score": "2", "Tags": [ "java", "jodatime" ], "Title": "Check if current time is within the timeframe using Joda-Time" }
220624
<p>Here is my <a href="https://en.wikipedia.org/wiki/Countdown_%28game_show%29" rel="nofollow noreferrer"><em>Countdown</em></a> word solver.</p> <p>This code aims to find all possible permutations of any length of a given input (which in the Countdown words game is any random assortment of letters). It then compares each permutation with the dictionary and prints it if it is a valid word. For example the letters "PHAYPC" could yield the following words (not limited to):</p> <ul> <li>Chap</li> <li>Happy</li> <li>Hay</li> </ul> <p>I've used the enchant library as my dictionary checker.</p> <pre><code>import itertools import enchant word = input("Please enter the letters or words to scramble: ") perm_words = itertools.chain.from_iterable(itertools.permutations(word, i) for i in range(3,len(word))) list_possible = [] list_words_print = [] for item in perm_words: list_possible.append("".join(item).lower()) dictionary = enchant.Dict("en_UK") for word in list_possible: if dictionary.check(word): if word not in list_words_print: list_words_print.append(word) print (list(item for item in list_words_print)) exit_key = input("Press any key to exit") </code></pre>
[]
[ { "body": "<p>Two suggestions for improvement. First, there's no need to keep track of all those possible words in a list <code>list_possible</code>. You could create and check them on the fly instead, saving memory and a bunch of append calls:</p>\n\n<pre><code>for item in perm_words:\n word = \"\".join(item).lower()\n if dictionary.check(word):\n if word not in list_words_print: \n list_words_print.append(word)\n</code></pre>\n\n<p><strong>EDIT</strong> There's a sneaky bug preventing this, as pointed out by OP. Due to <code>perm_words</code> generating the combinations with a length as determined by <code>range(3, len(word))</code>, <code>word</code> is not a variable that should be overwritten in this loop. Or, rename the user input.</p>\n\n<hr>\n\n<p>Second, having a list to keep the dictionary words in is unnecessarily slow. For every new word found, it's being compared to each word in that list. A faster option would be to store them in a set. Sets can't contain duplicates, so you could simply add each word without having to worry if you've seen it before:</p>\n\n<pre><code>found_words = set()\nfor item in perm_words:\n word = \"\".join(item).lower()\n if dictionary.check(word):\n found_words.add(word)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T13:47:53.303", "Id": "426301", "Score": "0", "body": "For some reason, including the word = \"\".join(item).lower() inside the for loop means that only 3-length combinations are printed. I have no idea as the original code worked perfectly and your improvement makes sense" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T14:03:54.110", "Id": "426307", "Score": "1", "body": "That's a neat bug! @EML See edit. Also, shouldn't it be `range(3, 1 + len(word))`? Without the +1 the code won't check for words using all characters." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T13:14:10.043", "Id": "220638", "ParentId": "220629", "Score": "3" } }, { "body": "<p>Generating all permutations is computationally expensive. For substrings of length <em>n</em>, there would be <em>n</em>! permutations. Note that 9! (which is 362880) likely exceeds the number of words in an English dictionary. Since you say that the input to your program may be of arbitrary length, checking the letter counts of each word in the dictionary would be a better strategy than generating all possible permutations, since it avoids pathological running times for large inputs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:46:34.340", "Id": "426349", "Score": "0", "body": "You mean reverse solve the problem by comparing every dictionary entry to the random assortment of letters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:27:15.017", "Id": "426360", "Score": "0", "body": "Yes. I've clarified my recommendation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:45:00.607", "Id": "220658", "ParentId": "220629", "Score": "3" } } ]
{ "AcceptedAnswerId": "220638", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T12:07:53.320", "Id": "220629", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Countdown - word solver" }
220629
<p>I am learning PHP 7 and decided to implement a simple FIFO singly-linked queue in it:</p> <pre><code>&lt;?php class QueueNode { var $item; var $next; function __construct($item) { $this-&gt;item = $item; } function get_item() { return $this-&gt;item; } } class Queue { var $head; var $tail; var $size; function push($item) { if ($this-&gt;size == 0) { $this-&gt;head = $this-&gt;tail = new QueueNode($item); } else { $new_node = new QueueNode($item); $this-&gt;tail-&gt;next = $new_node; $this-&gt;tail = $new_node; } $this-&gt;size++; } function pop() { if ($this-&gt;size == 0) { throw new Exception("Popping from an empty queue."); } $ret = $this-&gt;head-&gt;item; $this-&gt;head = $this-&gt;head-&gt;next; if (--$this-&gt;size == 0) { $this-&gt;head = $this-&gt;tail = null; } return $ret; } } $queue = new Queue(); for ($i = 1; $i &lt;= 10; $i++) { $queue-&gt;push($i); } for ($i = 1; $i &lt;= 10; $i++) { echo $queue-&gt;pop() . " "; } echo "&lt;br&gt;"; ?&gt; </code></pre> <p>As always, any critique is much appreciated.</p>
[]
[ { "body": "<h3>Getters and setters</h3>\n<p>So there is a getter for item (i.e. <code>get_item()</code>) - why not a getter (and setter) for the <code>next</code> property? If getters and setters are added, then those properties could be set to <code>private</code> visibility if deemed appropriate.</p>\n<p>Are you familiar with the <a href=\"https://www.php-fig.org/psr/\" rel=\"nofollow noreferrer\">PHP Standards Recommendations</a>? While it is only a suggestion, you might find them helpful for writing code that is maintainable and readable, not only for others but also your future self.</p>\n<p>According to <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a>:</p>\n<blockquote>\n<p>Method names MUST be declared in <code>camelCase()</code>.<sup><a href=\"https://www.php-fig.org/psr/psr-1/#43-methods\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<p>A format of <code>getItem()</code> is more widely used amongst many PHP developers.</p>\n<h3>Types and conditions</h3>\n<p>Inside <code>Queue::push()</code> and <code>Queue::pop()</code> I see this common first line:</p>\n<blockquote>\n<pre><code>if ($this-&gt;size == 0) {\n</code></pre>\n</blockquote>\n<p>It is advisable to use strict equality comparison operators (i.e. <code>===</code> and <code>!==</code>) to avoid excess type-juggling. As a consequence, <code>size</code> should perhaps be declared with a initial value of <code>0</code>.</p>\n<p>The conditional could also be shortened to <code>if (!$this-&gt;size) {</code> though that would allow any type that is considered to <strong><code>FALSE</code></strong> to allow the conditional block to be executed.</p>\n<h3>keyword <code>var</code></h3>\n<p><code>var</code> is a feature from PHP 4 and it isn't needed anymore<sup><a href=\"https://stackoverflow.com/a/1206120/1575353\">2</a></sup> - while it works as a synonym for <code>public</code> it is deprecated. If you adhere to <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2</a> then note it specifies:</p>\n<blockquote>\n<p>The <code>var</code> keyword MUST NOT be used to declare a property.<sup><a href=\"https://www.php-fig.org/psr/psr-2/#42-properties\" rel=\"nofollow noreferrer\">3</a></sup></p>\n</blockquote>\n<h3><code>for</code> loops</h3>\n<p>There isn't anything wrong with a traditional loop, but you could use the <a href=\"https://php.net/range\" rel=\"nofollow noreferrer\"><code>range()</code></a> function to iterate <code>$i</code> for you in a <code>foreach</code> loop:</p>\n<blockquote>\n<pre><code>for ($i = 1; $i &lt;= 10; $i++) {\n</code></pre>\n</blockquote>\n<p>can be changed to:</p>\n<pre><code>foreach(range(1, 10) as $i) {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:01:42.067", "Id": "220649", "ParentId": "220647", "Score": "3" } } ]
{ "AcceptedAnswerId": "220649", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T16:24:59.920", "Id": "220647", "Score": "3", "Tags": [ "php", "object-oriented", "linked-list", "queue" ], "Title": "Singly-linked queue in PHP 7" }
220647
<p>I got a C# class:</p> <pre><code>public class Agent { public string AgentId { set; get; } public double Longitude { set; get; } public double Latitude { set; get; } } </code></pre> <p>There are several agents in several different locations. During the program's lifetime, they can receive a call to another (latitude, longitude) point which is unknown during runtime. I got an API to calculate the distance in meters between their location and the given point. What I need eventually is to find the 5 closest agents to the given point.</p> <p>What I did in order to achieve this is adding another class:</p> <pre><code>public class AgentDistance : Agent, IComparable&lt;AgentDistance&gt; { public AgentDistance(Agent agent) { if(agent == null) { throw new Exception("Can't initalize agent with distance since agent is null"); } this.AgentId = agent.AgentId; this.Latitude = agent.Latitude; this.Longitude = agent.Longitude; } public double Distance { set; get; } public int CompareTo(AgentDistance other) { if(other == null) { return 1; } return Distance.CompareTo(other.Distance); } } </code></pre> <p>And the usage:</p> <pre><code>var agents = db.GetAgents(); if(agents == null || agents.Count == 0) { Console.WriteLine("No Results"); } List&lt;AgentDistance&gt; agentsWithDistance = new List&lt;AgentDistance&gt;(); foreach(Agent agent in agents) { double res = ws.GetDistanceMeters(agent.Latitude, agent.Longitude, customerLatitude, customerLongitude); agentsWithDistance.Add(new AgentDistance(agent) { Distance = res }); } agentsWithDistance.Sort(); for(int i = 0; i &lt; 5; i++) { Console.WriteLine(string.Format("agent_id: {0} distance: {1} m", agentsWithDistance[i].AgentId, agentsWithDistance[i].Distance)); } </code></pre> <p>It works, but is there a more elegant way to do it? I'm not sure if adding another class might be a bit redundant since all it does is just adding a property for sorting, but adding the distance property to the <code>Agent</code> class, doesn't make so much sense.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:01:15.223", "Id": "426436", "Score": "0", "body": "@KonradRudolph what do you mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:58:15.297", "Id": "426469", "Score": "0", "body": "Never mind, my mistake." } ]
[ { "body": "<p>I'd say you have the following options:</p>\n\n<ol>\n<li><strong>Keep that new class</strong> if you think it's relevant in your business. Here, it should be important to know if the logic of calculate the distance should be on that web service (I assume that 'ws' variable means that) or within your model (i.e., the 'Agent' class).</li>\n<li><strong>Use an anonymous class</strong> if you think you won't pass that info to another method.</li>\n<li><strong>Use a dictionary</strong> if you think it's not relevant in your business but will pass that info to another method.</li>\n</ol>\n\n<p>Personally, I'd go for the first one since it's the most natural to me. By the way, I'd use LINQ's OrderBy instead of implementing the IComparable interface; again, for expressiveness.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:08:43.340", "Id": "220664", "ParentId": "220650", "Score": "4" } }, { "body": "<blockquote>\n<pre><code>var agents = db.GetAgents();\nif(agents == null || agents.Count == 0)\n{\n Console.WriteLine(\"No Results\");\n}\n</code></pre>\n</blockquote>\n\n<p>You should exit your application/code block when you detect an invalid state. Here even if \"No Results\" is printed, the app will still run into a <code>NullReferenceException</code> or <code>IndexOutOfRangeException</code> in the next few steps. Also, talking of <code>IndexOutOfRangeException</code>, there is no check against if there is at least 5 agents in your db.</p>\n\n<p>Instead of creating an <code>IComparable</code>, you can just use linq to sort directly. But, since in your case, you also need to print out the distance (the value used for sorting), we will need to create an anonymous class to hold it:</p>\n\n<pre><code>var agents = db.GetAgents();\nif(agents == null || agents.Count == 0)\n{\n Console.WriteLine(\"No Results\");\n return;\n}\n\nvar nearestAgents = agents\n .Select(x =&gt; new \n {\n x.AgentId, \n DistanceToCustomer = ws.GetDistanceMeters(x.Latitude, x.Longitude, customerLatitude, customerLongitude) \n })\n .OrderBy(x =&gt; x.DistanceToCustomer);\nforeach (var agent in nearestAgents.Take(5))\n{\n Console.WriteLine($\"agent_id: {agent.AgentId} distance: {agent.DistanceToCustomer} m\");\n}\n</code></pre>\n\n<p>The <code>.Take(5)</code> ensures that only 5 agent will be printed out, or less.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:16:09.073", "Id": "426403", "Score": "1", "body": "The anonymous class doesn't need the `x.Latitude` and `x.Longitude` fields." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:09:12.247", "Id": "220665", "ParentId": "220650", "Score": "8" } }, { "body": "<p>I think, I would hold on to your decorator pattern because it is more reusable than the selection with anonymous objects.</p>\n\n<pre><code> public class DistancedAgent : Agent\n {\n public DistancedAgent(Agent source, double distance)\n {\n AgentId = source.AgentId;\n Latitude = source.Latitude;\n Longitude = source.Longitude;\n Distance = distance;\n }\n\n public double Distance { get; }\n\n public override string ToString()\n {\n return $\"{Latitude}, {Longitude} =&gt; {Distance}\";\n }\n }\n</code></pre>\n\n<p>You could extent <code>Agent</code> with some converter methods:</p>\n\n<pre><code>public static class Extensions\n{\n public static DistancedAgent WithDistance(this Agent agent, double distance)\n {\n return new DistancedAgent(agent, distance);\n }\n\n public static IEnumerable&lt;DistancedAgent&gt; WithDistance(this IEnumerable&lt;Agent&gt; agents, Func&lt;Agent, double&gt; getDistance)\n {\n return agents?.Where(a =&gt; a != null).Select(a =&gt; a.WithDistance(getDistance(a))) ?? new DistancedAgent[0];\n }\n\n public static IEnumerable&lt;DistancedAgent&gt; WithDistance(this IEnumerable&lt;Agent&gt; agents, IDistanceProvider distanceProvider)\n {\n return agents?.Where(a =&gt; a != null).Select(a =&gt; a.WithDistance(distanceProvider.GetDistance(a))) ?? new DistancedAgent[0];\n }\n}\n</code></pre>\n\n<p>where <code>IDistanceProvider</code> is</p>\n\n<pre><code> public interface IDistanceProvider\n {\n double GetDistance(Agent agent);\n }\n</code></pre>\n\n<hr>\n\n<p>In the concrete use case it ends up with code like this:</p>\n\n<pre><code> var agents = db.GetAgents();\n\n Func&lt;Agent, double&gt; getDistance = a =&gt; ws.GetDistanceMeters(a.Latitude, a.Longitude, customerLatitude, customerLongitude);\n\n foreach (DistancedAgent dAgent in agents.WithDistance(getDistance).OrderBy(da =&gt; da.Distance).Take(5))\n {\n Console.WriteLine(dAgent);\n }\n</code></pre>\n\n<p>which is easy to understand and maintain and you have a setup that can be used wherever needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T05:58:19.517", "Id": "220699", "ParentId": "220650", "Score": "0" } } ]
{ "AcceptedAnswerId": "220665", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:08:37.513", "Id": "220650", "Score": "6", "Tags": [ "c#", "sorting", "geospatial" ], "Title": "Finding the nearest agents to a customer using IComparable" }
220650
<p>I recently posted a <a href="/questions/220492/a-countdown-numbers-game-solver">solution for the numbers game</a> on the <a href="https://en.wikipedia.org/wiki/Countdown_%28game_show%29" rel="nofollow noreferrer"><em>Countdown</em> TV show</a> using a recursive technique. For those unfarmiliar with the rules…</p> <ul> <li>A fixed set of numbers (usually 6) are chosen at random</li> <li>A target value is set</li> <li>The player must reach the target value using some or all of the numbers from the list of 6 random numbers using only the operators +, *, - and /. The use of brackets is also permitted</li> </ul> <p>I have attached a new program that uses the itertools library and for loops. As with the last code the print statement</p> <ul> <li>"Eval..." means the program has used BODMAS (e.g: 1+3*10 = 31 as 10*3 = 30 and 30+1 = 31) whereas </li> <li>"Running sum..." produces a running sum of the totals (1+3*10 = 40 as 1+3 = 4, 4*10 = 40)</li> </ul> <pre><code>import itertools import re def unpack(method): string = method special = ["*","+","-","/"] list_sum = [] list_special = [] numbers = (re.findall(r"[\w']+", string)) for char in string: if char in special: list_special.append(char) for index in range (len(numbers)-1): to_eval = numbers[index] + list_special[index] + numbers[index+1] list_sum.append(f'{to_eval} = {eval(to_eval)}') numbers[index+1] = str(eval(to_eval)) return list_sum def plus (x,y): return x+y, "+" def minus (x,y): return x-y, "-" def times (x,y): return x*y, "*" def divide (x,y): return x/y, "/" def solve(): for numbers in list_sols: total = 0 running = "" list_to_call = [order_ops1,order_ops2,order_ops3,order_ops4,order_ops5,order_ops6] for operator in list_to_call[len(numbers)-2]: zipped = itertools.zip_longest(numbers, operator) to_calculate = (list(zipped)) running = "" total = 0 for (index,item) in enumerate(to_calculate): if index == 0: total += item[0] next_operator = item[1] running = str(item[0]) else: total, symbol = next_operator(total,item[0]) running += symbol + str(item[0]) if index &lt; len(numbers)-1: next_operator = item[1] if eval(running)==target: print(f"Eval: {running}") break if total == target: print (f'Running sum: {unpack(running)}') break def main(): global list_sols global order_ops1, order_ops2, order_ops3, order_ops4, order_ops5, order_ops6 global target numbers = [100,50,75,25,3,6] target = 952 list_sols = [] for number in itertools.chain.from_iterable(itertools.permutations(numbers,i) for i in range(2,7)): list_sols.append(list(number)) order_ops1,order_ops2,order_ops3,order_ops4,order_ops5,order_ops6 = [],[],[],[],[],[] for number in itertools.chain.from_iterable(itertools.product([plus,minus,times,divide],repeat=i) for i in range(1,6)): if len(number) ==1: order_ops1.append(list(number)) if len(number) ==2: order_ops2.append(list(number)) if len(number) ==3: order_ops3.append(list(number)) if len(number) ==4: order_ops4.append(list(number)) if len(number) ==5: order_ops5.append(list(number)) if len(number) ==6: order_ops6.append(list(number)) if target in numbers: print (target) return else: solve() return if __name__=="__main__": main() exit_key = input("Press any key to exit...") <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:26:04.577", "Id": "426339", "Score": "1", "body": "Why do you keep putting \"countdown\" in your question titles? What does that mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:34:45.810", "Id": "426343", "Score": "0", "body": "Its the name of a British TV game show (https://en.wikipedia.org/wiki/Countdown_(game_show)). I have tried solving the game show in different ways and thought it'd be nice to share the code with people in case they are working on a similar solution" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:21:38.543", "Id": "220652", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Countdown number game solution v2 using itertools" }
220652
<p>I have never posted to this forum, but was referred here. I need some help printing key iterations as well as optimizing my code for run time. If someone had some time to help/explain how to correct various parts, I would be much obliged. I am fairly new to R and trying to help out on a project.</p> <p>I am trying to run a bias-corrected percentile bootstrap for 3 different effect sizes. I heavily modified code from a colleague on a zero-truncated Poisson distribution to include bootstrapping for percentiles. While this code functions, the run time takes FAR too long. It takes about 3 days to do all of the 3 different effect sizes. At the end of the run, it only produces the last results for the last line and not anything in between. This is the real problem as I have the time. </p> <p>The console shows each of the 1000 iterations running which I do not need. Ideally, I would like to optimize run time. I would also like all of the outputs on the console or into a word/excel document rather than having to run them one at time. I would like for it to print the power of ab1, power of ab2, type I error of ab1 and type I error of ab2 for each of the seeds in each effect. Ideally, I would those 4 metrics broken down by effect and then again by seed within the effect. All these gathered in one place.</p> <p>I know the code is a bit clunky, and some help would be appreciated.</p> <p>I am fairly new to R, and was looking for some advice on how to proceed appropriately. The code is presented below:</p> <pre><code>library(pscl) library(boot) # RNG MODULE FOR TWO_PART HURDLE MODEL gen.hurdle = function(n, a, b1, b2, c1, c2, i0, i1, i2){ x = round(rnorm(n),3) e = rnorm(n) m = round(i0 + a*x + e, 3) lambda = exp(i1 + b1*m + c1*x) # PUT REGRESSION TERMS FOR THE CONTINUUM PART HERE; KEEP exp() ystar = qpois(runif(n, dpois(0, lambda), 1), lambda) # Zero-TRUNCATED POISSON DIST.; THE CONTINUUM PART z = i2 + b2*m + c2*x # PUT REGRESSION TERMS FOR THE BINARY PART HERE z_p = exp(z) / (1+exp(z)) # p(1) = 1-p(0) tstar = rbinom(n, 1, z_p) # BINOMIAL DIST. ; THE BINARY PART y= ystar*tstar # TWO-PART COUNT OUTCOME return(cbind(x,m,y,z,z_p,tstar)) } ################################################################################################## # MODEL ########################################################################################## ################################################################################################## # i=1 ################################### #small effect seed=51; n=50 ;a=.18; b=.16; c=.25; i=1 seed=53; n=100 ;a=.18; b=.16; c=.25; i=1 seed=55; n=200 ;a=.18; b=.16; c=.25; i=1 seed=57; n=300 ;a=.18; b=.16; c=.25; i=1 seed=58; n=500 ;a=.18; b=.16; c=.25; i=1 seed=59; n=1000;a=.18; b=.16; c=.25; i=1 #medium effect seed=61; n=50 ;a=.31; b=.35; c=.25; i=1 seed=63; n=100 ;a=.31; b=.35; c=.25; i=1 seed=65; n=200 ;a=.31; b=.35; c=.25; i=1 seed=67; n=300 ;a=.31; b=.35; c=.25; i=1 seed=68; n=500 ;a=.31; b=.35; c=.25; i=1 seed=69; n=1000;a=.31; b=.35; c=.25; i=1 #large effect seed=81; n=50 ;a=.52; b=.49; c=.25; i=1 seed=73; n=100 ;a=.52; b=.49; c=.25; i=1 seed=75; n=200 ;a=.52; b=.49; c=.25; i=1 seed=77; n=300 ;a=.52; b=.49; c=.25; i=1 seed=78; n=500 ;a=.52; b=.49; c=.25; i=1 seed=79; n=1000;a=.52; b=.49; c=.25; i=1 #model set.seed(seed) iterations = 1000 r = 1000 results = matrix(,iterations,4) for (iiii in 1:iterations){ data = data.frame(gen.hurdle(n, a, b, b, c, c, i, i, i)) data0 = data.frame(gen.hurdle(n, a, 0, 0, c, c, i, i, i)) p_0 =1-mean(data$z_p) p_0_hat =1-mean(data$tstar) p_0_b0 =1-mean(data0$z_p) p_0_hat_b0 =1-mean(data0$tstar) # power boot= matrix(,r,8) for(jjjj in 1:r){ #power fit1 = lm(m ~ x, data=data) fit2 = hurdle(formula = y ~ m + x, data=data, dist = "poisson", zero.dist = "binomial") a_hat = summary(fit1)$coef[2,1] b1_hat = summary(fit2)[[1]]$count[2,1] b2_hat = summary(fit2)[[1]]$zero[2,1] ab1_hat = prod(a_hat,b1_hat) ab2_hat = prod(a_hat,b2_hat) boot.data = data[sample(nrow(data), replace = TRUE), ] boot.data$y[1] = if(prod(boot.data$y) &gt; 0) 0 else boot.data$y[1] boot.fit1 = lm(m ~ x, data=boot.data) boot.fit2 = hurdle(formula = y ~ m + x, data=boot.data, dist = "poisson", zero.dist = "binomial") boot.a = summary(boot.fit1)$coef[2,1] boot.b1 = summary(boot.fit2)[[1]]$count[2,1] boot.b2 = summary(boot.fit2)[[1]]$zero[2,1] boot.ab1 = prod(boot.a,boot.b1) boot.ab2 = prod(boot.a,boot.b2) #type I error fit3 = lm(m ~ x, data=data0) fit4 = hurdle(formula = y ~ m + x, data=data0, dist = "poisson", zero.dist = "binomial") a_hat_b0 = summary(fit3)$coef[2,1] b1_hat_b0 = summary(fit4)[[1]]$count[2,1] b2_hat_b0 = summary(fit4)[[1]]$zero[2,1] ab1_hat_b0 = prod(a_hat_b0,b1_hat_b0) ab2_hat_b0 = prod(a_hat_b0,b2_hat_b0) boot.data0 = data0[sample(nrow(data0), replace = TRUE), ] boot.data0$y[1] = if(prod(boot.data0$y) &gt; 0) 0 else boot.data0$y[1] boot.fit3 = lm(m ~ x, data=boot.data0) boot.fit4 = hurdle(formula = y ~ m + x, data=boot.data0, dist = "poisson", zero.dist = "binomial") boot.a_b0 = summary(boot.fit3)$coef[2,1] boot.b1_b0 = summary(boot.fit4)[[1]]$count[2,1] boot.b2_b0 = summary(boot.fit4)[[1]]$zero[2,1] boot.ab1_b0 = prod(boot.a_b0,boot.b1_b0) boot.ab2_b0 = prod(boot.a_b0,boot.b2_b0) boot[jjjj,] = c(ab1_hat, ab2_hat, boot.ab1, boot.ab2, ab1_hat_b0, ab2_hat_b0, boot.ab1_b0, boot.ab2_b0) } z0.1 = qnorm((sum(boot[,3] &gt; boot[,1])+sum(boot[,3]==boot[,1])/2)/r) z0.2 = qnorm((sum(boot[,4] &gt; boot[,2])+sum(boot[,4]==boot[,2])/2)/r) z0.1_b0 = qnorm((sum(boot[,7] &gt; boot[,5])+sum(boot[,7]==boot[,5])/2)/r) z0.2_b0 = qnorm((sum(boot[,8] &gt; boot[,6])+sum(boot[,8]==boot[,6])/2)/r) alpha=0.05 # 95% limits z=qnorm(c(alpha/2,1-alpha/2)) # Std. norm. limits p1 = pnorm(z-2*z0.1) # bias-correct &amp; convert to proportions p2 = pnorm(z-2*z0.2) p1_b0 = pnorm(z-2*z0.1_b0) p2_b0 = pnorm(z-2*z0.2_b0) ci1 = quantile(boot[,3],p=p1) # Bias-corrected percentile lims ci2 = quantile(boot[,4],p=p2) ci1_b0 = quantile(boot[,7],p=p1_b0) ci2_b0 = quantile(boot[,8],p=p2_b0) sig.ab1 = if(prod(ci1) &gt; 0) 1 else 0 sig.ab2 = if(prod(ci2) &gt; 0) 1 else 0 sig.ab1_b0 = if(prod(ci1_b0) &gt; 0) 1 else 0 sig.ab2_b0 = if(prod(ci2_b0) &gt; 0) 1 else 0 #results results[iiii,] = c(sig.ab1, sig.ab2, sig.ab1_b0, sig.ab2_b0) message(paste0(iiii, " / iterations")) flush.console() } i n a b iterations #bootstrap how many r #power of ab1 mean(results[,1]) #power of ab2 mean(results[,2]) #type I error of ab1 mean(results[,3]) #type I error of ab2 mean(results[,4]) </code></pre> <p>It would seem to me that the problem with each of the effects being ran separately is coming from naming the results "results" for each loop. I do not know the best way to print each metric(for each effect size) without disturbing the loop. Alternatively, I could aggregate them into one chart as mentioned before.</p> <p>The length is obviously coming from the sheer amount of iterations and lack of RAM to process them fast enough. Is this something that can even been remedied? The time isn't nearly as much of a concern as not getting results for all effect sizes when the program is run.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:04:30.430", "Id": "426354", "Score": "0", "body": "Welcome to Code Review! You have to be the author of the code to get it reviewed. You can read more about that in the Help Center at [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:07:58.847", "Id": "426356", "Score": "0", "body": "@AlexV Hi! Thank you for pointing out that rule breach. I made some major changes to the code as it originally was just code for zero-truncated poisson distribution which I modified for bootstrapping. Is this permissible? I can reflect that in the message." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:12:50.673", "Id": "426357", "Score": "0", "body": "I personally would consider your question valid under these circumstances. You should definitely reflect that in your question!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:15:59.537", "Id": "426359", "Score": "0", "body": "Thank you, I will do that now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T23:38:59.187", "Id": "426389", "Score": "0", "body": "In a nutshell, the code is executed from top to bottom, so of all the lines looking like `seed=51; n=50 ;a=.18; b=.16; c=.25; i=1` will be immediately overridden by the one below and only the values in the last such line will enter the double `for` loop model. You need to write a function that takes `seed`, `n`, `a`, `b`, `c`, and `i` as inputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:19:31.500", "Id": "426474", "Score": "0", "body": "@flodel Thank you! I suspected as much. I think it may even be refitting the same data 1000 times for each of the 1000 data sets randomly generated from the 1 seed (the last one since there's nothing looping through the list)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:27:44.227", "Id": "220654", "Score": "2", "Tags": [ "beginner", "time-limit-exceeded", "statistics", "r" ], "Title": "Bias-corrected percentile Bootstrapping Optimization" }
220654
<p>I am trying to implement Dijkstra algorithm. I try to calculate cost of reaching every node from first node. Though I have tried with couple of graphs and results are correct but I have one doubt which leads me to think that something is wrong with my implementation. Here is my implementation</p> <pre><code>private int[] findShortestPathBetween(int[][] graph, int src) { int[] result = new int[graph.length]; for (int i = 0 ; i &lt; result.length ; i++) { result[i] = Integer.MAX_VALUE; } result[src] = 0; boolean[] visited = new boolean[graph.length]; int i = 0; while (true) { for (int kk = 0 ; kk &lt; graph.length ; kk++) { if (graph[i][kk] != 0 ) { // edge between nodes exists int previousCost = result[i]; if (previousCost == Integer.MAX_VALUE) { previousCost = 0; } int newCost = previousCost + graph[i][kk]; newCost = Math.min(newCost, result[kk]); if (newCost != result[kk]) { visited[kk] = false; //weight of visited node changed, remove it from visited nodes. } result[kk] = newCost; } } visited[i] = true; int nextNode = -1; int nextNodeCost = Integer.MAX_VALUE; for (int k = 0 ; k &lt; graph.length ; k++) { if (!visited[k]) { nextNode = k; break; } } if (nextNode == -1) { break; } i = nextNode; } return result; } </code></pre> <p>I think line containing following code should not be required.</p> <pre><code>visited[kk] = false; </code></pre> <p>Here I am marking an already visited node as not visited if its cost has changed. Not doing this gives wrong results. As per my understanding this should not be required because if a node has been marked visited it should never be visited again.</p> <p>I am trying to implement Dijkstra without using any queue (using queue is 2nd part of my implementation).</p> <p>Please check and confirm whether my implementation has any gaps or this is expected when we are not using queue to implement Dijkstra algorithm.</p> <p>Assumptions: I have used 2D array to represent my graph. If edge exist between 2 nodes corresponding entry in array is non-zero and if edge does not exist corresponding entry contains 0.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:37:12.443", "Id": "426444", "Score": "0", "body": "Can you provide the test graphs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T02:00:17.000", "Id": "426815", "Score": "0", "body": "String expected = \"[0, 3, 2, 4]\";\n int[][] graph = new int[][]{{0, 5, 2, 0},\n {5, 0, 1, 1},\n {2, 1, 0, 7},\n {0, 1, 7, 0},\n };" } ]
[ { "body": "<p>The graph is actually an adjacency graph. This is a much better name than <code>graph</code> to avoid people confusing it with a grid of nodes.</p>\n\n<p>The next node should be the unvisited node with the lowest cost.</p>\n\n<pre><code>for (int k = 0 ; k &lt; graph.length ; k++) {\n if (!visited[k] &amp;&amp; result[k] &lt; nextNodeCost) {\n nextNode = k;\n nextNodeCost = result[k];\n }\n}\n</code></pre>\n\n<p>This way you avoid needing to visit nodes multiple times because you will then never change a visited node's cost.</p>\n\n<p>The result array should be initialized with <code>result[0] = 0;</code> then you can remove the check in the for loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T09:57:45.900", "Id": "220710", "ParentId": "220659", "Score": "1" } } ]
{ "AcceptedAnswerId": "220710", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T17:46:10.987", "Id": "220659", "Score": "1", "Tags": [ "java", "algorithm", "pathfinding" ], "Title": "Implementation of Dijkstra algorithm" }
220659
<p>I'm making a puzzle game in Unity with sprite-based graphics. When the game is paused, I want to hide most game elements, because I don't want the player to be able to pause and leisurely think about their next move.</p> <p>I <em>could</em> just make the sprites invisible, but I decided to do something more stylish; render sprites with pseudo-glitches, simulated in this shader:</p> <pre><code>Shader "Sprites/Glitch Sprite" { Properties { [NoScaleOffset] _MainTex ("Sprite Atlas", 2D) = "white" {} [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0 [HideInInspector] _Flip ("Flip", Vector) = (1,1,1,1) [PerRendererData] _TextureRect ("Base Texture Rect", Vector) = (0, 0, 0, 0) // The position and size of this sprite on the original texture atlas } SubShader { Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" "CanUseSpriteAtlas"="True" } Cull Off Lighting Off ZWrite Off Blend One OneMinusSrcAlpha Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma target 3.0 #pragma multi_compile_instancing #pragma multi_compile _ PIXELSNAP_ON #pragma multi_compile _ ETC1_EXTERNAL_ALPHA #pragma instancing_options assumeuniformscaling // Sprites will not scale in my game #pragma instancing_options nolightmap #pragma instancing_options nolightprobe // My game does not use lighting (it's all pixel art) #include "UnitySprites.cginc" UNITY_INSTANCING_BUFFER_START(Props) UNITY_DEFINE_INSTANCED_PROP(float4, _TextureRect) // Sprites are GPU-instanced where supported UNITY_INSTANCING_BUFFER_END(Props) // These four properties are set once, when the game is first loaded uniform float4 _MainTex_TexelSize; uniform float2 _InitialSeed; uniform float4 _SpriteRectChunks[128]; // Coordinates of each 8x8 sprite chunk I want to use in the shader // x,y are the positions (in pixels) of the chunk on the original atlas, z,w are unused and set to 0 uniform int _SpriteRectChunkCount = 0; // Not all of these vectors are used, so I also pass in how many actually are struct vert2frag_img { float4 pos : SV_POSITION; half2 uv : TEXCOORD0; nointerpolation float4 chunk : POSITION1; // The chunk selection is done in the vertex shader UNITY_VERTEX_INPUT_INSTANCE_ID UNITY_VERTEX_OUTPUT_STEREO }; // Taken from https://stackoverflow.com/a/3451607/1089957 float2 remap(float2 value, float2 low1, float2 high1, float2 low2, float2 high2) { return low2 + (value - low1) * (high2 - low2) / (high1 - low1); } // Given a vec2 as a seed, return a number from [0, 1) // Taken from https://stackoverflow.com/a/10625698/1089957 float random(float2 seed) { const float2 r = float2( 23.1406926327792690, 2.6651441426902251 ); return frac(cos(fmod(123456789., 1e-7 + 256. * dot(seed, r)))); } int random(float2 seed, int limit) { return (int)round(random(seed) * limit); } vert2frag_img vert(appdata_img IN) { vert2frag_img OUT; UNITY_SETUP_INSTANCE_ID(IN); UNITY_TRANSFER_INSTANCE_ID(IN, OUT); UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT); OUT.pos = UnityFlipSprite(IN.vertex, _Flip); OUT.pos = UnityObjectToClipPos(OUT.pos); OUT.uv = IN.texcoord; float2 position = mul(unity_ObjectToWorld, float4(0, 0, 0, 1)).xy; #ifdef UNITY_INSTANCING_ENABLED int index = random(round(position * _InitialSeed * 8 + UNITY_GET_INSTANCE_ID(IN)), _SpriteRectChunkCount); #else int index = random(round(position * _InitialSeed * 8), _SpriteRectChunkCount); #endif OUT.chunk = _SpriteRectChunks[index]; #ifdef PIXELSNAP_ON OUT.pos = UnityPixelSnap(OUT.pos); #endif return OUT; } fixed4 frag(vert2frag_img IN) : SV_Target { UNITY_SETUP_INSTANCE_ID(IN); float2 pixels = remap(IN.uv, 0, 1, 0, _MainTex_TexelSize.zw); // texture coords (range [0, 1]) -&gt; texture pixels (range [0, TextureSize]) pixels = pixels - UNITY_ACCESS_INSTANCED_PROP(Props, _TextureRect).xy; // Sprite pixel coordinate, relative to (0, 0) pixels = fmod(pixels, 8); // Display glitched sprites in 8x8 chunks pixels = pixels + IN.chunk.xy; // Back to the sprite pixels = remap(pixels, 0, _MainTex_TexelSize.zw, 0, 1); // Remap to normalized coordinates fixed4 c = tex2D(_MainTex, clamp(pixels, 0, 1)); c.rgb *= c.a; return c; } ENDCG } } } </code></pre> <p>There's a lot of window dressing, but the actual shader code in the <code>CGPROGRAM</code> block is standard HLSL. This is a screenshot of my game <strong>without</strong> this shader:</p> <p><a href="https://i.stack.imgur.com/Ue7M2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ue7M2.png" alt="Screenshot, no shader"></a></p> <p>And this is the same scene, <strong>with</strong> the shader:</p> <p><a href="https://i.stack.imgur.com/wYJaB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wYJaB.png" alt="Screenshot, with shader"></a></p> <p>Here are some relevant facts:</p> <ul> <li>All sprites are stored on a single texture atlas.</li> <li>All sprites have a length and width that are a multiple of 8. But their position on the texture atlas might not be.</li> <li>Some sprites in the second screenshot are invisible, even though they should be glitchy like the ones that are. While this is <em>technically</em> a bug, it's consistent with the style I'm going for, so I will probably leave it as is. If you happen to have a fix to suggest, I'll try it out and see how it looks, <em>but that's not the basis of my question.</em></li> <li>I intend to release this game on a variety of platforms, so make no assumptions about what graphics API (DirectX, OpenGL, etc.) is actually being used. However, this shader will always be written in HLSL (Unity compiles it to other languages as needed).</li> </ul> <p><strong>These are my questions:</strong></p> <ul> <li>Are there ways I can optimize this shader?</li> </ul> <p>I'm looking for changes I can make in either the actual HLSL code or the surrounding ShaderLab declarations.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:06:55.257", "Id": "220662", "Score": "7", "Tags": [ "c#", "performance", "graphics", "unity3d", "portability" ], "Title": "Unity3D shader for rendering 2D sprites with a pseudo-glitch effect" }
220662
<h3>1. Backstory</h3> <p>I recently starting programming and I found out that Entity Framework works perfect for my small-sized applications due its simplicity.</p> <p>I've made my custom authorize attribute for MVC controllers and controller methods to check if the current user has a certain role (which is an enum type in my case).</p> <p>The following code represents my authorize attribute:</p> <pre><code>public class HasRoleAttribute : ActionFilterAttribute { private Role _role; public HasRoleAttribute(Role role) { this._role = role; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var context = new FactoryManagementContext(); var userName = filterContext.HttpContext.User.Identity.Name; var user = context.Users.FirstOrDefault(item =&gt; item.UserName == userName); var hasRole = user.Role == _role; if (user == null || !hasRole) { // If this user does not have the // required permission then redirect to login page var url = new UrlHelper(filterContext.RequestContext); var loginUrl = url.Content("/Account/Login"); filterContext.HttpContext.Response.Redirect(loginUrl, true); } } } public enum Role { Engineer, Manager, Admin } </code></pre> <h3>2. Question</h3> <p>It works as a charm, but I have only one question: is it necessary to initialize the database context every single time when authorizing a user?</p>
[]
[ { "body": "<p>You should not instanciate a new DbContext each time your code go throw your ActionFilter. <br> What you should do is to use <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\"><strong>dependency injection</strong></a> and to define an execution scope.\n<br><br>\nBecause you are using .net Framework and not .net core, I advise you to look into DI providers such as <a href=\"https://autofac.org/\" rel=\"nofollow noreferrer\">Autofac</a> or <a href=\"https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html\" rel=\"nofollow noreferrer\">Ninject</a>.\n<br><br>\nI advise you to look into <a href=\"https://en.wikipedia.org/wiki/Dependency_injection#Advantages\" rel=\"nofollow noreferrer\">why to use DI</a> and think about what execution scope you need (probably <code>perScope()</code> in your case).</p>\n\n<p>Hope it helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T09:38:04.703", "Id": "220709", "ParentId": "220666", "Score": "1" } } ]
{ "AcceptedAnswerId": "220709", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T18:12:39.823", "Id": "220666", "Score": "1", "Tags": [ "c#", "entity-framework", "asp.net-mvc" ], "Title": "Authorization using Entity Framework in ASP.NET MVC" }
220666
<p>This is my library class. This does not have any issues but I want to know if I have any mistakes, or ways to improve performance:</p> <p>variable and call (example of <code>SELECT</code>):</p> <pre><code>include(class_dbmanager.php) $this-&gt;DBMANAGER = new Class_DbManager(); $Query['DatabaseName'] = "SELECT user FROM table_user WHERE unsername='" . $username . "';"; $BDResult = $this-&gt;DBMANAGER-&gt;GetData($Query); </code></pre> <p>variable and call (example of <code>INSERT/UPDATE</code>):</p> <pre><code>$Query['DatabaseName'][] = "INSERT INTO Tbl_Sys_Usuarios(IdTUser, Username, Password, Email) VALUES ('$IdTUser', '$Username', '$Password', '$Email');"; $BDResult = $this-&gt;DBMANAGER-&gt;InsertData($Query); </code></pre> <p>The library:</p> <pre><code>&lt;?php class Class_DbManager { //for select //$Query is array with database index and query string //$Conf is secundary conection data public function GetData($Query, $Conf = '') { try { $DB_R = []; $DB = []; $val = []; $prefix = ''; $count = 0; if (USEPREFIX == True) { $prefix = DB_PRE; //prefix DB } reset($Query); $DB_2USE = key($Query); //Conecction. i use defined const... $conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . $prefix . "" . DBSYS . "", DB_USER, DB_PASS); //secundary Connection if (isset($Conf['CONF']['ChangeServ'])) { if ($Conf['CONF']['ChangeServ'] == true) { $conn = new PDO("mysql:host=" . $Conf['CONF']['DB_HOST'] . ";dbname=" . $Conf['CONF']['PREFIX2USE'] . "" . $Conf['CONF']['DB2USE'] . "", $Query['CONF']['DB_USER'], $Query['CONF']['DB_PASS']); } } $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn-&gt;exec("set names utf8"); $conn-&gt;exec('USE ' . $DB_2USE); //execution query. $DB_R['r'] = $conn-&gt;query($Query[$DB_2USE], PDO::FETCH_ASSOC); $count = $DB_R['r']-&gt;rowCount(); $DB_R['c'] = $count; if ($count == 0) { $DB_R['r'] = null; } elseif ($count == 1) { $DB_R['r'] = $DB_R['r']-&gt;fetch(); //Fetch result i f result is 1 if not resturn the result unfetch } $conn = null; return $DB_R; } catch (PDOException $e) { echo '&lt;pre&gt;'; echo var_dump($e); echo '&lt;pre&gt;'; } } //for Update and Insert //$Query is array with database index and query string //$Conf is secundary conection data public function UpdateData($Query, $Conf = '') { try { $DB_R = []; $DB = []; $val = []; $prefix = ''; $cT = 0; if (USEPREFIX == True) { $prefix = DB_PRE; } $conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . $prefix . "" . DBSYS . "", DB_USER, DB_PASS); if (isset($Conf['CONF']['ChangeServ'])) { if ($Conf['CONF']['ChangeServ'] == true) { $conn = new PDO("mysql:host=" . $Conf['CONF']['DB_HOST'] . ";dbname=" . $Conf['CONF']['PREFIX2USE'] . "" . $Conf['CONF']['DB2USE'] . "", $Query['CONF']['DB_USER'], $Query['CONF']['DB_PASS']); } } $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn-&gt;beginTransaction(); $conn-&gt;exec("set names utf8"); foreach ($Query as $DB_2USE =&gt; $QArr) { $conn-&gt;exec('USE ' . $DB_2USE); foreach ($QArr as $key =&gt; $QString) { $conn-&gt;exec($QString); $cT++; } } $conn-&gt;commit(); $conn = null; $DB_R['r'] = true; return $DB_R; } catch (PDOException $e) { #rollback al autoincrement $conn-&gt;rollback(); $conn-&gt;beginTransaction(); $conn-&gt;exec("set names utf8"); foreach ($Query as $DB_2USE =&gt; $QArr) { $conn-&gt;exec('USE ' . $DB_2USE); foreach ($QArr as $key =&gt; $QString) { preg_match('/\binto\b\s*(\w+)/i', $QString, $tables); $conn-&gt;exec("ALTER TABLE " . $tables[1] . " AUTO_INCREMENT=1;"); } } $conn-&gt;commit(); echo '&lt;pre&gt;'; echo var_dump($e); echo '&lt;pre&gt;'; } } //for Insert //$Query is array with database index and query string //$Conf is secundary conection data public function InsertData($Query, $Conf = '') { try { $DB_R = []; $DB = []; $val = []; $prefix = ''; $cT = 0; if (USEPREFIX == True) { $prefix = DB_PRE; } $conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . $prefix . "" . DBSYS . "", DB_USER, DB_PASS); if (isset($Conf['CONF']['ChangeServ'])) { if ($Conf['CONF']['ChangeServ'] == true) { $conn = new PDO("mysql:host=" . $Conf['CONF']['DB_HOST'] . ";dbname=" . $Conf['CONF']['PREFIX2USE'] . "" . $Conf['CONF']['DB2USE'] . "", $Query['CONF']['DB_USER'], $Query['CONF']['DB_PASS']); } } $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn-&gt;beginTransaction(); $conn-&gt;exec("set names utf8"); foreach ($Query as $DB_2USE =&gt; $QArr) { $conn-&gt;exec('USE ' . $DB_2USE); foreach ($QArr as $key =&gt; $QString) { $conn-&gt;exec($QString); $cT++; } } $conn-&gt;commit(); $conn = null; $DB_R['r'] = true; return $DB_R; } catch (PDOException $e) { #rollback al autoincrement $conn-&gt;rollback(); $conn-&gt;beginTransaction(); $conn-&gt;exec("set names utf8"); foreach ($Query as $DB_2USE =&gt; $QArr) { $conn-&gt;exec('USE ' . $DB_2USE); foreach ($QArr as $key =&gt; $QString) { preg_match('/\binto\b\s*(\w+)/i', $QString, $tables); $conn-&gt;exec("ALTER TABLE " . $tables[1] . " AUTO_INCREMENT=1;"); } } $conn-&gt;commit(); echo '&lt;pre&gt;'; echo var_dump($e); echo '&lt;pre&gt;'; } } //for delete //$Query is array with database index and query string //$Conf is secundary conection data public function DeleteData($Query, $Conf = '') { try { $DB_R = []; $DB = []; $val = []; $prefix = ''; $cT = 0; if (USEPREFIX == True) { $prefix = DB_PRE; } $conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . $prefix . "" . DBSYS . "", DB_USER, DB_PASS); if (isset($Conf['CONF']['ChangeServ'])) { if ($Conf['CONF']['ChangeServ'] == true) { $conn = new PDO("mysql:host=" . $Conf['CONF']['DB_HOST'] . ";dbname=" . $Conf['CONF']['PREFIX2USE'] . "" . $Conf['CONF']['DB2USE'] . "", $Query['CONF']['DB_USER'], $Query['CONF']['DB_PASS']); } } $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn-&gt;beginTransaction(); $conn-&gt;exec("set names utf8"); foreach ($Query as $DB_2USE =&gt; $QArr) { $conn-&gt;exec('USE ' . $DB_2USE); foreach ($QArr as $key =&gt; $QString) { $conn-&gt;exec($QString); $cT++; } } $conn-&gt;commit(); $conn = null; $DB_R['r'] = true; return $DB_R; } catch (PDOException $e) { #rollback al autoincrement $conn-&gt;rollback(); $conn-&gt;beginTransaction(); $conn-&gt;exec("set names utf8"); foreach ($Query as $DB_2USE =&gt; $QArr) { $conn-&gt;exec('USE ' . $DB_2USE); foreach ($QArr as $key =&gt; $QString) { preg_match('/\binto\b\s*(\w+)/i', $QString, $tables); $conn-&gt;exec("ALTER TABLE " . $tables[1] . " AUTO_INCREMENT=1;"); } } $conn-&gt;commit(); echo '&lt;pre&gt;'; echo var_dump($e); echo '&lt;pre&gt;'; } } } </code></pre> <p><strong>i think add the compatibility for prepared statement but have this issues building the query string:</strong></p> <pre><code>&lt;?php //perm analisis simulated create array. $queryArr = []; $perms = []; $perms['p-001'] = array(0, 1, 1, 1, 0); $perms['p-002'] = array(0, 1, 1, 0, 1); $perms['p-003'] = array(1, 1, 0, 1, 1); $perms['p-004'] = array(1, 0, 1, 1, 1); //query String build foreach ($perms as $index =&gt; $arrayperms) { if ($arrayperms[0] == 1) { //insert $query = "INSERT INTO tb_perms_user(Id_Proccess,create,read,update,delete)value('$index'," . $arrayperms[1] . "," . $arrayperms[2] . "," . $arrayperms[3] . "," . $arrayperms[4] . ");"; } else { //update $query = "UPDATE tb_perms_user SET create=" . $arrayperms[1] . ",read=" . $arrayperms[2] . ",update=" . $arrayperms[3] . ",delete=" . $arrayperms[1] . " WHERE Id_Proccess='$index';"; } $queryArr['databasename'][] = $query; } echo '&lt;pre&gt;'; echo var_dump($queryArr); echo '&lt;/pre&gt;'; </code></pre> <p>When i run the script like this:</p> <pre><code>$BDResult = $this-&gt;DBMANAGER-&gt;InsertData($queryArr); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T19:56:00.000", "Id": "426372", "Score": "2", "body": "I already have a review for the most of issues in your class. Some time ago I wrote an article about [common mistakes in database wrappers](https://phpdelusions.net/pdo/common_mistakes). Sadly, but your library has almost all of them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T20:27:36.607", "Id": "426375", "Score": "0", "body": "@YourCommonSense Thanks, I will be doing a revision and adjustments to improve the library." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T21:12:53.150", "Id": "426378", "Score": "1", "body": "I'm not convinced that your example calls work, considering that they populate `$Query` in different ways." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T21:16:50.873", "Id": "426379", "Score": "1", "body": "@200_success $Query populate is diferent betwhen select to insert/Update/delete, becouse you only can execute a select query statement at a time, but i can pass much more that 1 query in insert/update/delete statement.... becouse it $query have 2 build method... single array for select, and 2 dimension array for insert/update/delete" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T07:22:03.020", "Id": "426420", "Score": "0", "body": "What is the point of `\"ALTER TABLE \" . $tables[1] . \" AUTO_INCREMENT=1;\"` query? it looks extremely suspicious. Looks like you are shooting yourself in the foot here. Did you actually try this code on a real database? Was it able to work further afterwards?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T21:00:17.017", "Id": "427552", "Score": "0", "body": "because $conn->rollback(); not restore de auto-increment." } ]
[ { "body": "<p>For some of your class' issues I have a review already. Some time ago I wrote an article about <a href=\"https://phpdelusions.net/pdo/common_mistakes\" rel=\"nofollow noreferrer\">common mistakes in database wrappers</a>. </p>\n\n<p>To list them briefly, </p>\n\n<ul>\n<li>the most grave problem, <strong>no support for prepared statements</strong>. In 2019 it cannot be excused. It's like starting your own bank and storing the money on the backyard. You will go bankrupt yourself and ruin your clients' money. Your query array must accept a query with placeholders and an array with data for them.</li>\n<li>error reporting. <code>echo var_dump($e);</code> <strong>is definitely not</strong> the way errors should be reported. Instead of catching PDO exceptions just leave them be.</li>\n<li>Connection is made every time anew which is also bad. If you have to work wth different connections, then write a distinct method that creates different connections on demand and holds them during the script execution, returning the same connection every time it is requested. </li>\n</ul>\n\n<p>There are other issues as well.</p>\n\n<p>The most evident one is the code duplication, <em>on so many levels</em></p>\n\n<ul>\n<li>The code in InsertData, UpdateData, DeleteData is identical. Why use that many functions if you can use just one? </li>\n<li>And even if you want separate functions, why duplicate so much code every time? Create a generic method that contains all the common code and then call it inside other methods. </li>\n<li>and some code is duplicated within functions without any apparent reason. Why you are calling the SET NAMES query so many times? the charset should be set only once (and it must be done in the DSN, not in the query call).</li>\n</ul>\n\n<p>The code in the catch part for a transaction looks VERY strange. I suppose it is written out of some incorrect notion. <strong>There is not a single reason to reset the autoincrement</strong>, least it should be done for a failed transaction. Make your code for catch just this way</p>\n\n<pre><code> } catch (PDOException $e) {\n $conn-&gt;rollback();\n throw $e;\n }\n</code></pre>\n\n<p>and leave autoincrement alone.</p>\n\n<p>the way you are using GetData() is rather strange. Why you are selecting the first row from the resultset? What if your code would expect several rows to be iterated over, but for the moment only one returned? </p>\n\n<p>Let me suggest another code for this function</p>\n\n<pre><code>public function getData($db2use, $query, $data = [], $Conf = [])\n{\n // all the connection related stuff should go into a dedicated method\n $conn = $this-&gt;connection($db2use, $conf = []);\n $stmt = $conn-&gt;prepare($query);\n $stmt-&gt;execute($data);\n return $stmt;\n}\n</code></pre>\n\n<p>with this simple function you will be able to get everything you want from the query and even more. for example,</p>\n\n<pre><code>$query = \"SELECT user FROM table_user WHERE unsername=?\";\n$user = $this-&gt;db-&gt;GetData('DatabaseName', $query, [$username])-&gt;fetchColumn();\n</code></pre>\n\n<p>the code is much simpler, both in the function and in the application and at the same time it is more flexible, for example it lets you use various fetch methods offered by PDO</p>\n\n<p>To perform multuple queries in a transaction, have a distinct method that accepts an array of arrays each of the following structure</p>\n\n<pre><code>$queries = [\n [\n 'query' =&gt; \"INSERT INTO table1 VALUES (null, ?,?,?)\";\n 'params' =&gt; [\n [$name, $position, $salary],\n ],\n ],\n [\n 'query' =&gt; \"UPDATE table2 SET category=? where id=?\";\n 'params' =&gt; [\n [$category1, $id1],\n [$category2, $id2],\n [$category3, $id3],\n ],\n ],\n];\n</code></pre>\n\n<p>then you will be able to loop over queries and for each it will be possible to execute multiple sets of parameters, like this (based on the code from my <a href=\"https://phpdelusions.net/pdo_examples/insert\" rel=\"nofollow noreferrer\">multiple query execution example</a>)</p>\n\n<pre><code>try {\n $conn = $this-&gt;connection($db2use, $conf = []);\n $conn-&gt;beginTransaction();\n foreach ($queries as $one)\n {\n $stmt = $conn-&gt;prepare($one['query']);\n foreach ($one['params'] as $params)\n $stmt-&gt;execute($params);\n }\n }\n $conn-&gt;commit();\n}catch (Exception $e){\n $pdo-&gt;rollback();\n throw $e;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:40:42.883", "Id": "426478", "Score": "0", "body": "thank you for response How would it be if I need to use internal junctions (inner joins) or nest select from different tables ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:41:39.897", "Id": "426479", "Score": "0", "body": "I'm not very familiar with the prepared statement... zorry..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:48:31.120", "Id": "426480", "Score": "0", "body": "The result of the query with JOIN is exactly the same, a database class has nothing to do with it. And for the prepared statements there is nothing complicated, you may check it here, https://phpdelusions.net/pdo#prepared" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:53:50.530", "Id": "426482", "Score": "0", "body": "I have another question; this [$ username] is an array or what ?, I would like to pass a single data and not a very large structure [$username, $var1, $var2, $var3, $var4, $var5]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:58:23.097", "Id": "426483", "Score": "0", "body": "Yes, this is an array. Yes, you want to pass a structure if you want use all these variables in the query. There is nothing big, however. You are already sending all these variables in the query. So just send them separately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T14:03:50.047", "Id": "426485", "Score": "0", "body": "thank you very much I will be reviewing the code, the point of the try / catch of the error, it is merely to personalize the error output by screen; actually where is the echo var_dump ($ e); I usually use a specific function to generate a personalized log and a counting output for non-programmers, mainly for testing and quality." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T14:06:48.870", "Id": "426487", "Score": "0", "body": "You can personalize the error messages without try catch. Please kindly refer to this article, [PHP error reporting](https://phpdelusions.net/articles/error_reporting)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T14:16:21.363", "Id": "426488", "Score": "0", "body": "i use: `error_reporting(E_ALL); register_shutdown_function(\"ShutdownHandler\"); set_exception_handler(\"ExeptionHandler\"); set_error_handler(\"ErrorHandler\");`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T14:19:59.090", "Id": "426490", "Score": "0", "body": "So you can add your var_dump to the exception handler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T16:58:52.030", "Id": "427520", "Score": "0", "body": "hello, in such case that I need to execute multiple insert, at the same time, as the Script would do to identify which variables correspond to each query (bind); considering that I want everything to be done in a single appointment to the Script ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T17:50:48.800", "Id": "427525", "Score": "0", "body": "can you see the example i have add to my post. how this work with your implement.??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T19:11:18.413", "Id": "427537", "Score": "0", "body": "Sorry I don't understand what are you asking" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T20:25:10.123", "Id": "427548", "Score": "0", "body": "see the last update of my post, i have add an example of how work my script, i check your suggestion with select and not problem, but the problem is when i try to use multiple query to insert/update in same array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-28T07:47:25.477", "Id": "427587", "Score": "0", "body": "check the updated answer" } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T08:43:31.903", "Id": "220705", "ParentId": "220670", "Score": "2" } } ]
{ "AcceptedAnswerId": "220705", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T19:37:16.767", "Id": "220670", "Score": "2", "Tags": [ "php", "mysql", "pdo" ], "Title": "PDO library to handle MySQL queries" }
220670
<p><strong>The task</strong></p> <p>is taken from <a href="https://leetcode.com/problems/plus-one/" rel="nofollow noreferrer">leetcode</a></p> <blockquote> <p>Given a non-empty array of digits representing a non-negative integer, plus one to the integer.</p> <p>The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.</p> <p>You may assume the integer does not contain any leading zero, except the number 0 itself.</p> <p><strong>Example 1:</strong></p> <p>Input: [1,2,3]</p> <p>Output: [1,2,4]</p> <p>Explanation: The array represents the integer 123.</p> <p><strong>Example 2:</strong></p> <p>Input: [4,3,2,1]</p> <p>Output: [4,3,2,2]</p> <p>Explanation: The array represents the integer 4321.</p> </blockquote> <p><strong>My solution</strong></p> <pre><code>/** * @param {number[]} digits * @return {number[]} */ var plusOne = function(digits) { let i = digits.length; let carry = 1; let tmp; const res = []; while(i &gt; 0 || carry) { tmp = (--i &gt;= 0 ? digits[i] : 0) + carry; carry = tmp / 10 | 0; res.unshift(tmp % 10); } return res; }; </code></pre>
[]
[ { "body": "<p>It looks like your logic is fine, but I don't find it very readable. I guess it would be fine if you could clearly explain your logic in a tech interview, but here's how I'd write it just to be more clear. </p>\n\n<p>Use a <code>for</code> loop (that's what they're for!), modify the digits array in place unless they specify you shouldn't, and you can return as soon as you don't have anything left to carry.</p>\n\n<pre><code>var plusOne = function(digits){\n let carry=1;\n\n for(let i=digits.length-1; i&gt;=0; i--){\n let digitSum = carry + digits[i];\n if(digitSum &gt;= 10){\n digits[i] = digitSum%10;\n }\n else{\n digits[i] = digitSum;\n return digits;\n }\n }\n\n if(carry == 1){\n digits.unshift(1);\n }\n return digits;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T05:34:53.920", "Id": "426402", "Score": "0", "body": "You could save yourself the Else case . Or is there a reason why you wanted to include it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:55:29.020", "Id": "426450", "Score": "0", "body": "What are `while` loops for? Do you realize that a `let i` in a for loop means a new `i` is pushed to the heap, assigned the old value and operated on for every iteration, plus the one for the or loop prep. For loops with block scopes are more complex than while loops both in terms of source size and CPU load." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T22:18:20.840", "Id": "220680", "ParentId": "220672", "Score": "2" } }, { "body": "<p>Nice. Good use of the carry to add the 1.</p>\n\n<p>One point. Arrays only grow from the end. <code>Array.unshift()</code> means that each item must be moved up and is <span class=\"math-container\">\\$O(n)\\$</span> complexity (making the whole function approx <span class=\"math-container\">\\$O(n^{log(n)})\\$</span> ) while <code>Array.push()</code> is only <span class=\"math-container\">\\$O(1)\\$</span> but then you will have to reverse but would still be <span class=\"math-container\">\\$O(n)\\$</span> overall.</p>\n\n<p>You could also pre-allocate the array and slice the result array if there is no extra digit.</p>\n\n<pre><code>function plusOne(digits) {\n var i = digits.length, carry = 1, tmp;\n const res = [];\n while (i-- &gt; 0 || carry) {\n tmp = (i &gt;= 0 ? digits[i] : 0) + carry;\n carry = tmp / 10 | 0;\n res.push(tmp % 10);\n }\n return res.reverse();\n}\n</code></pre>\n\n<ul>\n<li>If you must use function expressions use a <code>const</code>. Eg <code>const plusOne = function</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:33:40.797", "Id": "220715", "ParentId": "220672", "Score": "2" } } ]
{ "AcceptedAnswerId": "220715", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T20:06:38.707", "Id": "220672", "Score": "4", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6" ], "Title": "Add one to the last array element" }
220672
<p>I have here a working method of parsing input arguments however it seems redundant. I would like to shorten this code so it doesn't appear so repetitive.</p> <pre><code>tool.sh &lt;file-to-use&gt; tool.sh &lt;file-to-use&gt; -o &lt;output-file-name&gt; # If arguments are set and equals "-o" then set APP_NAME if [[ -n $3 ]] &amp;&amp; [[ $2 = "-o" ]]; then APP_NAME=$3 # If argument is set and equals anything besides "-o" throw error and show help menu elif [[ -n $2 ]] &amp;&amp; [[ $2 != "-o" ]]; then echo "ERROR: Synatx error." bash $0 -h exit # If "-o" is set but they did not give a output name throw error and display help menu elif [[ -z $3 ]] &amp;&amp; [[ $2 = "-o" ]]; then echo "ERROR: Did not specify output file name." bash $0 -h exit fi </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T23:51:12.143", "Id": "426390", "Score": "1", "body": "Have you seen https://stackoverflow.com/questions/7069682/how-to-get-arguments-with-flags-in-bash ??" } ]
[ { "body": "<p>Use the <code>${variable?error message}</code> syntax to error on empty arguments. Use <code>shift</code> to remove parsed arguments from the positional parameters, so that the next unseen argument is always <code>$1</code>. If there are any arguments left at the end, there were too many.</p>\n\n<p>When a message isn't enough, you can use <code>trap … EXIT</code> to call a function on error. Remember to remove the trap after parsing and at the very start of your handler function.</p>\n\n<p>This version isn't any shorter than yours but it's more generic. You can add parameters or rearrange their order without altering the numbers in the existing logic. The error-handling is in one place instead of two.</p>\n\n<pre><code>show_help() { \n trap - EXIT # omitting this can lead to an infinite loop\n exec $0 -h\n exit\n}\n\ntrap show_help EXIT\nerror_usage=\"Usage: $0 input-file [-o output-file]\"\ninput=${1?$error_usage} &amp;&amp; shift\n[[ $1 = -o ]] &amp;&amp; output=${2?$error_usage} &amp;&amp; shift 2\n[[ -n $1 ]] &amp;&amp; echo $error_usage &amp;&amp; exit 0\ntrap - EXIT\n\necho \"input=$input output=$output\"\n</code></pre>\n\n<p>Rather than invoking ourselves to display help, I'd just put the help logic in the <code>show_help</code> function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T23:13:33.867", "Id": "426387", "Score": "0", "body": "Interesting thanks for the crash course! (Leveling up)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T23:08:02.757", "Id": "220683", "ParentId": "220681", "Score": "3" } }, { "body": "<p>Although tagged <a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged &#39;bash&#39;\" rel=\"tag\">bash</a>, this could easily be portable POSIX shell if we use <code>[</code> rather than <code>[[</code>.</p>\n\n<p>Always quote strings containing parameter expansions; even though you might think it unlikely that anyone would invoke the script with <code>$0</code> containing spaces (for example), if you don't code for it, then someone eventually will!</p>\n\n<p>Error messages should always be directed to <code>&amp;2</code>, and error exits should always be non-zero.</p>\n\n<p>Consider using <code>getopt</code> for better argument handling (or at least loop over the arguments and use <code>shift</code> to consume them). Users don't like having to remember that <code>-o filename</code> has to come after the input file; they are used to commands that accept options in any reasonable order.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T23:12:32.497", "Id": "426586", "Score": "0", "body": "yes this would be nice but it gets a bit confusing to me when you decide you dont want to use a flag for a input file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:29:48.243", "Id": "426623", "Score": "0", "body": "Not a problem, if you say that any non-option argument is an input file. Do you need a demonstration of how that looks?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T17:41:41.867", "Id": "220746", "ParentId": "220681", "Score": "3" } } ]
{ "AcceptedAnswerId": "220683", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T22:29:03.800", "Id": "220681", "Score": "2", "Tags": [ "bash" ], "Title": "Looking to shorten method of parsing arguments in BASH" }
220681
<p>I am building out a simple web server in Go. My goal is to expand on this framework in a different application I am building. </p> <p>Here is my github repo <a href="https://github.com/jmacnc/gowebserver" rel="nofollow noreferrer">https://github.com/jmacnc/gowebserver</a></p> <p>Is what I have here using best practices? </p> <p>I am specifically looking for feedback on the tests, and how I am connecting to different databases (testing and main application). As seen below...</p> <pre class="lang-golang prettyprint-override"><code>//Handler for posting a new user func (d *MongoDB) PostUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") //Retrieving request body var user User _ = json.NewDecoder(r.Body).Decode(&amp;user) //Posting Company err := d.PostUserToDB(user) //Error Handling if err != nil { fmt.Println(err) w.WriteHeader(500) } } //Populating a new user in the database func (d *MongoDB) PostUserToDB(user User) error { _, err := d.db.Collection("users").InsertOne(context.Background(), user) if err != nil { return err } return nil } func main() { //Connects to the database d , _ := ConnectToDB() //Creates mux router/multiplexer r := mux.NewRouter() //Handle Functions r.HandleFunc("/user", d.PostUser).Methods("POST") //Starts web server //Prints a string saying that the app is running... fmt.Println("Application Running...") log.Fatal(http.ListenAndServe(LOCALHOST, r)) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T07:09:17.733", "Id": "426416", "Score": "0", "body": "Where are the tests and `ConnectToDB` logic tho?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:33:02.943", "Id": "426441", "Score": "0", "body": "It the GitHub repo" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T23:12:15.333", "Id": "220684", "Score": "3", "Tags": [ "unit-testing", "go", "rest", "web-services" ], "Title": "Simple REST Base Web Server with Unit Tests" }
220684
<p>I have small web application that need a users permissions system to access some content or add/edit it.</p> <p>I'm using roles given to a user to manage priviliges, and also a user custom <code>meta</code> to set a custom priviliges to a specific user.</p> <p>I want to know if this method is good ? if not why ? Is there is any suggestion better than put priviligies in a array ? because is too long :( .</p> <pre><code> if(!function_exists('user_cap')) { /** * */ function user_cap( $user_id, $cap, $action, $accesable = null ) { $get_user_info = get_user_info( $user_id ); $user_role = $get_user_info-&gt;user_role; /** * Super admin role can determine custom privileges for every user */ //$user_privileges = get_user_meta( $user_id, 'user_privileges' ); // $privileges = [ 'super_admin' =&gt; [ 'users' =&gt; [ 'create' =&gt; 'yes', 'read' =&gt; 'yes', 'update' =&gt; 'yes', 'delete' =&gt; 'yes' ], 'projects' =&gt; [ 'create' =&gt; 'yes', 'read' =&gt; 'yes', 'update' =&gt; 'yes', 'delete' =&gt; 'yes' ], 'locations' =&gt; [ 'create' =&gt; 'yes', 'read' =&gt; 'yes', 'update' =&gt; 'yes', 'delete' =&gt; 'yes' ], 'reminders' =&gt; [ 'create' =&gt; 'yes', 'read' =&gt; 'yes', 'update' =&gt; 'yes', 'delete' =&gt; 'yes' ], 'administrations' =&gt; [ 'create' =&gt; 'yes', 'read' =&gt; 'yes', 'update' =&gt; 'yes', 'delete' =&gt; 'yes' ], 'locations' =&gt; [ 'create' =&gt; 'yes', 'read' =&gt; 'yes', 'update' =&gt; 'yes', 'delete' =&gt; 'yes' ], ], 'user' =&gt; [ 'users' =&gt; [ 'create' =&gt; 'no', 'read' =&gt; 'no', 'update' =&gt; 'no', 'delete' =&gt; 'no' ], 'projects' =&gt; [ 'create' =&gt; 'no', 'read' =&gt; 'get_user_responsible_projects', 'update' =&gt; 'no', 'delete' =&gt; 'no' ], 'locations' =&gt; [ 'create' =&gt; 'no', 'read' =&gt; 'no', 'update' =&gt; 'no', 'delete' =&gt; 'no' ], 'reminders' =&gt; [ 'create' =&gt; 'yes', 'read' =&gt; 'get_user_reminders', 'update' =&gt; 'get_user_reminders', 'delete' =&gt; 'get_user_reminders' ], 'administrations' =&gt; [ 'create' =&gt; 'no', 'read' =&gt; 'no', 'update' =&gt; 'no', 'delete' =&gt; 'no' ], 'locations' =&gt; [ 'create' =&gt; 'no', 'read' =&gt; 'no', 'update' =&gt; 'no', 'delete' =&gt; 'no' ], ], ]; $role_privilege = $privileges[$user_role][$cap][$action]; if($privilegs == 'yes') { return true; }elseif($privilege == 'no') { return false; }else{ $privilege = call_user_func($privilege); if(in_array($accesable, $privilege) { return true; } } return false; } } if(!function_exists('user_can')) { /** * @param int $user_id * @param string $cap * @param string $action */ function user_can( $user_id, $cap, $action ) { return user_cap( $user_id, $cap, $action ); } } if(!function_exists('current_user_can')) { /** * @param string $cap * @parzm string $action * * @return mixed (string on success|boolean on failure) */ function current_user_can( $cap, $action ) { $current_user = current_user(); if(empty($current_user)) { return false; } return user_can($current_user-&gt;id, $cap, $action); } } </code></pre>
[]
[ { "body": "<p>There will be many, many ways to structure these permissions. I'll offer a pathway that doesn't totally abandon your original script.</p>\n\n<ol>\n<li><p>Don't bother writing out all of the <code>super_admin</code> permissions until the day when you actually have a <code>no</code> setting for them. Just write a simple condition on that single variable and an early return.</p></li>\n<li><p>Only store the <code>yes</code> and callback values. This will save lots of eye strain and scrolling. Have your program assume <code>No</code> permission by default and only declare the access granting keys. By doing this, you can write an early <code>false</code> return if the set of keys are not listed.</p></li>\n<li><p>If the listed value in the permissions lookup array is <code>yes</code>, early return <code>true</code>.</p></li>\n<li><p>Leave the \"heaviest\" action 'til last. This return is the final determining line, so it can be an inline condition on <code>return</code>.</p></li>\n</ol>\n\n<p>The adjusted script might look like this: (notice no typos and no temporary variables)</p>\n\n<pre><code>function user_cap($user_id, $cap, $action, $accesable = null) {\n $get_user_info = get_user_info($user_id);\n $user_role = $get_user_info-&gt;user_role;\n\n $privileges = [\n 'user' =&gt; [\n 'projects' =&gt; [\n 'read' =&gt; 'get_user_responsible_projects',\n ],\n 'reminders' =&gt; [\n 'create' =&gt; 'yes',\n 'read' =&gt; 'get_user_reminders',\n 'update' =&gt; 'get_user_reminders',\n 'delete' =&gt; 'get_user_reminders'\n ]\n ]\n ];\n\n if ($user_role == 'super_admin') {\n return true;\n }\n\n if (!isset($privileges[$user_role][$cap][$action])) {\n return false;\n }\n\n if ($privileges[$user_role][$cap][$action] == 'yes') {\n return true;\n }\n\n return in_array($accesable, call_user_func($privileges[$user_role][$cap][$action]));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T08:55:28.193", "Id": "220706", "ParentId": "220687", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T00:49:55.120", "Id": "220687", "Score": "0", "Tags": [ "php" ], "Title": "Small project users privileges" }
220687
<p>I was tasked with creating the class <code>RandomStringChooser</code> that prints the strings in the passed array in a random order, based on the <code>for</code> loop in the tester. If the number of iterations in the <code>for</code> loop is larger than the size of the array passed, then "NONE" should be returned. Look at the tester in the program for an example of how this is run.</p> <p>I'm looking for feedback on code efficiency, neatness, and other nitpicks that can improve the look of my code. I'd very much like to kick bad habits to the curb.</p> <pre><code>import java.util.List; import java.util.ArrayList; import java.util.Random; // Declare the RandomStringChooser class public class RandomStringChooser { /** Declare any fields (instance variables) **/ private ArrayList&lt;String&gt; wordArray; private Random r; /** Declare any constructors */ public RandomStringChooser(String[] wordArray) { this.wordArray = convert(wordArray); this.r = new Random(); } /**Convert array to arraylist**/ private ArrayList&lt;String&gt; convert(String[] array) { ArrayList&lt;String&gt; arraylist = new ArrayList&lt;String&gt;(); for(String string : array) { arraylist.add(string); } return arraylist; } /** Write the getNext method */ public String getNext() { if(this.wordArray.size() != 0) { int index = r.nextInt(this.wordArray.size()); String word = this.wordArray.get(index); if(word != null) { this.wordArray.remove(index); return word; } return "NONE"; } return "NONE"; } /** This is a main method for testing the class */ public static void main(String[] args) { System.out.println("It should print the words in the array in a random order and then NONE twice"); String[] wordArray = {"wheels", "on", "the", "bus"}; RandomStringChooser sChooser = new RandomStringChooser(wordArray); //This loop will output the words in `wordArray` in random order, then "NONE" twice for (int k = 0; k &lt; 6; k++) { System.out.println(sChooser.getNext() + " "); } //This loop will output the words in `wordArray` in random order, then stop for (int k = 0; k &lt; 4; k++) { System.out.println(sChooser.getNext() + " ") } } // end of main } // end of class </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T04:34:15.740", "Id": "426400", "Score": "0", "body": "In the `k < 4` loop in `main()`, it will just print `NONE` four times." } ]
[ { "body": "<h2>Interface</h2>\n\n<p>When I see a method named <code>get…()</code>, I expect it to behave like a getter method: it should retrieve data, with no side-effects. Your <code>getNext()</code>, though, has the side-effect of consuming one random element from the list. Therefore, <code>next()</code> would be a more appropriate name than <code>getNext()</code>.</p>\n\n<p>Once you rename it, you'll see that your <code>RandomStringChooser</code> should probably just implement the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Iterator.html\" rel=\"nofollow noreferrer\"><code>Iterator&lt;String&gt;</code></a> interface. Java programmers instantly recognize an <code>Iterator</code> and know how one should behave.</p>\n\n<p>Then, you'll see that the <code>Iterator</code> interface says that <code>next()</code> should throw <code>NoSuchElementException</code> when the elements have been exhausted — and that is what you should do too. In fact, returning <a href=\"https://www.snopes.com/fact-check/licensed-to-bill/\" rel=\"nofollow noreferrer\">\"NONE\" as a special string to indicate a missing value is a bad practice</a>. </p>\n\n<p>Furthermore, if one of the input strings is in fact <code>null</code>, it shouldn't be the job of your <code>RandomStringChooser</code> to translate it to \"NONE\".</p>\n\n<p>Consider changing the signature of the constructor to <code>public RandomStringChooser(String... words)</code>. The code will continue to work the same way, but you would also have the option of invoking it as <code>new RandomStringChooser(\"wheels\", \"on\", \"the\", \"bus\")</code>, with multiple string arguments.</p>\n\n<h2>Efficiency</h2>\n\n<p>Whenever you extract a random element from the list, you call <code>this.wordArray.remove(index)</code>. Removing an element causes all of the subsequent elements to be copied over to fill the gap. Therefore, if you randomly go through an <em>n</em>-element list, you will perform O(<em>n</em><sup>2</sup>) copy operations, which is quite poor for efficiency.</p>\n\n<p>A better idea would be to implement a <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher-Yates shuffle</a>, which just swaps one pair of elements per output string.</p>\n\n<h2>Miscellaneous</h2>\n\n<p><code>wordArray</code> is poorly named: it's actually a <code>java.util.List</code>, not an array.</p>\n\n<p>Your signposting comments are annoying noise to anyone who knows Java.</p>\n\n<h2>Suggested implementation</h2>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.Random;\n\npublic class RandomStringChooser implements Iterator&lt;String&gt; {\n\n private Random r;\n private String[] words;\n private int n;\n\n public RandomStringChooser(String... words) {\n this.r = new Random();\n this.words = Arrays.copyOf(words, words.length);\n this.reset();\n }\n\n /**\n * Makes all words eligible to be chosen again, even if they have been\n * previously returned by &lt;code&gt;next()&lt;/code&gt;.\n */\n public void reset() {\n this.n = this.words.length;\n }\n\n public boolean hasNext() {\n return this.n &gt; 0;\n }\n\n public String next() {\n if (!this.hasNext()) {\n throw new NoSuchElementException();\n }\n\n // Fisher-Yates shuffle\n int index = r.nextInt(this.n--);\n String word = this.words[index];\n this.words[index] = this.words[this.n];\n this.words[this.n] = word;\n return word;\n }\n\n /** This is a main method for testing the class */\n public static void main(String[] args) {\n System.out.println(\"It should print the words in the array in a random order and then NONE twice\");\n RandomStringChooser sChooser = new RandomStringChooser(\n \"wheels\", \"on\", \"the\", \"bus\"\n );\n //This loop will output the words in `wordArray` in random order, then \"NONE\" twice\n for (int k = 0; k &lt; 6; k++) {\n System.out.println(sChooser.hasNext() ? sChooser.next() : \"NONE\");\n }\n //This loop will output the words in `wordArray` in random order, then stop\n sChooser.reset();\n for (int k = 0; k &lt; 4; k++) {\n System.out.println(sChooser.hasNext() ? sChooser.next() : \"NONE\");\n }\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T04:56:04.120", "Id": "220693", "ParentId": "220688", "Score": "7" } } ]
{ "AcceptedAnswerId": "220693", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T01:23:55.727", "Id": "220688", "Score": "3", "Tags": [ "java", "strings", "array", "random" ], "Title": "Random String Chooser" }
220688
<p><a href="https://codereview.stackexchange.com/questions/219888/simple-ring-circular-buffer-c-class">The Original Post (v1)</a></p> <p>I'm looking for feedback on the updated version of the code posted at the link above.</p> <pre><code>#pragma once #include &lt;memory&gt; #include &lt;cassert&gt; #include &lt;type_traits&gt; namespace datastructures { template&lt;class _Ty, size_t _Size&gt; class CircularBufferv2 { // uses char as type to prevent default _Ty initialization. alignas(alignof(_Ty)) char buffer[_Size * sizeof(_Ty)]; size_t head; size_t tail; bool isFull; public: constexpr CircularBufferv2() noexcept : buffer{0}, head{0}, tail{0}, isFull{false} { } void push(const _Ty&amp; item) noexcept { assert(!isFull &amp;&amp; "Attempting to push item into full buffer!"); new (&amp;buffer[head * sizeof(_Ty)]) _Ty(std::move(item)); head = ++head % _Size; isFull = head == tail; } _Ty pop() noexcept { assert(!is_empty() &amp;&amp; "Attempting to pop item from empty buffer!"); auto location = reinterpret_cast&lt;_Ty*&gt;(&amp;buffer[tail * sizeof(_Ty)]); auto result = std::move(*location); std::destroy_at(location); tail = ++tail % _Size; isFull = false; return result; } _NODISCARD constexpr _Ty&amp; peek() noexcept { assert(!is_empty() &amp;&amp; "Attempting to peek in empty buffer!"); return *reinterpret_cast&lt;_Ty*&gt;(&amp;buffer[tail * sizeof(_Ty)]); } _NODISCARD constexpr const _Ty&amp; peek() const noexcept { assert(!is_empty() &amp;&amp; "Attempting to peek in empty buffer!"); return *reinterpret_cast&lt;_Ty*&gt;(&amp;buffer[tail * sizeof(_Ty)]); } _NODISCARD constexpr bool is_empty() const noexcept { return !isFull &amp;&amp; tail == head; } _NODISCARD constexpr size_t get_capacity() const noexcept { return _Size; } _NODISCARD constexpr size_t get_size() const noexcept { if (isFull) return _Size; if (head &gt;= tail) return head - tail; return _Size + head - tail; } _NODISCARD _CONSTEXPR17 _Ty* data() noexcept { return buffer; } _NODISCARD _CONSTEXPR17 const _Ty* data() const noexcept { return buffer; } }; } </code></pre> <p>I want to take advantage of all of the new features(c++17) while also supporting older compilers(preferably all older compilers but c++11 is probably as old as i'll actually be compiling for). Any suggestions welcome. (I'm attempting to use this class as an example class to follow when constructing other classes.)</p> <p>Also, the use of <code>_CONSTEXPR17</code> on the <code>data</code> functions I was wondering why use the macro vs just a <code>constexpr</code>? (I based the use of macros around the <code>std::array</code> struct, its data function uses <code>_CONSTEXPR17</code> rather than just <code>constexpr</code>.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T02:31:34.790", "Id": "426397", "Score": "2", "body": "You are aiming for C++11/C++17 compilers, yet use non-standard macros. Why? Why not stick to the standard?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:17:18.500", "Id": "426404", "Score": "2", "body": "Identifiers starting with underscore followed by a capitol letter are reserved for the implementation. i.e. They are not designed for use by application developers and thus you should not be using them. In this context `_Ty`, `_Size`, `_CONTEXPR17`, `_NODISCARD` should not be used in your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:19:19.283", "Id": "426405", "Score": "1", "body": "[What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/q/228783/14065)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:48:49.170", "Id": "426407", "Score": "0", "body": "You probably shouldn’t be using `v2` in the class name anyway. Consider using inline namespaces if you need different versions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:50:50.207", "Id": "426409", "Score": "0", "body": "@L.F. v2 will be removed once i finalize the class so you can ignore that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:53:18.923", "Id": "426411", "Score": "0", "body": "@MartinYork So the macros for contexpr etc shouldnt be used? Also I didn't realize those macros were non standard, I saw them used in the std::array implementation so I assumed they were standard, is there something that should be used instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T07:06:49.770", "Id": "426415", "Score": "0", "body": "@HexCrown Those identifiers are \"reserved for the implementation\" this means the compiler and the library shipped with the compiler is allowed to use them (so using them with `std::array` is OK). But they are not designed to be used by application developers. Be careful of using the term `Non Standard` that is not a correct usage of that term." } ]
[ { "body": "<p>Is there any reason for your users to access your internal buffer? To me that data methods shouldn't be there.</p>\n\n<p>Don't like very much those reinterpret_cast but I see you have those there to support not default constructable types. I could live with those and get back that additional feature as long as that implementation detail is sealed into the class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:55:17.173", "Id": "426412", "Score": "0", "body": "What do you mean by \"I could live with those and get back that additional feature as long as that implementation detail is sealed into the class.\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T07:04:07.740", "Id": "426414", "Score": "1", "body": "Right now you are giving access to external users to your implementation details. Your users need to know how to get Ty from the internal buffer. That is not a nice thing if the access is not that straight forward." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T06:29:32.017", "Id": "220701", "ParentId": "220690", "Score": "1" } }, { "body": "<p>Instead of a char array you can use <code>std::aligned_storage</code>.</p>\n\n<p>You aren't consistent with your macros you have both <code>constexpr</code> and <code>_CONSTEXPR17</code>. Pick one and stick to it.</p>\n\n<p><code>destroy_at</code> is standard only from C++17 onward. The equivalent syntax is <code>location-&gt;~_Ty();</code> However it may be worth to put this and the placement new into a helper function to move the ugly syntax elsewhere and clarify the function.</p>\n\n<p>You don't have a move variant of push or a bulk add/remove using iterators.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:07:48.770", "Id": "220721", "ParentId": "220690", "Score": "3" } } ]
{ "AcceptedAnswerId": "220721", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T01:29:14.297", "Id": "220690", "Score": "2", "Tags": [ "c++", "c++11", "c++17", "circular-list" ], "Title": "Simple ring/circular buffer c++ class V2" }
220690
<p>I have improved <a href="https://codereview.stackexchange.com/questions/220647/singly-linked-queue-in-php-7">this post</a> to the code below. </p> <p>As always, any critique is much appreciated!</p> <pre><code>&lt;?php class QueueNode { function __construct($item) { $this-&gt;item = $item; $this-&gt;next = null; } function __destruct() { $this-&gt;item = null; } function getItem() { return $this-&gt;item; } } class QueueIterator implements Iterator { function __construct($queue) { $this-&gt;queue = $queue; $this-&gt;current_node = $queue-&gt;head; } public function current() { return $this-&gt;current_node-&gt;item; } public function key(): \scalar { return null; } public function next(): void { $this-&gt;current_node = $this-&gt;current_node-&gt;next; } public function rewind(): void { $this-&gt;current_node = $this-&gt;queue-&gt;head; } public function valid(): bool { return isset($this-&gt;current_node); } } class Queue implements IteratorAggregate { function __construct() { $this-&gt;head = null; $this-&gt;tail = null; $this-&gt;size = 0; } function __destruct() { $this-&gt;head = null; $this-&gt;tail = null; } function push($item) { if ($this-&gt;size === 0) { $this-&gt;head = $this-&gt;tail = new QueueNode($item); } else { $new_node = new QueueNode($item); $this-&gt;tail-&gt;next = $new_node; $this-&gt;tail = $new_node; } $this-&gt;size++; } function pop() { if ($this-&gt;size === 0) { throw new Exception("Popping from an empty queue."); } $ret = $this-&gt;head-&gt;getItem(); $this-&gt;head = $this-&gt;head-&gt;next; if (--$this-&gt;size == 0) { $this-&gt;head = $this-&gt;tail = null; } return $ret; } function getFirst() { if ($this-&gt;size() === 0) { throw new Exception("getFirst() on empty Queue."); } return $this-&gt;head-&gt;getItem(); } function getLast() { if ($this-&gt;size() === 0) { throw new Exception("getLast() on empty Queue."); } return $this-&gt;tail-&gt;getItem(); } function size() { return $this-&gt;size; } function isEmpty() { return size() === 0; } public function getIterator(): \Traversable { return new QueueIterator($this); } } $queue = new Queue(); for ($i = 1; $i &lt;= 10; $i++) { $queue-&gt;push($i); } echo "Iteration: "; foreach ($queue as $item) { echo $item . " "; } echo "&lt;br&gt;Popping: "; for ($i = 1; $i &lt;= 10; $i++) { echo $queue-&gt;getFirst() . ", " . $queue-&gt;pop() . " "; } echo "&lt;br&gt;Bye!"; ?&gt; </code></pre> <p><strong>Output</strong></p> <pre><code>Iteration: 1 2 3 4 5 6 7 8 9 10 Popping: 1, 1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 8, 8 9, 9 10, 10 Bye! </code></pre>
[]
[ { "body": "<p>I see three major problems with your code:</p>\n\n<ol>\n<li>You dont use PHP 7 type hinting / return types</li>\n<li>You dont have any scopes on your methods</li>\n<li>If you wont modify your classes in the future and/or you wont extend from these classes you should use <code>final</code> for your class declarations</li>\n<li>you should always set <code>declare(strict_types=1);</code> at the beginning of every php script as long as there are no veeeery good reasons to avoid it. It will force you to write your code more typesafe or you will get fatal errors</li>\n</ol>\n\n<p>I will give you an example for each point i mentioned</p>\n\n<p><strong>1. \"You dont use PHP 7 type hinting / return types\"</strong></p>\n\n<p><strong>Before:</strong></p>\n\n<pre><code>function push($item) {\n</code></pre>\n\n<p><strong>After:</strong> </p>\n\n<pre><code>function push(int $item): void\n</code></pre>\n\n<p><strong>2. You dont have any scopes on your methods</strong></p>\n\n<p><strong>Before:</strong></p>\n\n<pre><code>function getItem() {\n</code></pre>\n\n<p><strong>After:</strong></p>\n\n<pre><code>public function getItem(): void\n</code></pre>\n\n<p><strong>3. class declaration as final</strong></p>\n\n<p><strong>Before:</strong></p>\n\n<pre><code>class QueueNode\n</code></pre>\n\n<p><strong>After:</strong></p>\n\n<pre><code>final class QueueNode\n</code></pre>\n\n<p><strong>Sidenote:</strong> </p>\n\n<p>Also you should use properties like <code>private $item = null;</code> instead of your constructor setting. Your IDE and also any other maintainer will have trouble finding bugs and/or understanding this code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T06:35:31.383", "Id": "220792", "ParentId": "220695", "Score": "2" } } ]
{ "AcceptedAnswerId": "220792", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T05:28:15.423", "Id": "220695", "Score": "2", "Tags": [ "php", "object-oriented", "linked-list", "queue" ], "Title": "Singly-linked queue in PHP 7 #2" }
220695
<p>This simple piece of software is generating a vehicle object by using the get_vehicle() function, </p> <p>Whenever i need to generate a specific vehicle I pass in the vehicle ID to this method and it returns the appropriate vehicle. </p> <p>Within the get_vehicle() function, each vehicle is generated within a case label within a switch statement, </p> <p>This code isn't very efficient because i need to generate 1000 vehicles i'll have to feed each vehicle information in its own case label, which can cause a maintenance nightmare, </p> <pre><code> #include &lt;stdio.h&gt; typedef struct Vehicle { char type[10]; //Suv, sedan, hatchback char make[10]; //toyota , nissan, ford char model[10]; //toyota-LANDCRUISER, nissan_maxima, ford_ranger int manufacturing_year; }Vehicle; Vehicle get_vehicle(int vehicle_ID); int main() { Vehicle toyota_landcruizer = get_vehicle(1); Vehicle nissan_maxima = get_vehicle(2); Vehicle ford_ranger = get_vehicle(3); printf("Make 1 is %s \n",toyota_landcruizer.make); printf("Make 2 is %s \n",nissan_maxima.make); printf("Make 3 is %s \n",ford_ranger.make); return 0; } void copyString(char new_string[], char dest_string[]) { //we are assuming string length will always be less than 10 int i,length; for(i = 0; i &lt; 10; i++) dest_string[i] = '\0'; //initialize the destination string with proper state length = strlen(new_string); for(i = 0; i &lt; length; i++) dest_string[i] = new_string[i]; } Vehicle get_vehicle(int vehicle_ID) { switch(vehicle_ID) { case 1 : //toyota Landcruizer { Vehicle toyota_landcruizer; copyString("SUV",toyota_landcruizer.type); //set type copyString("TOYOTA",toyota_landcruizer.make); copyString("LAND-CRUIZER",toyota_landcruizer.model); toyota_landcruizer.manufacturing_year = 2019; return toyota_landcruizer; break; } case 2 : //Nissan Maxima { Vehicle nissan_maxima; copyString("SEDAN",nissan_maxima.type); //set type copyString("NISSAN",nissan_maxima.make); copyString("MAXIMA",nissan_maxima.model); nissan_maxima.manufacturing_year = 2009; return nissan_maxima; break; } case 3 : //Ford ranger { Vehicle ford_ranger; copyString("SUV",ford_ranger.type); //set type copyString("FORD",ford_ranger.make); copyString("RANGER",ford_ranger.model); ford_ranger.manufacturing_year = 2016; return ford_ranger; break; } } } </code></pre> <p>How can i optimize the get_vehicle() function and remove duplicate case labels doing the same thing in each case label ? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:19:25.953", "Id": "426452", "Score": "0", "body": "It might be better if your title stated what the program did rather than the help you are seeking. Please see https://codereview.stackexchange.com/help/how-to-ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:25:29.523", "Id": "426454", "Score": "0", "body": "@pacmaninbw I've made an edit to the title. What do you think about the new title.?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:30:56.403", "Id": "426455", "Score": "1", "body": "I think the title belongs in the body of the question and that the title should be what the program is trying to accomplish. You might also want to take the Hello World out of the code. I'm trying to help you improve the question so that people will stop to look and maybe answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:53:48.527", "Id": "426465", "Score": "0", "body": "Welcome to Code Review! Is the list of vehicles to be generated by the program or is the list known at compile time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:56:31.640", "Id": "426467", "Score": "0", "body": "@Edward the list is known at compile time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:15:06.377", "Id": "426473", "Score": "1", "body": "What are you doing with the `Vehicle` objects that are returned from the function? Is read-only access sufficient? A bit more context to the problem is still needed." } ]
[ { "body": "<p><strong>Don't Re-Invent the Wheel Unless Absolutely Necessary</strong><br>\nThe C programming language already contains the function <a href=\"https://en.wikibooks.org/wiki/C_Programming/string.h/strcpy\" rel=\"nofollow noreferrer\">strcpy(destination, source)</a>. You have access to this function and many more string functions when you include string.h in your program. There is also the <code>char* strncpy(char* dst, const char* src, size_t size);</code> function that limits the number of characters that will be copied. C library functions have been optimized so that they will perform faster then code you write yourself.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nVehicle get_vehicle(int vehicle_ID)\n{\n switch (vehicle_ID)\n {\n case 1: //toyota Landcruizer\n {\n Vehicle toyota_landcruizer;\n strcpy(toyota_landcruizer.type, \"SUV\"); //set type\n strcpy(toyota_landcruizer.make, \"TOYOTA\");\n strncpy(toyota_landcruizer.model, \"LAND-CRUIZER\", 10);\n toyota_landcruizer.manufacturing_year = 2019;\n return toyota_landcruizer;\n\n break;\n }\n\n ...\n}\n</code></pre>\n\n<p><strong>Don't Repeat Yourself</strong><br>\nThere is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function.</p>\n\n<p>To simplify the code in <code>get_vehicle(int vehicle_ID)</code> you can write a generic function that creates a vehicle</p>\n\n<pre><code>Vehicle add_vehicle(char *make, char *model, char* auto_type, int year)\n{\n ...\n}\n\nVehicle get_vehicle(int vehicle_ID)\n{\n switch (vehicle_ID)\n {\n case 1: //toyota Landcruizer\n return add_vehicle(\"TOYOTA\", \"LAND-CRUISER\", \"SUV\", 2019);\n\n case 2: //Nissan Maxima\n return= add_vehicle(\"NISSAN\", \"MAXIMA\", \"SEDAN\", 2009);\n\n case 3: //Ford ranger\n return add_vehicle(\"FORD\", \"RANGER\", \"SUV\", 2016);\n }\n}\n</code></pre>\n\n<p>The <code>return</code> statement is enough, no <code>break</code> statement is necessary because it can't be reached.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T17:25:10.763", "Id": "426538", "Score": "1", "body": "Many compilers will complain that `get_vehicle()` may fall off the end without returning a value (since they cannot prove that it will be passed a `vehicle_ID` that corresponds to a `case` of the `switch`). We need a `return` after the `switch`, or a `default:` label." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:41:50.460", "Id": "426574", "Score": "0", "body": "@TobySpeight Definitely need a default case, sorry I should have mentioned that along with the magic numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:31:58.827", "Id": "426624", "Score": "1", "body": "BTW, if you have an enum for the vehicle IDs, it's better to have the fallback outside the `switch`, as decent compilers will warn about missing `case` labels if you don't account for them with `default`. That's probably what's wanted in this code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T14:17:41.143", "Id": "220734", "ParentId": "220717", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:56:48.603", "Id": "220717", "Score": "-2", "Tags": [ "performance", "c" ], "Title": "Optimizing a method that generates more than 1000 objects of the same type" }
220717
<p>My idea is to not not expose/use service's Proxy everywhere throughout the application, rather exercising all service communications(using client Proxy) from a single class. To achieve this I have created below class: - </p> <pre><code>namespace MyOrganization.EventSender { using MyOrganization.EventSender.DTOs; using MyOrganization.EventSender.Proxy; using MyOrganization.EventSender.Utilities; using log4net; using Newtonsoft.Json; using System; using System.ServiceModel; using System.ServiceProcess; /// &lt;summary&gt; /// The User Session Detail Sender /// &lt;/summary&gt; public class SessionDataSender : ISessionDataSender { private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private SessionDataDTO _sessionDataDTO; public SessionDataSender(SessionDataDTO sessionDataDTO) { _sessionDataDTO = sessionDataDTO; } public bool Send() { try { Proxy.MessageProcessorProxy.SessionDetails sd = new Proxy.MessageProcessorProxy.SessionDetails(); sd.ChangeTime = _sessionDataDTO.ChangeTime; sd.ChangeType = _sessionDataDTO.ChangeType; sd.Username = _sessionDataDTO.Username; sd.SessionId = _sessionDataDTO.SessionId; log.Info($"Sending SessionEvent [{sd.ChangeType}] to Web-Srver."); var client = new Proxy.MessageProcessorProxy.MessageProcessorClient(); var response = client.LogEventDetails(sd); Proxy.ProxyFactory.CloseProxy(client as ICommunicationObject); log.Info($"Web-Server Response: [{response.ResponseMessage}]. Reference: [ {JsonConvert.SerializeObject(sd)} ] "); return true; } catch (Exception ex) { log.Error($"Exception: [{ex.ToString()}]"); return false; } } } } </code></pre> <p>Now, my questions are: -</p> <ul> <li>Is it good to map every DTOs into Proxy's DataContract? As my this class will grow with more service calls with different DTOs.</li> <li>How this class should be architect so that it doesn't violate SRP/Design-patterns?</li> </ul>
[]
[ { "body": "<blockquote>\n <p>Is it good to map every DTOs into Proxy's DataContract? As my this\n class will grow with more service calls with different DTOs.</p>\n</blockquote>\n\n<p>Yes, mapping to your own domain improves modularity by decoupling the DTO library from your domain.</p>\n\n<blockquote>\n <p>How this class should be architect so that it doesn't violate\n SRP/Design-patterns?</p>\n</blockquote>\n\n<ol>\n<li>Use either a custom or existing mapping framework to remove the boiler-plate mapping code from your flow. You could create a <code>Mapper</code> class.</li>\n<li>Consider using <a href=\"https://en.wikipedia.org/wiki/Aspect-oriented_software_development\" rel=\"nofollow noreferrer\">AOP</a> for refactoring boiler-plate try-catch blocks. You could create a <code>LogEntryExitAndErrorAnnotation</code> class.</li>\n<li>Your reponse object is not required</li>\n<li>Use a <code>using</code> block to dispose the client</li>\n<li>Don't use a <code>boolean</code>, when it is always <code>true</code> on success, and hidden when an <em>exception</em> occured.</li>\n</ol>\n\n<p>adapted:</p>\n\n<pre><code> [LogEntryExitAndErrorAnnotation]\n public void Send()\n {\n var sd = mapper.Map&lt;Proxy.MessageProcessorProxy.SessionDetails&gt;(_sessionDataDTO); \n\n // see notes below why to use an adapter\n using (var client = new MessageProcessorClientAdapter(\n new Proxy.MessageProcessorProxy.MessageProcessorClient()))\n client.LogEventDetails(sd);\n }\n</code></pre>\n\n<h2>Note on (4)</h2>\n\n<p>As the OP pointed out: <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/use-close-abort-release-wcf-client-resources\" rel=\"nofollow noreferrer\">Dispose could hide the root exception</a>.</p>\n\n<p>To avoid this, you can use an adapter. I would use T4 templates to generate these for all my clients.</p>\n\n<p>Suppose your client interface is</p>\n\n<pre><code>public interface IMessageProcessorClient : IDisposable {\n void LogEventDetails(object data); // or typed class\n}\n</code></pre>\n\n<p>You can use the code below to have the best possible exception details. If no error occured during the operation, the error of Dispose is thrown, else an aggregate error is thrown.</p>\n\n<pre><code>public class MessageProcessorClientAdapter : IMessageProcessorClient {\n public IMessageProcessorClient Source {get; private set;}\n public Exception Error {get;private set;}\n public MessageProcessorClientAdapter(IMessageProcessorClient source) {\n this.Source = source; // check for null\n }\n public void LogEventDetails(object data) {\n try {\n this.Source.LogEventDetails(data);\n } catch (Exception error) {\n this.Error = error;\n }\n }\n public void Dispose() {\n try {\n this.Source.Dispose();\n } catch (Exception error) {\n if (this.Error == null) {\n this.Error = error;\n } else {\n this.Error = new AggregateException(this.Error, error);\n }\n } finally {\n if (this.Error != null) { \n throw this.Error;\n }\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:18:46.067", "Id": "426497", "Score": "0", "body": "Thanks for review & suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:24:28.783", "Id": "426524", "Score": "0", "body": "`LogEntryExitAndErrorAnnotation` - oh, this will produce a lot of garbage log entries ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:27:09.563", "Id": "426525", "Score": "0", "body": "@t3chb0t well, perhaps this is overkill. If the service is hosted in IIS, you could always enable logs here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:29:29.910", "Id": "426531", "Score": "0", "body": "I treat aspect-oriented logging generally as a sign of _I don't know what I'm doing so I'd better log everything_ ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:31:56.547", "Id": "426532", "Score": "0", "body": "@t3chb0t at my current client, we log this extensively to show other teams we 'did' manage to process their request, so the bug 'must' be at their code ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T06:42:28.697", "Id": "426614", "Score": "0", "body": "So, it is not a good practice to use AOP based logging?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T06:45:00.880", "Id": "426615", "Score": "0", "body": "@Anil Kumar If you decide to log all entry, exit, errors in your service operations, I would suggest to use AOP. The real question is: do you want to log all this information? Like discussed above, if you use IIS, you can enable logs from this API. So, I would say, it depends on what you want, and which technology is available to you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T11:10:38.653", "Id": "426655", "Score": "0", "body": "point no (4) using block can't be used https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/use-close-abort-release-wcf-client-resources" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T12:15:02.300", "Id": "426664", "Score": "0", "body": "@Anil Kumar Interesting post! However, it is by design that a Dispose exception can hide an exception within the clause. I will update my post with an adapter class to avoid this problem, maintaining the nice Dispose pattern." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:03:25.407", "Id": "220719", "ParentId": "220718", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T11:57:08.370", "Id": "220718", "Score": "1", "Tags": [ "c#", "object-oriented", "design-patterns", "wcf" ], "Title": "Map client application's DTO to service-proxy's DataContract" }
220718
<p>A factorial of a number is the product of all the integers from <code>1</code> to that number. </p> <p>For example, the factorial of <code>5</code> (denoted as <code>5!</code>) is <code>1*2*3*4*5 = 120</code>. The factorial of <code>0</code> is <code>1</code>.</p> <pre><code>def recur_factorial(x): if x == 1: return 1 else: return (x * recur_factorial(x - 1)) num = int(input("Enter number: ")) print("The factorial of", num, "is", recur_factorial(num)) </code></pre> <p>So I would like to know whether I could make this program shorter and more efficient.</p> <p>Also, I would like to know the advantages and disadvantages of recursion.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:42:26.360", "Id": "426458", "Score": "1", "body": "`The factorial of 0 is 1.` What does this code do for `x==0`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:45:34.527", "Id": "426459", "Score": "0", "body": "@MaartenFabré - I have edited my code to include your question above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:47:26.867", "Id": "426460", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:48:06.520", "Id": "426461", "Score": "1", "body": "Once a question has an answer, leave the code in it alone. If the original code wasn't complete, please learn something from this for your next question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:48:31.910", "Id": "426462", "Score": "0", "body": "@MaartenFabré - `if num == 0: print (\"The factorial of 0 is 1\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:49:14.940", "Id": "426464", "Score": "0", "body": "@Mast - Thank you, I will keep this in mind." } ]
[ { "body": "<p>Looking over your code, this is what I have for you:</p>\n\n<ul>\n<li>Your function can be turned into a one-liner</li>\n<li>You should use <code>if __name__ == '__main__'</code> to ensure you're not running this program externally.</li>\n</ul>\n\n<p>Refactored Code:</p>\n\n<pre><code>def recur_factorial(x):\n return 1 if x == 1 else (x * recur_factorial(x - 1))\n\ndef main():\n num = int(input(\"Enter number: \"))\n print(\"The factorial of\", num, \"is\", recur_factorial(num))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>You can read <a href=\"https://stackoverflow.com/questions/5250733/what-are-the-advantages-and-disadvantages-of-recursion\">this StackOverflow question</a> for more information about the advantages and disadvantages of recursion</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:24:52.590", "Id": "426453", "Score": "0", "body": "Upvoted! Thanks, I will keep this in mind." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:22:36.283", "Id": "220723", "ParentId": "220720", "Score": "3" } } ]
{ "AcceptedAnswerId": "220723", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:06:44.980", "Id": "220720", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "recursion" ], "Title": "Python program to find the factorial of a number using recursion" }
220720
<p>I have written a Python program to take in two strings and print the larger of the two strings.</p> <p>Here is my code - </p> <pre><code>string1 = input("Enter first string: ") string2 = input("Enter second string: ") count1 = 0 count2 = 0 for i in string1: count1 = count1 + 1 for j in string2: count2 = count2 + 1 if (count1 &lt; count2): print ("Larger string is:") print (string2) elif (count1 == count2): print ("Both strings are equal.") else: print ("Larger string is:") print (string1) </code></pre> <p>Here are some example outputs -</p> <pre class="lang-none prettyprint-override"><code>Enter first string: everything Enter second string: nothing Larger string is: everything Enter first string: cat Enter second string: apple Larger string is: apple </code></pre> <p>I feel that my code is unnecessarily long. Therefore, I would like to know whether I could make this program shorter and more efficient.</p> <p>Any help would be highly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T17:14:42.387", "Id": "426987", "Score": "1", "body": "So \"larger\" is length, not lexically sorted last? i.e. `\"aa\"` is larger than `\"z\"`. Normally we'd use the word \"longer\" to make it 100% clear we're talking just about length, not some other comparison predicate like alphabetical order, i.e. first mismatching character." } ]
[ { "body": "<p>Python strings supports Python built-in <a href=\"https://docs.python.org/3/library/functions.html?highlight=len#len\" rel=\"noreferrer\">len</a> function. You don't need to iterate through them manually, as for lists/dicts/sets etc (it is not Pythonic):</p>\n\n<pre><code>def compare_strings_len(s1, s2):\n if len(s1) &gt; len(s2):\n print('String 1 is longer: ', s1)\n elif len(s1) &lt; len(s2):\n print('String 2 is longer: ', s2)\n else:\n print('Strings length are equal!')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T14:06:27.240", "Id": "426486", "Score": "0", "body": "Upvoted! Thanks, I will keep in mind to use inbuilt functions as they make programs easier to write." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T14:29:45.267", "Id": "427492", "Score": "2", "body": "...and easier to read!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:33:34.180", "Id": "220730", "ParentId": "220726", "Score": "36" } }, { "body": "<h2>Long live the <a href=\"http://book.pythontips.com/en/latest/ternary_operators.html\" rel=\"nofollow noreferrer\">Ternary</a>:</h2>\n\n<pre><code>def print_longer(s,s2):\n # return (s,s2)[len(s)&lt;len(s2)] if you don't want to print within the function.\n print( ( s, s2 )[ len(s) &lt; len(s2) ] )\n</code></pre>\n\n<h2>Explanation:</h2>\n\n<p>if-else statements are clean, but they're verbose. A ternary operation would reduce this to a one-liner.</p>\n\n<p>The format is as follows: <code>(result_if_false,result_if_true)[comparison]</code></p>\n\n<p>What is happening is that <code>(s,s2)</code> is creating a tuple of the two strings. <code>len(s)&lt;len(s2)</code> then compares the two, and because they're within square brackets <code>[]</code>; the boolean result is casted to an integer index. </p>\n\n<p>Since you can only have a 0 or 1 result, this returns <code>s</code> if it is larger than <code>s2</code>, and vice-versa.</p>\n\n<p>EDIT: This returns <code>s</code> if both strings are of equal lengths.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T17:03:29.347", "Id": "426536", "Score": "1", "body": "Upvoted! Thanks for the detailed response! Some really good stuff in here!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T18:37:44.517", "Id": "426549", "Score": "4", "body": "It doesn't properly handle the case of `\"Both strings are equal.\"` but upvoted anyways because it's a nice approach" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:25:35.630", "Id": "426571", "Score": "3", "body": "The expression in your answer is _not_ a ternary operator. By definition, a ternary operator takes 3 arguments. Your code uses binary operators instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:30:17.310", "Id": "426572", "Score": "2", "body": "It is interesting and _really_ short gimmick, but I definetly don't use this in production code :) I spent nearly 10-20 seconds looking at the code until I understood how it is working!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T22:00:51.473", "Id": "426577", "Score": "2", "body": "@RolandIllig While the term \"ternary\" refers to a function with three arguments, the term is often used to refer to a specific ternary operator (a description of which is linked to in the answer). This answer builds that functionality out of binary operators." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T23:03:38.693", "Id": "426585", "Score": "4", "body": "Python's ternary is `a if condition else b`, not your tuple-indexing. Your own link calls your method obscure. It should only be seen as a holdover from very old versions of Python that don't support the `if`/`else` syntax ([pre-2.5](https://stackoverflow.com/a/394814/1394393))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T04:43:19.007", "Id": "426602", "Score": "8", "body": "I don't think this is appropriate. Python doesn't support C style ternaries and attempting to replicate it by *indexing a tuple* is not pythonic and so should not be suggested" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T06:06:04.010", "Id": "426613", "Score": "5", "body": "@Sirens The `if`/`else` syntax is equivalent to C style ternaries, in that it only executes the selected expression." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T19:52:39.230", "Id": "427015", "Score": "0", "body": "@jpmc26 Makes one wonder whether `if ... else` has better performance than tuple indexing, given that the latter is branchless." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T18:52:19.687", "Id": "427151", "Score": "2", "body": "@Rogem: In a pure interpreter like CPython, control dependencies in the Python program become data dependencies in the interpreter. The interpreter typically uses indirect branches to dispatch to handler functions for different Python bytecode operations. Plus CPython has *huge* overhead for evaluating an expression, probably larger than the branch mispredict cost of the host CPU. e.g. it's big enough to basically hide the difference between hardware division vs. multiply!! [Why are bitwise operators slower than multiplication/division/modulo?](//stackoverflow.com/q/54047100)" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T17:02:12.210", "Id": "220742", "ParentId": "220726", "Score": "2" } }, { "body": "<p>Here's how I would get the longer string:</p>\n\n<pre><code>max(string_1, string_2, key=len) # Returns the longer string\n</code></pre>\n\n<p>The <code>key</code> keyword argument is a pattern you'll see frequently in python. It accepts a function as an argument (in our case <code>len</code>).</p>\n\n<p>If you wanted to find the longest of multiple strings, you could do that too:</p>\n\n<pre><code>max('a', 'bc', 'def', 'ghi', 'jklm', key=len) # =&gt; 'jklm'\n</code></pre>\n\n<p>Warning:</p>\n\n<p>This solution is not a great fit if you need to know when two strings are of equal length. If that's a requirement of yours, you'd be better off using a solution from one of the other answers.</p>\n\n<p>I won't bother updating this approach to handle that requirement: that would feel like working against the language.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T08:55:26.540", "Id": "426637", "Score": "12", "body": "Bear in mind that `max` will not work as intended if both string are the same len" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T18:44:00.870", "Id": "426774", "Score": "6", "body": "Yeah, for this answer to be correct and true to the functionality, there has to be an equality check first before doing `max()`. Please fix that or mention that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T13:20:29.393", "Id": "426907", "Score": "7", "body": "Not sure how this answer got so many upvotes: it specializes to treat a use case beyond project scope (more than two inputs) and fails to handle a core acceptance criteria (identify when strings have same length). `max` is tidy and Pythonic, but this is a poor code review." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:49:53.110", "Id": "220770", "ParentId": "220726", "Score": "34" } }, { "body": "<p>Building off of WeRelic and user201327 answers, if you really want to optimize for short code, you can do:</p>\n\n<p><code>print(('Larger string is:{}'.format(max(string1,string2, key=len)),'Both strings are equal.')[len(string1)==len(string2)])</code></p>\n\n<p>However, a more readable version would be</p>\n\n<pre><code>if len(string1)==len(string2):\n print('Both strings are equal.')\nelse:\n print('Larger string is:{}'.format(max(string1,string2, key=len))\n</code></pre>\n\n<p>Or, following JollyJoker's suggestion,</p>\n\n<pre><code>print( 'Both strings are equal.' if len(string1)==len(string2) \n else 'Larger string is:{}'.format(max(string1,string2, key=len)))\n</code></pre>\n\n<p>Breaking down the short version:</p>\n\n<p><code>max(string1,string2, key=len)</code> returns the larger string, as measured by length</p>\n\n<p><code>('Larger string is:{}'.format(max(string1,string2, key=len))</code> Takes the larger of the two strings, and inserts it into the string <code>'Larger string is:</code></p>\n\n<p><code>('Larger string is:{}'.format(max(string1,string2, key=len)),'Both strings are equal.')</code> creates tuple where the first value says what the larger string is, and the second element says they're equal</p>\n\n<p><code>len(string1)==len(string2)</code> returns a boolean based on whether the strings are equal length.</p>\n\n<p><code>[len(string1)==len(string2)]</code> takes one of the elements of the tuple, according to the value of <code>len(string1)==len(string2)</code>. This <a href=\"https://en.wikibooks.org/wiki/Introduction_to_Programming_Languages/Coercion\" rel=\"nofollow noreferrer\">coerces</a> the boolean into an integer: <code>False</code> is considered to be <code>0</code> and retrieves the <code>Larger string is:</code> element. <code>True</code> is considered to be <code>1</code>, and retrieves the <code>'Both strings are equal.'</code> element.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T08:29:20.073", "Id": "426630", "Score": "0", "body": "Judging by the comments, this answer except using `a if condition else b` should be the correct one. So, `print('Both strings are equal.' if len(string1)==len(string2) else 'Larger string is:{}'.format(max(string1,string2, key=len)` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T09:35:29.377", "Id": "426643", "Score": "1", "body": "-1, this is _technically_ correct, but the functionality is obfuscated to the point where you need multiple paragraphs to explain how it works. This isn't code golf; rather, the code should be easy-to-read and self-explanatory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T13:55:37.713", "Id": "426682", "Score": "0", "body": "@crunch Well, the OP did indicate that they were asking for a short version. And I think it's a bit perverse to penalize me for spending several paragraphs explaining the code. Much of the length was due to explaining things at a basic level, such as linking to an explanation of coercion. But I've edited to make it more clear that this isn't necessarily the best way of doing it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T13:56:36.193", "Id": "426684", "Score": "0", "body": "@JollyJoker In Python, it's `if condition a else b`, rather than `a if condition else b`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T13:57:52.697", "Id": "426685", "Score": "4", "body": "@Acccumulation http://book.pythontips.com/en/latest/ternary_operators.html It's real, just looks like a switched around if-else" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-29T12:49:01.200", "Id": "427796", "Score": "0", "body": "@Acccumulation I don't have enough rep to downvote anyway! After your edit, though, I'll upvote instead." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T22:10:44.597", "Id": "220772", "ParentId": "220726", "Score": "6" } }, { "body": "<h1>Limit execution to main module</h1>\n\n<p>It <a href=\"https://stackoverflow.com/a/419189/1394393\">is customary</a> for code that starts executing a series of commands to be surrounded in a special <code>if</code>-block:</p>\n\n<pre><code>if __name__ == '__main__':\n ...\n</code></pre>\n\n<p>This prevents the code from being executed when it is imported into another module.</p>\n\n<h1>It's probably a good idea to put most of your code into a method or two</h1>\n\n<p>Particularly once you've put your code inside a main block, the multiple levels of indentation can get a little messy quickly. It helps to put some of the code into a method and then call it, rather than just have it all in sequence:</p>\n\n<pre><code>def print_longer_string(s1, s2):\n ...\n\nstring1 = input(\"Enter first string: \")\nstring2 = input(\"Enter second string: \")\nprint_longer_string(string1, string2)\n</code></pre>\n\n<h1>Use <code>len</code></h1>\n\n<p><code>len</code> <a href=\"https://stackoverflow.com/a/37262373/1394393\">is the standard mechanism</a> for obtaining the length of a <code>str</code>, as well as any other sequence type.</p>\n\n<h1>Reduce repetition</h1>\n\n<p>You can reduce your <code>if</code> block to just two conditions by testing for equal lengths first and using a ternary:</p>\n\n<pre><code>if len(string1) == len(string2):\n print(\"Both strings are equal.\")\nelse:\n print(\"Larger string is:\")\n print(string1 if len(string1) &gt; len(string2) else string2)\n</code></pre>\n\n<p>This allows you to avoid repeating the <code>print(\"Larger string is:\")</code> line without having to move that message to a variable.</p>\n\n<h1>Use more descriptive messages</h1>\n\n<p>\"Both strings are equal\" doesn't really describe what the program is telling you. \"Larger\" can also have different meanings, as well. (It could refer to lexical sorting, for example.) \"The strings have equal length\" and \"The longer string is:\" would be more explicit and less likely to cause confusion. We could differentiate between character and byte length, if that won't be clear from context, but character length is the usual assumption and is what you get from Python 3 by default.</p>\n\n<h1>Formatting</h1>\n\n<p>Read PEP8 for Python's standards on the use of spaces around parentheses, indentation length, and blank lines. Your team might define their own standards, but PEP8 is the industry default.</p>\n\n<h1>Final code</h1>\n\n<p>Putting all these together, you will get something like</p>\n\n<pre><code>def print_longer_string(s1, s2):\n if len(s1) == len(s2):\n print(\"The strings have equal length\")\n else:\n print(\"The longer string is:\")\n print(s1 if len(s1) &gt; len(s2) else s2)\n\nif __name__ == '__main__':\n s1 = input(\"Enter the first string: \")\n s2 = input(\"Enter the second string: \")\n print_longer_string(s1, s2)\n</code></pre>\n\n<p>You'll note I also shortened the variables down to <code>s1</code> and <code>s2</code>. <code>string1</code> is actually fine as a variable name if you prefer; I just find <code>s1</code> a bit quicker to read through. You usually want meaningful variable names, but there's no semantic meaning to these variables to capture in the name since it's just two arbitrary strings, so <code>s1</code> doesn't really lose anything over <code>string1</code>.</p>\n\n<p>I also want to note that I considered separating out the <code>print</code>ing from actually picking which string to print. I decided <em>not</em> to separate them because the case of equal lengths was handled differently. This fact greatly reduced any benefit we would get from separating the determination from the actual IO call. Separating them would require either having a function that returns the full string to print (which has little value since the exact message is probably dependent on the IO mechanism anyway) or introducing an extra indicator in the return value to detect the equal length case (which is a level of complexity the program does not need yet under its current requirements).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T13:42:09.697", "Id": "426914", "Score": "0", "body": "IIRC, in Python 3, `len` returns the number of *codepoints*, not *graphemes* or *grapheme clusters*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T16:38:50.180", "Id": "426978", "Score": "0", "body": "@SolomonUcko: True. But there aren't any simple built-in solutions to that problem; [`unicodedata.normalize` in NFC/NFKC mode](https://docs.python.org/3/library/unicodedata.html#unicodedata.normalize) will compose cases where an existing codepoint can express the composed form of decomposed code points, but there are some languages (East Asian IIRC) where the set of composed characters is too huge to assign a codepoint to each, so you can't combine them. I'm sure some PyPI module offers grapheme support, but it's usually allowable to compare codepoint lengths in exercises like this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T17:41:42.237", "Id": "426990", "Score": "0", "body": "@ShadowRanger Yep. BTW, I found the [`grapheme`](https://pypi.org/project/grapheme/) package. It is much less efficient to operate on graphemes, though, as they are variable-size, and operating on codepoints is often good enough. A native implementation could, however, store an array of pointers to the beginning of each grapheme, and perform operations using that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T23:33:02.790", "Id": "220777", "ParentId": "220726", "Score": "28" } }, { "body": "<p>You can immediately assume that the first one is larger and then reassign it to the second one if that one is larger, like this: </p>\n\n<pre><code>larger = input(\"Enter first string: \")\nstring2 = input(\"Enter second string: \")\nif (len(string2) &gt; len(larger)):\n larger = string2\nprint(larger)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T16:05:14.727", "Id": "426737", "Score": "1", "body": "Brackets are not necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T16:58:49.610", "Id": "426753", "Score": "1", "body": "Was your code supposed to be C or Python? At the moment, it's neither." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T17:58:15.527", "Id": "426760", "Score": "0", "body": "@Mast Sorry, I don't know either. I'm just pretending." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T07:08:54.577", "Id": "426832", "Score": "0", "body": "@Mast Fixed now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-29T13:18:19.950", "Id": "427807", "Score": "0", "body": "This does not behave as the original post does for the case of strings of equal length." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T12:58:55.077", "Id": "220827", "ParentId": "220726", "Score": "-1" } }, { "body": "<p>Since <a href=\"https://codereview.stackexchange.com/a/220772/121394\">Acccumulation's answer</a> was considered too confusing, here's the same using a real <a href=\"http://book.pythontips.com/en/latest/ternary_operators.html\" rel=\"noreferrer\">Python ternary operator</a>.</p>\n\n<pre><code>print('Equal' if len(s1) == len(s2) else 'Larger is ' + max(s1, s2, key=len))\n</code></pre>\n\n<p>I don't see the point in using .format for this kind of simple concatenation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T13:30:23.520", "Id": "220834", "ParentId": "220726", "Score": "7" } }, { "body": "<p>Here's how I would find the longest strings in a list of strings:</p>\n\n<pre><code>import itertools\n\ndef longest_string(strings):\n if not strings:\n return []\n\n strings_by_length = itertools.groupby(strings, len)\n maximum_length = max(strings_by_length.keys())\n return strings_by_length[maximum_length]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-29T13:17:29.473", "Id": "427805", "Score": "0", "body": "This does not behave as the original post does for the case of strings of equal length." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T22:27:31.417", "Id": "220872", "ParentId": "220726", "Score": "0" } } ]
{ "AcceptedAnswerId": "220730", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T12:52:34.590", "Id": "220726", "Score": "15", "Tags": [ "python", "performance", "python-3.x", "strings" ], "Title": "Python program to take in two strings and print the larger string" }
220726
<p>I'm hoping someone would be able to identify if my code is prone to SQL injections, and just overall see if there is anything that could be done better, faster or more efficiently</p> <p>Im very new to OOP and prepared statements so there might be some glaringly obvious problems but just let me know!</p> <p><em>auth_class.php</em></p> <pre><code>require 'db.php'; session_start(); ///needs an open session to set the logged in value class User { public $username = null; public $password = null; public $name = null; public $email = null; public $ftp = null; public $connection = null; function __construct(){ $this-&gt;connection = connect_db(); ///this is the basic database connection } public function passwordValidator($password){ if (strlen($password) &lt; 5) { $errors[] = "Password too short!"; } if (!preg_match("#[0-9]+#", $password)) { $errors[] = "Password must include at least one number!"; } if (!preg_match("#[a-zA-Z]+#", $password)) { $errors[] = "Password must include at least one letter!"; } if(empty($errors)){ $this-&gt;password = password_hash($password, PASSWORD_DEFAULT); return; }else{ return $errors;//this function checks the password and returns an array of errors it is checked on the other end } } public function storeFormValues($username, $name, $email) { //This needs to check the values below to confirm that there is somthing there! Although they are set as required inputs if(empty($username)){ $errors[] = "please Enter a username!"; }else{ if (!preg_match("/^[a-zA-Z ]*$/",$username)) { $errors[] = "Only letters and white space allowed"; }else{ $this-&gt;username = $username; } } if(empty($name)){ $errors[] = "please Enter a name!"; }else{ if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $errors[] = "Only letters and white space allowed"; }else{ $this-&gt;name = $name; } } if(empty($email)){ $errors[] = "please Enter a email!"; }else{ if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format"; }else{ $this-&gt;email = $email; $this-&gt;ftp = $email; } } if(empty($errors)){ return; //no errors all stored fine }else{ return $errors;//this function checks the password and returns an array of errors it is checked on the other end } } public function logout() { session_destroy(); header("Location: ../login.php"); ///destroys all session data and redirects to login } public function userLogin($email, $password) { try{ $sql = "SELECT * FROM accounts where account_email = ?"; $stmt = $this-&gt;connection-&gt;prepare($sql); $stmt-&gt;execute(array($email)); if ($stmt-&gt;rowCount() &gt; 0){ $output = $stmt-&gt;fetch(); $hash = $output['account_password']; if (password_verify($password, $hash)) { header_remove(); header('Location: ./home.php'); $_SESSION['loggedIn'] = 1; $_SESSION['username'] = $output['account_username']; $_SESSION['id'] = $output['account_id']; $_SESSION['name'] = $output['account_name']; $_SESSION['email'] = $output['account_email']; return; //user logged in } else { $_SESSION['loggedIn'] = 0; $error[] = "Wrong Password!"; return $error; //user password didnt match } }else{ $error[] = "User Not Found!"; ///no user found return $error; } }catch (PDOException $e){ //$e-&gt;getMessage(); $error[] = "There is an error Contact help@help.com"; return $error; } } public function userRegister() { //below is the basic code to add a user to the database try{ $sql = "INSERT INTO accounts (account_name, account_password, account_username, account_email, ftp_user) VALUES (?,?,?,?,?)"; $stmt= $this-&gt;connection-&gt;prepare($sql); $stmt-&gt;execute([$this-&gt;name, $this-&gt;password, $this-&gt;username, $this-&gt;email, $this-&gt;ftp]); return; } catch (PDOException $e) { //$error[] = "DataBase Error: The could not be added.&lt;br&gt;".$e-&gt;getMessage(); $error[] = "We already have an account with that username!"; return $error; } } public function changeUserData() { //below is the basic code to add a user to the database try{ $sql = "UPDATE accounts SET account_name=?, account_password=?, account_username=?, account_email =? "; $stmt= $this-&gt;connection-&gt;prepare($sql); $stmt-&gt;execute([$this-&gt;name, $this-&gt;password, $this-&gt;username, $this-&gt;email]); return; } catch (PDOException $e) { $error[] = "DataBase Error: ERROR.&lt;br&gt;".$e-&gt;getMessage(); //$error[] = "We already have an account with that username!"; return $error; } } } </code></pre> <p>db.php</p> <pre><code>function connect_db() { try { $servername = "localhost"; $username = "root"; $password = ""; try { $conn = new PDO("mysql:host=$servername;dbname=main_database", $username, $password); // set the PDO error mode to exception $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e-&gt;getMessage(); } } catch (PDOException $e) { // Proccess error echo 'Cannot connect to database: ' . $e-&gt;getMessage(); } return $conn; } </code></pre> <p>And this is the section at the top of my login page.</p> <pre><code>include("./php/classes/auth_class.php"); if(isset($_SESSION['loggedIn']) &amp;&amp; $_SESSION['loggedIn'] === 1) { header('Location: ./home.php'); } $notification = NULL; if(isset($_POST['submitlogin'])){ $instance = new User(); $loginValidate = $instance-&gt;userlogin($_POST['email'], $_POST['password']); if(empty($loginValidate)){ //Login successfull }else{ //print_r($loginValidate); //login unsucessfull $notification = $loginValidate; } } if(isset($_POST['submitregister'])){ $instance = new User(); $passwordValidate = $instance-&gt;passwordValidator($_POST['upass']); if(empty($passwordValidate)){ $formValueValidator = $instance-&gt;storeFormValues($_POST['uname'],$_POST['fullname'], $_POST['uemail']); if(empty($formValueValidator)){ $registerValidate = $instance-&gt;userRegister(); if(empty($registerValidate)){ ///user registed fine $notification = "Registration complete please login!"; }else{ //print_r($registerValidate); ///prints errors if found with register $notification = $registerValidate; } }else{ ///unable to store form values //print_r($formValueValidator); $notification = $formValueValidator; } }else{ //print_r($passwordValidate); //unable to validate password $notification = $passwordValidate; } } </code></pre> <p>Thanks in advance! Cheers, Greg</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T05:16:59.723", "Id": "427397", "Score": "0", "body": "Not a major, but I find it much easier dealing with code when there's a standard naming convention across methods. For example, in your `User` class you have `passwordValidator()` and `storeFormValues()` - one is like a noun / name, the other like a verb / action. Instead, `validatePassword()` would make sense with `storeFormValues()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-28T08:35:14.637", "Id": "427590", "Score": "0", "body": "That makes sense I will change that thanks! Did you see any other problems?" } ]
[ { "body": "<ul>\n<li><p>Your three password requirements can be baked into one expression.</p>\n\n<pre><code>if (!preg_match('/(?=.*[a-z])(?=.*\\d).{5,}/i', $password)) {\n $this-&gt;errors[] = 'Passwords must have a minimum of 5 characters and contain at least one letter and at least on number';\n return false;\n}\n$this-&gt;password = password_hash($password, PASSWORD_DEFAULT);\nreturn true;\n</code></pre>\n\n<p>Executing one function versus three improves efficiency, but not in a noticeable way. I like to have consistent/dependable return values (rather than returns that sometimes provide an iterable value and sometimes not).</p></li>\n<li><p>For \"tin-foil hat\" reasons, I like to advise that only non-personal data be stored in sessions (as much as possible) because of maliciousness called \"Session Hijacking\". In other words, save an arbitrary <code>id</code>, but not name, email, password, creditcard number, social security number, drivers license, library card, ...anything that might be valuable to bad people who like to spoof, hack, and trick others.</p></li>\n<li><p>I would do away with the <code>rowCount() &gt; 0</code>, you only need to check if <code>fetch()</code> has any data in it. <a href=\"https://stackoverflow.com/a/37611531/2943403\">https://stackoverflow.com/a/37611531/2943403</a></p></li>\n<li><p>By returning boolean or possibly \"truthy\" / \"falsey\" values from your methods, you can reliably construct method calls that easily interpret their success. Consider in the future that you want to return the last inserted id or the number of affected rows from an update/delete query -- if you are passing an array of errors in some instances, you'll first need to assess the return's data type to determine how to handle it. For this reason, make a class variable (<code>$errors</code>) to gather any errors, and always return either iterable or non-iterable data.</p></li>\n<li><p>When checking the returns from your method calls, you are calling <code>empty()</code>, but you can simply use <code>!$variable</code> -- it will know the difference between a falsey <code>null</code> and a truthy array of one or more errors.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T14:35:05.377", "Id": "426694", "Score": "0", "body": "As for storing values in session data would you instead use another function to get them if they are needed to be displayed on a page as appose to storing them in session? Also if im understanding correctly are you saying I should either return true/false or an array and not both? How would I know where it failed if it only returns true or false?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T19:47:46.897", "Id": "426789", "Score": "0", "body": "1. Yes, you use the user's `id` from the session to query the database for what is needed for each page load. Because that value will be the PRIMARY KEY, the query will perform swiftly. 2. Yes, I recommend that pass truthy/falsey return values which share the same data type. If you want to reurn a populated array on failure, that's fine, just pass an empty array on success. This allows you to simply use `if (!$returnValue) {` ( or `if ($returnValue) {`) every time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T19:50:25.020", "Id": "426791", "Score": "1", "body": "When `if (!$booleanReturn) {` (I mean you are returning literal `true`|`false`), you will know to access your `$error` class variable. (`$instance->error`) By the way `instance` is too vague of a variable name because one script may have multiple instances in play. Better to call it `$user` or something specific/relevant." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T12:05:17.610", "Id": "220822", "ParentId": "220728", "Score": "2" } } ]
{ "AcceptedAnswerId": "220822", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:00:46.980", "Id": "220728", "Score": "4", "Tags": [ "php", "sql", "mysql" ], "Title": "PHP Login Class - Security and Efficiency Check" }
220728
<p>I'm new to docker and after much research and stufy I've created a sample application and would like it to be reviewed in case if I'm missing any corner or if there's redundant information that can be simplified.</p> <p><strong>Dockerfile</strong></p> <pre><code>FROM node WORKDIR /src COPY . . RUN npm install CMD ["npm", "start"] </code></pre> <p><strong>docker-compose.yml</strong></p> <p>MySQL is getting initialized through schema.sql</p> <pre><code>version: '3' services: database: image: "mysql:5.7" container_name: "mysql" ports: - "6603:3306" volumes: - ./schema.sql:/docker-entrypoint-initdb.d/init.sql environment: DATABASE_HOST: database MYSQL_ROOT_PASSWORD: rootpass MYSQL_DATABASE: test MYSQL_USER: mysql MYSQL_PASSWORD: password service: build: . image: "node" container_name: "nodejs" ports: - "8080:8080" depends_on: - database links: - database environment: DATABASE_HOST: database MYSQL_PORT: 3306 MYSQL_DATABASE: test MYSQL_USER: mysql MYSQL_PASSWORD: password restart: on-failure </code></pre> <p><strong>index.js</strong></p> <p>It has some delay, that basically waits for the mysql to become fully alive.</p> <pre><code>setTimeout(function(){ var mysql = require('mysql'); var con = mysql.createConnection({ host: process.env.DATABASE_HOST, user: process.env.MYSQL_USER, password: process.env.MYSQL_PASSWORD, database: process.env.MYSQL_DATABASE }); con.connect(function(err) { if (err) throw err; console.log("Database Connected!"); var http = require('http'); //create a server object: http.createServer(function (req, res) { res.write('Hello World!'); //write a response to the client res.end(); //end the response }).listen(8080); //the server object listens on port 8080 console.log("Listening at 8080"); }); }, 10 * 1000); </code></pre> <p>I had one file in docker-compose.yml which I removed assuming it's not required.</p> <pre><code># volumes: # - .:/src </code></pre>
[]
[ { "body": "<p>Probably it's better to you concrete <code>node</code> version.</p>\n\n<p>Also, you can try <a href=\"https://expressjs.com/\" rel=\"nofollow noreferrer\"><code>expressjs</code></a> framework.</p>\n\n<p>I have got simple example of <code>Dockerfile</code> <a href=\"https://github.com/andrzejsydor/docker/tree/master/nodejs\" rel=\"nofollow noreferrer\">here in this sub-directory of my repository</a>.\nBut that is without Docker Compose and connection to any database.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T15:20:13.530", "Id": "225421", "ParentId": "220731", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:57:14.337", "Id": "220731", "Score": "3", "Tags": [ "mysql", "node.js", "dockerfile", "docker" ], "Title": "Reviewing the Dockerfile and docker-compose.yml files for a basic nodejs mysql project" }
220731
<p>I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.</p> <p>Here is my code:</p> <pre><code># This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print ("Select operation.") print ("1. Add") print ("2. Subtract") print ("3. Multiply") print ("4. Divide") choice = input("Enter choice (1/2/3/4): ") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1, "+", num2, "=", add(num1,num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1,num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1,num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1,num2)) else: print("Invalid input") </code></pre> <p>So, I would like to know whether I could make this code shorter and more efficient.</p> <p>Also, any alternatives are greatly welcome.</p> <p>Any help would be highly appreciated.</p>
[]
[ { "body": "<ol>\n<li><p>You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: \"Don't repeat yourself\". In your case you can store all functions and its info in some kind of structure, like dict.</p></li>\n<li><p>You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).</p></li>\n</ol>\n\n<p>Here is the improved code:</p>\n\n<pre><code># This function adds two numbers \ndef add(x, y):\n return x + y\n\n# This function subtracts two numbers \ndef subtract(x, y):\n return x - y\n\n# This function multiplies two numbers\ndef multiply(x, y):\n return x * y\n\n# This function divides two numbers\ndef divide(x, y):\n return x / y\n\nprint(\"Select operation.\")\nprint(\"1. Add\")\nprint(\"2. Subtract\")\nprint(\"3. Multiply\")\nprint(\"4. Divide\")\n\nfunctions_dict = {\n '1': [add, '+'],\n '2': [subtract, '-'],\n '3': [multiply, '*'],\n '4': [divide, '/']\n}\n\nwhile True:\n choice = input(\"Enter choice (1/2/3/4) or 'q' to quit: \")\n if choice == 'q':\n break\n elif choice in functions_dict:\n num1 = int(input(\"Enter first number: \"))\n num2 = int(input(\"Enter second number: \"))\n print('{} {} {} = {}'.format(\n num1,\n functions_dict[choice][1],\n num2,\n functions_dict[choice][0](num1, num2)\n ))\n else:\n print('Invalid number')\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:54:18.740", "Id": "426566", "Score": "0", "body": "I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T01:55:25.167", "Id": "426592", "Score": "0", "body": "Maybe add `print (\"Q. Quit\")` after `print (\"4. Divide\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T12:42:39.240", "Id": "426666", "Score": "1", "body": "A few things: There should be no space after the `print` function. You can also use `elif choice in functions_dict`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T13:13:55.763", "Id": "426672", "Score": "0", "body": "Thank you! `elif choice in functions_dict` is really better than my version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T15:38:06.650", "Id": "426728", "Score": "0", "body": "No if main guard?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T14:32:18.117", "Id": "220735", "ParentId": "220732", "Score": "7" } }, { "body": "<p>One issue I see is with casting the user's input to <code>int</code>:</p>\n\n<pre><code>num1 = int(input(\"Enter first number: \"))\nnum2 = int(input(\"Enter second number: \"))\n</code></pre>\n\n<p>You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.</p>\n\n<p>I suggest either surrounding the input with a try/except block to catch that possibility:</p>\n\n<pre><code>try:\n num1 = int(input(\"Enter first number: \"))\nexcept ValueError:\n print(\"RuhRoh\")\n</code></pre>\n\n<p>Or using <code>str.isdigit()</code>:</p>\n\n<pre><code>num1 = input(\"Enter first number: \")\nif not num1.isdigit():\n print(\"RuhRoh\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T14:33:01.287", "Id": "220736", "ParentId": "220732", "Score": "6" } }, { "body": "<p>I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.</p>\n\n<p>Hopefully this code will show you about regex and such. Findall is quite useful.</p>\n\n<pre><code> import re\n while True:\n my_operation = input(\"Enter a simple arithmetic operation (-+*/), no parentheses:\")\n if not my_operation:\n print(\"Goodbye!\")\n break\n numstrings = re.split(\"[\\*\\+/\\-]\", my_operation) #x*y, for instance\n if len(numstrings) == 1:\n print(\"I need an operation.\")\n continue\n if len(numstrings) != 2: #2*3*4 bails\n print(\"I can only do a single operation right now.\")\n continue\n for my_num in numstrings:\n if not my_num.isdigit(): #e.g. if you try z * 12\n print(my_num, \"is not a digit.\")\n continue\n numbers = [int(x) for x in numstrings] # convert strings to integers\n my_operator = re.findall(\"[\\*\\+/\\-]\", my_operation)[0] #this finds the first incidence of the operators\n out_string = my_operation + \" = \"\n if my_operator == '-': out_string += str(numbers[0] - numbers[1])\n elif my_operator == '+': out_string += str(numbers[0] + numbers[1])\n elif my_operator == '*': out_string += str(numbers[0] * numbers[1])\n elif my_operator == '/': out_string += str(numbers[0] / numbers[1])\n else: print(\"unknown\")\n print(out_string)\n</code></pre>\n\n<p>Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&amp;3 (bitwise and) or 5|3(bitwise or).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T13:14:44.600", "Id": "220828", "ParentId": "220732", "Score": "1" } } ]
{ "AcceptedAnswerId": "220735", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T14:04:28.680", "Id": "220732", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "calculator" ], "Title": "Python program for a simple calculator" }
220732
<p>I wrote code sample below that is finding decimal values in jObject without '.' char, and convert them to long type. The issue is that it works for max jObject that contains two child jObjects.</p> <pre><code>public JObject ModifyDoubleIntegers(JObject objectToModify) { JObject resultObjectModified = new JObject(); foreach (var item in objectToModify) { if (item.Value.Type == JTokenType.Object) { var itemObject = (JObject)item.Value; var itemValues = new JObject(); foreach (var childItem in itemObject) { if (childItem.Value.Type == JTokenType.Object) { var grandChild = (JObject)childItem.Value; var grandChildValues = new JObject(); foreach (var grandChildItem in grandChild) { if (grandChildItem.Value.Type == JTokenType.Float &amp;&amp; !grandChildItem.Value.ToString().Contains('.')) { grandChildValues.Add(new JProperty(grandChildItem.Key, grandChildItem.Value.ToObject&lt;long&gt;())); } else { grandChildValues.Add(new JProperty(grandChildItem.Key, grandChildItem.Value)); } } itemValues.Add(childItem.Key, grandChildValues); } else { if (childItem.Value.Type == JTokenType.Float &amp;&amp; !childItem.Value.ToString().Contains('.')) { itemValues.Add(new JProperty(childItem.Key, childItem.Value.ToObject&lt;long&gt;())); } else { itemValues.Add(new JProperty(childItem.Key, childItem.Value)); } } } resultObjectModified.Add(item.Key, itemValues); } else { if (item.Value.Type == JTokenType.Float &amp;&amp; !item.Value.ToString().Contains('.')) { resultObjectModified.Add(new JProperty(item.Key, item.Value.ToObject&lt;long&gt;())); } else { resultObjectModified.Add(new JProperty(item.Key, item.Value)); } } } return resultObjectModified; } </code></pre> <p>json response from API:</p> <pre><code>{ "id": "F32C93C0AD7B489DA904C10DAE724ED0", "name": "Pixar 99", "amount1": null, "currency": "ZAR", "referenceDate": "2019-04-05T00:00:00+00:00", "dealTeamLeadUser": null, "dealTeamSecondaryUser": null, "projectName": null, "region": { "id": "7680EEE333C648E49135AF52205F7DDC", "name": "Shared" }, "priority": { "code": 3, "description": "Medium" }, "sourceType": { "code": "FUNDINV", "description": "Fund (invested)" }, "sourceContact": { "id": "22F2185C9B0E4D6A9945D00DAA1CA220", "firstName": "Ingeborg", "lastName": "Actili" }, "sourceCompany": { "id": "95495010D5C1470F98184819263CD20C", "name": "Aquila LP" }, "dealType": { "code": "FOF", "description": "Fund of funds" }, "number": 65, "workflow": { "code": "22684BFAD6EC416A861E94ACD07421CF", "description": "2 - Fund of Private Equity" }, "assignedToUser": { "id": "D260BCC5D72C4CBDA8A0003AAEA26120", "displayName": "AddTypeEmpty" }, "assignedToGroup": null, "supervisorUser": { "id": "72BFD2F2725E488E8BB852673042735B", "displayName": "QA TEST eFront" }, "supervisorGroup": null, "status": { "code": "FPE_4", "description": "4 - Detailed evaluation in progress (PE Fund)" }, "nextStepDate": "2020-04-15T00:00:00+00:00", "companyInfo": null, "closingDate": "2021-04-16T00:00:00+00:00", "expectedFinalCloseDate": "2022-04-06T00:00:00+00:00", "ourCommitment": 12000000, "targetIrr": 0.14, "targetTvpi": 3, "fundInfo": { "id": "346A51E0399341ABACFEE92F5B40A9BA", "region": { "id": "7680EEE333C648E49135AF52205F7DDC", "name": "Shared" }, "name": "Antlia Opportunities Fund IV LLP", "shortName": "Antlia IV", "status": { "code": 301, "description": "Prospect Invested Fund" }, "legalForm": { "code": "ZAF-LLP", "description": "ZAF - LLP - Limited Liability Partnership" }, "nature": { "code": "50000000", "description": "50 - Telecommunication Services" }, "category": null, "stage": { "code": "PE_MEZZ", "description": "PE - Mezzanine Capital" }, "geography": { "code": "AFRICA_SOUTHERN", "description": "Southern Africa" }, "vintageYear": 2011, "startDate": "2011-03-16T00:00:00+00:00", "closeDate": "2011-04-30T00:00:00+00:00", "endDate": null, "contractDate": null, "mangtFeesOutsideCommitment": false, "endInvestDate": "2015-04-30T00:00:00+00:00", "endPlannedDate": "2020-04-30T00:00:00+00:00", "endAddPlannedDate": null, "investmentPeriod": null, "fundDuration": null, "additionalYears": null, "clawback": false, "catchup": null, "managementFeesPercent": 0.01, "managementFeesPercent1": 0.01, "managementFeesMore": null, "managementFeesPolicy": null, "country": { "code": "ZA", "description": "South Africa" }, "currency": "ZAR", "carriedInterest": 0.15, "carriedPerDeal": false, "hurdleRate": 0.08, "catchupRate": 0.02, "description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "investmentPolicy": null, "distributionPolicy": null, "revenueDistribution": null, "secondHurdle": 0.03, "hurdleDescription": null, "secondCarried": 0.19, "carriedDescription": null, "managementFrequency": { "code": "QUATERLY" }, "fundGroupBy": { "id": "FC4362360C8F4FF59D6161241E10110E", "name": "eFront Parallel Fund B" }, "managementCompany": { "id": "FE5A9AAAFDE44E01BEA2AF85DF449855", "managementCompanyId": null, "name": "Antlia (Pty) Ltd" }, "otherFund": { "id": "104CB83F393D409D8B3DED9FDCB8EEC9", "region": { "id": "7680EEE333C648E49135AF52205F7DDC", "name": "Shared" }, "name": { "id": "346A51E0399341ABACFEE92F5B40A9BA", "name": "Antlia Opportunities Fund IV LLP" }, "mngtFeesBeforeInvestment": null, "beforeMngtFeesBase": { "code": "COMMITMENT", "description": "Commitment" }, "mngtFeesAfterInvestment": null, "afterMngtFeesBase": { "code": "NAV", "description": "NAV" }, "feeOffset": null, "feeOffsetDescription": "1,00%", "hurdleBase": { "code": "1", "description": "Called capital" }, "hurdleType": null, "size": 4500000000, "extensionMngtFeeBase": null, "minSize": null, "maxSize": null, "firstCloseSize": null }, "hedgeFund": { "id": "2B1B5B97A441493BBD62D560C3E64CB7", "region": { "id": "7680EEE333C648E49135AF52205F7DDC", "name": "Shared" }, "name": { "id": "346A51E0399341ABACFEE92F5B40A9BA", "name": "Antlia Opportunities Fund IV LLP" }, "minimumInvestment": null, "managementFee": null, "redemptionFee": null, "incentiveFee": null, "otherFees": null, "managementFeeHelp": null, "redemptionFeeHelp": null, "incentiveFeeHelp": null, "otherFeesHelp": null, "admissionDates": null, "subscriptionFreq": null, "subscriptionFreqHelp": null, "redemptionFreq": null, "redemptionFreqHelp": null, "redemptionNoticeDays": null, "redemptionNotice": null, "redemptionPayout": null, "highWaterMarkText": null, "sidePocket": null, "sidePocketText": null, "newIssues": null, "newIssuesText": null, "reportingPeriod": null, "reportingStyle": null, "fundAssets": null, "domicile": null, "highWaterMark": null, "hurdleRate": null, "leverage": null, "crystallization": null, "hurdleRateHelp": null, "leverageHelp": null, "crystallizationHelp": null, "lockup": null, "lockupPeriod": null, "lockupPeriodHelp": null, "number1": null, "fiscalDay1": null, "fiscalMonth1": null, "initialVami": null, "benchmark1": null, "benchmark2": null }, "firmContact": { "id": "CC9D6D4E77684E4D82314FA70705BF4E", "name": "Rawlinson, Anthony B." }, "offerCoInvestment": null, "gpCommitment": 0.03, "mngFeesPercentExtension": null, "feeOffset": null, "carryEscrow": 0.23 }, "keyFigures": null, "investment": null, "comments": null, "description": null } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:05:30.227", "Id": "426513", "Score": "0", "body": "Hi. What version of the Newtonsoft library you use? Also, does your code compile?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:19:25.903", "Id": "426518", "Score": "0", "body": "_and it works for max jObject that contains two child jObjects_ - why is this an issue? We'll also need some samples. Could you create a console app (or something) demonstrating how this code works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:24:07.513", "Id": "426523", "Score": "0", "body": "also check this out for recursively finding leaf nodes in this monstrously written API (https://dotnetfiddle.net/5Iae0V)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T17:13:38.207", "Id": "426537", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T17:35:27.780", "Id": "426541", "Score": "0", "body": "I have just noticed that this is not at all recursive... why are calling it like that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T11:52:24.190", "Id": "426660", "Score": "0", "body": "@dfhwze It uses 11.0, and yes it compiles and it is working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T11:52:56.440", "Id": "426661", "Score": "1", "body": "@t3chb0t I've added json response that I am going through, after parsing it with jObject.Parse." } ]
[ { "body": "<h2>Proposed Solution</h2>\n\n<pre><code>public static JObject ModifyDoubleIntegers(JObject source) {\n if (source == null) return null;\n var target = new JObject(source);\n var properties = target.DescendantsAndSelf().Where(\n x =&gt; x.Type == JTokenType.Float).Select(x =&gt; x.Parent).OfType&lt;JProperty&gt;();\n foreach (var property in properties.Where(x\n =&gt; Regex.IsMatch(x.Value.ToObject&lt;string&gt;(), @\"^\\d*$\")))\n {\n property.Value = property.Value.ToObject&lt;long&gt;();\n }\n return target;\n }\n</code></pre>\n\n<hr>\n\n<h2>Remark</h2>\n\n<p>When parsing the sample json file you provided, all integers were parsed as <code>JTokenType.Integer</code> and all floats as <code>JTokenType.Float</code>, so I feel this entire problem is mute. Everything gets parsed correctly by calling <code>JObject.Parse(json)</code>. </p>\n\n<blockquote>\n <p>How did you end up having integer values in a <code>JTokenType.Float</code>?</p>\n</blockquote>\n\n<hr>\n\n<h2>Review</h2>\n\n<p>First of all, you don't need to loop <code>n</code> levels deep. There is a convenient method <code>JContainer.DescendantsAndSelf</code> that does the trick for you. I also changed the variable names to more common names.</p>\n\n<blockquote>\n<pre><code>public JObject ModifyDoubleIntegers(JObject objectToModify)\n{\n JObject resultObjectModified = new JObject();\n foreach (var item in objectToModify)\n {\n ..\n</code></pre>\n</blockquote>\n\n<pre><code> public static JObject ModifyDoubleIntegers(JObject source) {\n if (source == null) return null;\n var target = new JObject(source);\n var properties = target.DescendantsAndSelf();\n ..\n</code></pre>\n\n<hr>\n\n<p>Now, to change the <code>float</code> values to <code>long</code>, you need to obtain all <em>descendants</em> of type <code>JTokenType.Float</code> and select their <em>parent</em> <code>JProperty</code>.</p>\n\n<blockquote>\n<pre><code>foreach (var grandChildItem in grandChild)\n {\n if (grandChildItem.Value.Type == JTokenType.Float))\n {\n ..\n</code></pre>\n</blockquote>\n\n<pre><code>var properties = target.DescendantsAndSelf().Where(\n x =&gt; x.Type == JTokenType.Float).Select(x =&gt; x.Parent).OfType&lt;JProperty&gt;();\n</code></pre>\n\n<hr>\n\n<p>The last step is to change from <code>float</code> to <code>long</code>. I would not filter on <code>Contains('.')</code>, since this depends on your thread's <code>CultureInfo</code>. At my computer, I would have to check on <code>Contains(',')</code>. [after remarks OP] We should use a context-free check on <code>float</code>. The best I can come up with is <code>Regex.IsMatch(value, @\"^\\d*$\")</code>.</p>\n\n<blockquote>\n<pre><code> if (grandChildItem.Value.Type == JTokenType.Float \n &amp;&amp; !grandChildItem.Value.ToString().Contains('.')) \n {\n grandChildValues.Add(new JProperty(\n grandChildItem.Key, grandChildItem.Value.ToObject&lt;long&gt;())); \n }\n</code></pre>\n</blockquote>\n\n<pre><code>foreach (var property in properties.Where(x\n =&gt; Regex.IsMatch(x.Value.ToObject&lt;string&gt;(), @\"^\\d*$\")))\n{ \n property.Value = property.Value.ToObject&lt;long&gt;();\n}\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T16:33:58.897", "Id": "426747", "Score": "0", "body": "It is indeed a good solution, but still not working well. There are differences for all the float type JTokens with values other than integer. They are cutoff after the '.' ex: **\"hurdleRate\": 0.08** becomes **\"hurdleRate\": 0** . That was the reason I was checking for the '.' when I find the **jTokenType.Float**" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T16:36:15.667", "Id": "426749", "Score": "0", "body": "@miskegm I am a bit confused on what exactly you want. I have provided a solution that does exactly the same as yours. Could you please specify what you expect from the code, that would make things a bit easier to follow :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T18:57:15.053", "Id": "426777", "Score": "0", "body": "@miskegm I think I get it now, you want all Integer values that are stored in a float to be stored a long. I will adapt my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T07:59:58.963", "Id": "426833", "Score": "0", "body": "Yes, exactly that, int values stored in float to be stored a long. It works like a charm now. Thanks a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T08:13:39.377", "Id": "426834", "Score": "0", "body": "When parsing json response from server, the jToken float values like amount = 13000, becomes amount = 13000.0, so that is the reason fot this modification I am doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T08:17:12.353", "Id": "426835", "Score": "0", "body": "@miskegm Then perhaps the regex should become @\"^\\d*([,.][0])?$\". Else I think 13000.0 will remain so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T10:48:40.387", "Id": "426863", "Score": "0", "body": "I prefer a visitor like [this](https://codereview.stackexchange.com/questions/208641/chaining-json-transformations-with-visitors) one to traverse and modify the tree similar to the expression-visitor and leave the original tree untouched. Nicely extendable ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T10:52:10.040", "Id": "426866", "Score": "0", "body": "@t3chb0t When building an API for JToken-processing, I would definately go with the visitor and/or listener approaches. For this use-case, I don't mind a simple Linq approach :-)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T14:40:52.917", "Id": "220842", "ParentId": "220737", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:03:45.630", "Id": "220737", "Score": "1", "Tags": [ "c#", "tree", "json" ], "Title": "Parse provided json, and in jObject find and convert all jToken.double types that have whole number value to long type" }
220737
<p>I have written a Python program to check for Armstrong numbers in a certain range.</p> <p>An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, <code>371</code> is an Armstrong number since <code>3**3 + 7**3 + 1**3 = 371</code>.</p> <p>Here is my code:</p> <pre><code>lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) for num in range(lower, upper + 1): order = len(str(num)) sum = 0 temp = num while temp &gt; 0: digit = temp % 10 sum += digit ** order temp //= 10 if num == sum: print(num) </code></pre> <p>Here is an example output:</p> <pre><code>Enter lower range: 200 Enter upper range: 5000 370 371 407 1634 </code></pre> <p>So, I would like to know whether I could make this program shorter and more efficient.</p> <p>Any help would be highly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:36:03.103", "Id": "426499", "Score": "0", "body": "\"sum of the cubes of its digits\"? The power should be equal to the number of digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:38:41.690", "Id": "426500", "Score": "0", "body": "@Sedsarq - taken from - https://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:42:01.070", "Id": "426502", "Score": "0", "body": "@Sedsarq - Yes, you are also right - the power should be equal to the number of digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:46:06.110", "Id": "426504", "Score": "0", "body": "@vurmux - I thought the `performance` tag was necessary as a larger range takes more time to print the output and therefore I needed the code to be as efficient as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:49:51.170", "Id": "426507", "Score": "1", "body": "You're right, so I rolled back the removal." } ]
[ { "body": "<p>Python has a good standard module for work with decimal numbers: <a href=\"https://docs.python.org/3/library/decimal.html#decimal.Decimal\" rel=\"nofollow noreferrer\">decimal</a>. Your code (still <code>C/C++</code>-style) can be replaced with this code:</p>\n\n<pre><code>import decimal\n\n# A separate function to check if the number is an Armstrong number\ndef is_armstrong(number):\n # Get tuple of number digits\n num_digits = decimal.Decimal(number).as_tuple().digits\n # Return the result of check if it is an Armstrong number\n return number == sum(d ** len(num_digits) for d in num_digits)\n\nlower = int(input(\"Enter lower range: \"))\nupper = int(input(\"Enter upper range: \"))\n\nfor num in range(lower, upper):\n if is_armstrong(num):\n print(num)\n</code></pre>\n\n<hr>\n\n<p>About performance:</p>\n\n<p>I checked how long your code works for one million numbers:</p>\n\n<pre><code>import datetime\n\nt1 = datetime.datetime.now()\nfor num in range(1, 1000000):\n order = len(str(num))\n sum_ = 0\n temp = num\n while temp &gt; 0:\n digit = temp % 10\n sum_ += digit ** order\n temp //= 10\n if num == sum_:\n q = num\nt2 = datetime.datetime.now()\nstr(t2-t1)\n</code></pre>\n\n<p>And it returned:</p>\n\n<p><code>'0:00:02.568923'</code></p>\n\n<p>Two and a half seconds. I think it is not the sort of code where one should worry about performance. Moreover, the complexity of each <code>is_armstrong()</code> call is <strong>O(log(N))</strong> (we summarize powers <strong>O(1)</strong> of digits <strong>O(log(N))</strong>) for each number so the result complexity is <strong>O(N log(N))</strong>. For one BILLION numbers this script will work less than hour! It compares favorably with, for example, some kind of graph algorithms with <strong>O(N^3 E^2)</strong> complexity that works for days and every little improvement can save literally hours of CPU working.</p>\n\n<p>P.S. If you aren't familiar with Big O notation, check <a href=\"https://en.wikipedia.org/wiki/Big_O_notation\" rel=\"nofollow noreferrer\">this</a> article in Wikipedia.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:40:55.590", "Id": "426533", "Score": "1", "body": "Good answer, I did not know the Decimal module. Minor point that could be improved: \"return (True if expression else False)\" could be \"return bool(expresion)\" or even \"return express\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:48:43.177", "Id": "426534", "Score": "0", "body": "Definetly! Thank you! I thought that it can be simplified but missed it somehow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:20:42.927", "Id": "426621", "Score": "0", "body": "Considering that the Armstrong numbers are all found already and can be easily googled, it's likely this is more a programming challenge, where performance is the whole point. And percentage wise, there's a lot to shave off from 1M numbers in 2 seconds in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:21:41.113", "Id": "426622", "Score": "1", "body": "`Decimal` is typically imported directly, `from decimal import Decimal`, rather than referenced from within the module. Same with `datetime`: `from datetime import datetime`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:16:55.170", "Id": "220740", "ParentId": "220738", "Score": "11" } }, { "body": "<p><strong>Names</strong></p>\n\n<p>Using <code>sum</code> as a variable name is not adviced as it hides the <code>sum</code> builtin. I'd suggest <code>sum_pow</code> as an alternative.</p>\n\n<p>Also, <code>temp</code> does not convey much information. I'd use <code>remaining</code> even though I am not fully convinced.</p>\n\n<p><strong>Extracting digits from a number</strong></p>\n\n<p>You've used divisions and modulo to compute the different digits for a number. You can use <code>divmod</code> which is a pretty unknown builtin which returns the result for both operations in one go.</p>\n\n<p>That would give:</p>\n\n<pre><code> remaining = num\n while remaining:\n remaining, digit = divmod(remaining, 10)\n sum_pow += digit ** order\n</code></pre>\n\n<p>Also, a better alternative would be to avoid doing this ourselves: extracting the different digits is pretty much what <code>str</code> does for us. Also, we already call it anyway, we could make the most out of it and reuse the result.</p>\n\n<pre><code> num_str = str(num)\n order = len(num_str)\n sum_pow = 0\n for digit in num_str:\n sum_pow += int(digit) ** order\n</code></pre>\n\n<p><strong>More builtins</strong></p>\n\n<p>Disclaimer: next comment may be a bit overwhelming for a beginner. Don't worry, just take your time and read documentation online if need be.</p>\n\n<p>We've already delegated most of the hard work to Python builtins but we can go further. The summing part could be handled by the <code>sum</code> builtin along with generator expressions.</p>\n\n<pre><code>for num in range(lower, upper + 1):\n num_str = str(num)\n order = len(num_str)\n sum_pow = sum(int(digit) ** order for digit in num_str)\n if num == sum_pow:\n print(num)\n</code></pre>\n\n<p><strong>Going further</strong></p>\n\n<p>A few other things could be improved from an organisation point of view:</p>\n\n<ul>\n<li>split the code in functions</li>\n<li>use the <a href=\"https://stackoverflow.com/questions/8228257/what-does-if-name-main-mean-in-python\">if <strong>name</strong> == \"<strong>main</strong>\"</a> check</li>\n</ul>\n\n<p>Going even further, we could write unit tests for the logic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T16:17:29.767", "Id": "220741", "ParentId": "220738", "Score": "14" } }, { "body": "<p>I'm going to focus on the performance aspect, as I believe other parts already have good answers. While the program may be simple and performant, it is still fun to go in and micro-optimize a little. In general I would recommend against it.</p>\n\n<p>Here is your code put into a function to make it clear what changes in the future. I've made the function return the numbers since that was easier for me to work with. I don't have anything new that I would suggest changing.</p>\n\n<pre><code>def armstrong(lower, upper):\n armstrong_numbers = []\n for num in range(lower, upper + 1):\n order = len(str(num))\n sum = 0\n\n temp = num\n while temp &gt; 0:\n digit = temp % 10\n sum += digit ** order\n temp //= 10\n\n if num == sum:\n armstrong_numbers.append(num)\n\n return armstrong_numbers\n</code></pre>\n\n<h2>Precompute</h2>\n\n<p>A google search says another name for these numbers are <a href=\"http://mathworld.wolfram.com/NarcissisticNumber.html\" rel=\"nofollow noreferrer\">narcissistic numbers</a> and that there are only a finite number of them (88 to be exact). We could make a list of the numbers, loop over the list and return the numbers between lower and upper. This only works if someone else has done the work and generated all the numbers already.</p>\n\n<h2>Precompute a little</h2>\n\n<p>The above point could be useful though, the first 9 armstrong numbers are the numbers 1 through 9. Let's \"precompute\" as many of those as we need. We should really add a check to make sure lower &lt;= upper, but alas...</p>\n\n<pre><code>def armstrong(lower, upper):\n cutoff = min(10, upper + 1)\n armstrong_numbers = list(range(lower, cutoff))\n if lower &lt; 10:\n lower = 10\n\n for num in range(lower, upper + 1):\n order = len(str(num))\n sum = 0\n\n temp = num\n while temp &gt; 0:\n digit = temp % 10\n sum += digit ** order\n temp //= 10\n\n if num == sum:\n armstrong_numbers.append(num)\n\n return armstrong_numbers\n</code></pre>\n\n<h2>Optimize the powers</h2>\n\n<p>Another good point that showed up when googling armstrong numbers is that no number bigger than 10<sup>60</sup> can be an armstrong number. This means we can work out every possible answer for digit<sup>order</sup> ahead of time and reuse it each loop. This should be useful as I think computing arbitrary powers is not as fast as looking up the answer in a table.</p>\n\n<p>As plainly as I can state it, there are only 10 digits, and order is at most 60, so we can make a table 10 * 60 big that stores all the answers to digit<sup>order</sup> and use that instead.</p>\n\n<pre><code>def armstrong(lower, upper):\n cutoff = min(10, upper + 1)\n armstrong_numbers = list(range(lower, cutoff))\n if lower &lt; 10:\n lower = 10\n\n powers_table = [[d ** n for d in range(10)] for n in range(60)]\n\n for num in range(lower, upper + 1):\n order = len(str(num))\n row = powers_table[order] # We only care about one row of the table at a time.\n sum = 0\n\n temp = num\n while temp &gt; 0:\n digit = temp % 10\n sum += row[digit]\n temp //= 10\n\n if num == sum:\n armstrong_numbers.append(num)\n\n return armstrong_numbers\n</code></pre>\n\n<h2>Check less numbers</h2>\n\n<p>The last idea that I <a href=\"http://delivery.acm.org/10.1145/1970000/1963548/p43-rolfe.pdf?ip=149.157.244.164&amp;id=1963548&amp;acc=ACTIVE%20SERVICE&amp;key=846C3111CE4A4710.AB4E84BDC4F162A6.4D4702B0C3E38B35.4D4702B0C3E38B35&amp;__acm__=1558556675_21302e0a6b066982c4f798f95ce4e79e\" rel=\"nofollow noreferrer\">found online (see section 5)</a> is to skip numbers with certain prefixes. We can guarantee a number will never work if it the sum of all of its digits except the last one is odd.</p>\n\n<p>The reason for this is as follows. Raising a number to a power won't change its parity. In other words if a number x is even, x<sup>n</sup> is also even. If x is odd x<sup>n</sup> is also odd. The sum of the digits raised to a power n will have the same parity as the sum of the digits. For example if we have the 3 digit number 18X. The sum of it's digits cubed is 1**3 (odd) + 8<sup>3</sup> (even) + X<sup>3</sup> which is the same as 1 (odd) + 8 (even) + X.</p>\n\n<p>Assume the sum of all the digits of an armstrong number excluding the last digit is odd then we have either</p>\n\n<pre><code>(A**n + B**n + C**n + ...W**n) + X**n == odd + X**n == odd if X is even or\n(A**n + B**n + C**n + ...W**n) + X**n == odd + X**n == even if X is odd\n</code></pre>\n\n<p>But if the last digit (X) is even, the sum has to be even it to which it isn't.\nIf the last digit is odd, the sum has to be odd, but it isn't. Either way, we get a contradiction, so our assumption must be wrong.</p>\n\n<p>The code is a bit messy, but it gives the idea. It agrees with the other snippets above for the query (1, 100000)</p>\n\n<pre><code>def armstrong3(lower, upper): \n cutoff = min(10, upper + 1) \n armstrong_numbers = list(range(lower, cutoff)) \n if lower &lt; 10: \n lower = 10 \n\n powers_table = [[d ** n for d in range(10)] for n in range(60)] \n\n start, end = lower // 10, upper // 10 \n for leading_digits in range(start, end + 1): \n if sum(c in \"13579\" for c in str(leading_digits)) % 2 == 1: \n # Skip numbers with an odd sum parity \n continue \n\n order = len(str(leading_digits)) + 1 # We will add a last digit later \n row = powers_table[order] # We only care about one row of the table at a time. \n sum = 0 \n\n temp = leading_digits \n while temp &gt; 0: \n digit = temp % 10 \n sum += row[digit] \n temp //= 10 \n\n for last_digit in range(10): \n final_total = sum + row[last_digit] \n if 10 * leading_digits + last_digit == final_total and final_total &lt;= upper: \n armstrong_numbers.append(num) \n\n return armstrong_numbers\n</code></pre>\n\n<p>Micro-benchmarked locally I get the following</p>\n\n<pre><code>%timeit armstrong(1, 100000)\n143 ms ± 104 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n%timeit armstrong2(1, 100000)\n69.4 ms ± 2.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n%timeit armstrong3(1, 100000)\n14.9 ms ± 31.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n</code></pre>\n\n<p>So the extra tuning was worth it.</p>\n\n<h2>Other work</h2>\n\n<p>I didn't get around to implementing the ideas at this <a href=\"https://github.com/shamily/ArmstrongNumbers\" rel=\"nofollow noreferrer\">github project</a>. The code is in java and run with N &lt; 10 at the smallest (above you can see my benchmarks were only for N &lt; 5), so I don't think the performance is anywhere near as good as that code. It would be the next place to go if you are interested in pushing things further.</p>\n\n<p>I looked at using divmod instead of modding and dividing by 10. The performance was worse for me, so I chose not to use it.</p>\n\n<pre><code>%timeit armstrong(1, 100000)\n143 ms ± 104 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n%timeit armstrong_divmod(1, 100000)\n173 ms ± 5.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T02:56:21.827", "Id": "426594", "Score": "0", "body": "Upvoted! Thanks for the amazing response. It helped me a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:02:16.360", "Id": "220765", "ParentId": "220738", "Score": "6" } }, { "body": "<p>It would save a lot of time to start from the other end, by making the sums first. Notice that a digit combination like (1, 2, 3) is shared by six numbers: 123, 132, 213, 231, 312, 321. They all have the same digit cube sum 1^3 + 2^3 + 3^3 = 36. Your code will iterate over those numbers and recalculate the same sum 6 times.</p>\n\n<p>Instead, you could use the digit combination (1, 2, 3) and calculate the digit cube sum 36 once. Then check if the digits in that sum is a permutation of those in the digit combination - if so, it's an Armstrong number. Then move to the next digit combination (1, 2, 4) to check another six numbers in one fell swoop.</p>\n\n<p>The digit combinations can be iterated over using <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools.combinations_with_replacement\" rel=\"noreferrer\">itertools.combinations_with_replacement</a>. Here's an example that generates all Armstrong numbers of length 1 to 10 (so under 10 billion), running in under 3 seconds on my machine:</p>\n\n<pre><code>from itertools import combinations_with_replacement\n\narmstrongs = []\nfor length in range(1, 11):\nfound = []\nfor digits in combinations_with_replacement(range(10), length):\n\n # make the digit power sum\n s = sum(pow(d, length) for d in digits)\n\n # collect the digits of the sum\n temp = s\n sumdigits = []\n while temp:\n temp, d = divmod(temp, 10)\n sumdigits.append(d)\n\n # compare the two digit groups. Notice that \"digits\" is already sorted\n if list(digits) == sorted(sumdigits):\n found.append(s)\n\n# the sum-first-method doesn't find Armstrong numbers in order, so\n# an additional sorting is thrown in here.\narmstrongs.extend(sorted(found))\n\nprint(armstrongs)\n</code></pre>\n\n<p>This could be optimized further, by for example checking if <code>sumdigits</code> has the right length before sorting. You could also check the digit <code>d</code> as it's chopped off from the sum and make sure it exists at all within <code>digits</code>. If not, the two digit groups are clearly different and you can move to the next iteration.</p>\n\n<hr>\n\n<p>Now, this example doesn't limit the results to a range. But it can quite easily be modified to do so: Check the lengths of the boundary numbers, then use those in the <code>for length in range(1, 11):</code> line to only generate Armstrong numbers of relevant length. So modify the top to:</p>\n\n<pre><code>lower = 400\nupper = 15000\n\nlowerlength = len(str(lower))\nupperlength = len(str(upper))\narmstrongs = []\nfor length in range(lowerlength, upperlength + 1):\n</code></pre>\n\n<p>Then generate the numbers as before, and once you have them, filter down:</p>\n\n<pre><code>armstrongs = [n for n in armstrongs if lower &lt;= n &lt;= upper]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:08:12.077", "Id": "426617", "Score": "0", "body": "Upvoted! Thanks for the answer. It helped me a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:01:14.577", "Id": "220794", "ParentId": "220738", "Score": "8" } } ]
{ "AcceptedAnswerId": "220741", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T15:04:06.647", "Id": "220738", "Score": "9", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Python program to find Armstrong numbers in a certain range" }
220738
<p>A linked list is a data structure that has a beginning, and an end. The only way through the structure is to go to the "next step", like stepping stones. This linked list works the same way, but in ascending order.</p> <p>There's two things I'd like to know about this code:</p> <ol> <li>Are there any <strong><em>efficiencies</em></strong> I can make?</li> <li>What methods could I use to make the sorting more <strong><em>generalized</em></strong> (like inputting a scriptblock as a parameter for sorting)</li> </ol> <pre><code>&lt;# .SYNOPSIS Basic sorted Linked List implementation for practice and understanding .DESCRIPTION A list of objects linked together by pointing to the previous or next nodes. The list is lead by and preceeded by nil nodes (Nodes with a value of $null) and are currently sorted in ascending order. .TODO Add customizable sorting preference to the Linked List #&gt; class Node { &lt;# .SYNOPSIS Basic Node class that holds the previous and next items in a the linked list .DESCRIPTION The Node class is used to represent items in a Linked List. Each Node has a Previous and Next node. These Nodes can be $null or have any PSObject inside them. On creation, each Node creates a seperate 'Nil' node, which has no Nodes next to them, and a value of $null. #&gt; [Node] $previous [PSObject]$data [Node] $next Node() {} Node($value) { $this.data = $value $this.previous = [Node]::new() $this.next = [Node]::new() } [String] ToString(){ return "$($this.data)" } } class linkedList { &lt;# .SYNOPSIS Linked List class that sorts PSObjects in Ascending order. .DESCRIPTION The Linked List class starts with two `Nill` Nodes. As more Nodes are added, they're inserted in ascending order, depending on their return type. Integars will be ordered from -inf to inf, and Strings will be alphabetically. Items that equate will not be added. Inserting a 5 into a list that already has a 5 in it, will not be added. Alternatively, adding a "Z" when "z" is already added will also not work. Item is not replaced, just is not entered. .EXAMPLE $list = [linkedList]::new() $list.insert(5) $list.insert(2) $list.insert(11) $list.insert(12) $list.insert(1) $list.toString() &gt;&gt; nil -&gt; 1 -&gt; 2 -&gt; 5 -&gt; 11 -&gt; 12 -&gt; nil .EXAMPLE $list = [linkedList]::new() $list.insert('Z') $list.insert('c') $list.insert('z') $list.insert('a') $list.insert('C') $list.insert('J') $list.insert('r') $list.insert('Q') $list.toString() &gt;&gt; nil -&gt; a -&gt; c -&gt; J -&gt; Q -&gt; r -&gt; Z -&gt; nil #&gt; [Node]$head linkedList() { $this.head = [Node]::new($null) } hidden [Node] searchItem ([PSObject]$o, [switch]$add=$false) { &lt;# .SYNOPSIS Looks for the PSObject specified by $o .DESCRIPTION Searches for the item specified in $o within the list. If the item is in the list, it's returned. If the item is not in the list, the last valid node is returned. If the item is not in the list and $add is $true, then the node that would otherwise be before the searched item is returned. This allows the Insert function to add the node in the proper location. #&gt; [Node]$currNode = $this.head [Node]$prevNode = $null # Return the Head if it's the first item in the list. if( $this.head.get_next() -eq $null ){ return $this.head } while ($currNode -and $currNode.get_next()){ $currData = $currNode.get_data() # return the node if it's found if ($currData -eq $o) { return $currNode } # Return previous node if the current node is larger than the item being evaluated if ($currData -gt $o -and $add) { return $prevNode } # Return the last non-nil node in the list if we hit the end if (!$currNode.get_next() -and $add){ return $currNode } $prevNode = $currNode $currNode = $currNode.get_next() } return $prevNode } [PSObject] search ([PSObject]$obj){ &lt;# .SYNOPSIS Returns the value of the node being searched for .DESCRIPTION Searches for the item specified in $o within the list. If the item is in the list, it's returned. If the item is not in the list, $null is returned. #&gt; $returnObj = $this.searchItem($obj, $false) if($obj -eq $returnObj.get_data()){ return $returnObj.get_data() } return $null } insert ($o) { &lt;# .SYNOPSIS Inserts the PSObject requeste .DESCRIPTION Searches for the item specified in $o within the list. If the item is in the list, it's returned. If the item is not in the list, $null is returned. #&gt; $currNode = $this.searchItem($o, $true); $nNode = [Node]::new($o) # Do not insert a repeated item if($currNode.get_data() -eq $o){ return } # Insert new item after the "next lowest" object data elseif( $o -gt $currNode.get_data() ){ $this.swap($currNode, $nNode, $currNode.next) } } hidden swap($prev, $new, $next){ &lt;# .SYNOPSIS Sets the Next and Previous nodes for new nodes. .DESCRIPTION Set the Next and Previous nodes in the $new Node. Correct the Next and Previous pointers for the Prev and Next nodes, respecitvely. #&gt; $new.set_previous($prev) $new.set_next($next) $prev.set_next($new) $next.set_previous($new) } [String] ToString(){ $s = "nil" $curr = $this.head while($curr.get_next()) { $s += "$($curr.get_data()) -&gt; " $curr = $curr.get_next() } return ($s + ("nil",$curr.get_data())[!!$curr.get_data()]) } } </code></pre> <p><strong>Sample:</strong></p> <pre><code> $numOfObjects = 10 $list = [linkedList]::new() 1..$numOfObjects | % { $item = -join (( 0x41..0x5A) + ( 0x61..0x7A) | Get-Random -Count $numOfObjects | % {[char]$_}) $list.insert($item) } $list.ToString() -replace " -&gt; ","`n" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T16:11:47.827", "Id": "426740", "Score": "0", "body": "Is there a particular reason for disuse the (generic) [`LinkedList<T>` Class](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T16:19:31.623", "Id": "426744", "Score": "0", "body": "@JosefZ I’m mostly doing it for understanding/practice with the concept. It’s not something thats going to be used practically, otherwise I would use it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T18:10:12.753", "Id": "220748", "Score": "4", "Tags": [ "beginner", "object-oriented", "sorting", "linked-list", "powershell" ], "Title": "Sorted LinkedList" }
220748
<p>This function (<code>find_prefix</code>) is supposed to find words starting with a given prefix in a container. The container is sorted. This function is a fairly performance-critical part of the code, so I am open for any optimization suggestions. Here is a brief usage case; <code>test_in</code> is <a href="https://github.com/dwyl/english-words" rel="nofollow noreferrer">a file</a> with <code>\n</code> separated English words:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;string&gt; #include &lt;iterator&gt; #include &lt;tuple&gt; #include &lt;fstream&gt; template &lt;typename It_beg, typename It_end, typename Prefix&gt; auto find_prefix(const It_beg beg, const It_end end, Prefix prefix) { auto low = std::lower_bound(beg, end, prefix); ++prefix.back(); auto up = std::lower_bound(beg, end, prefix); return std::make_tuple(low, up); } int main() { std::string s; std::fstream file("test_in"); if (!file) { std::cerr &lt;&lt; "Failed to open the file\n"; return -1; } std::vector&lt;std::string&gt; svec; svec.reserve(470000); while (file &gt;&gt; s) { svec.push_back(s); } std::sort(svec.begin(), svec.end()); while (std::cin &gt;&gt; s) { auto [beg, end] = find_prefix(svec.cbegin(), svec.cend(), s); std::copy(beg, end, std::ostream_iterator&lt;std::string&gt;(std::cout, "\n")); } return 0; } </code></pre> <p>When the input is "stack" we get this output:</p> <pre class="lang-none prettyprint-override"><code>stack stack's stack-garth stackable stackage stacked stackencloud stacker stackering stackers stacket stackfreed stackful stackgarth stackhousiaceous stacking stackless stackman stackmen stacks stackstand stackup stackups stackyard </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T19:32:23.183", "Id": "426552", "Score": "0", "body": "I don't think this works. If `prefix.back()` is already the max value the result will be incorrect (and incrementing the max value will also be undefined behaviour for signed types)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T19:41:20.653", "Id": "426554", "Score": "0", "body": "`beg` and `end` of different types?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:18:13.430", "Id": "426559", "Score": "2", "body": "I recommend creating an example (a small file with includes, the code above, and some usage cases). Some more elaboration on the code, the problem and conditions in which the code will be run (input patterns, whether from file or not, etc) will be welcome too. I know the code is short, but there can be a lot to say about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:41:47.647", "Id": "426562", "Score": "0", "body": "@Incomputable is it alright now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:42:39.823", "Id": "426563", "Score": "0", "body": "@vnp tried to be as general as possible honestly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:45:48.787", "Id": "426564", "Score": "0", "body": "@user673679 do you suggest I check for the overflow case in the function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T22:33:15.743", "Id": "426582", "Score": "1", "body": "@Ayxan, certainly. Lets see what others think" } ]
[ { "body": "<ol>\n<li><p>As you are effectively reading the whole file <code>test_in</code> into memory in lots of small independent chunks, consider a different approach:</p>\n\n<ol>\n<li>Read the whole file as one big chunk, or preferably simply map it.</li>\n<li>Put <code>std::string_view</code>s into that array in the vector, instead of strings.</li>\n</ol>\n\n<p>Most <code>std::string</code>s employ SSO, meaning there are two possible states (external string, active SSO), in contrast to the single one for <code>std::string_view</code>. Thus, no branch-misprediction.</p>\n\n<p>Additionally, <code>std::string</code> is generally at least twice the size of <code>std::string_view</code>, so this about halves the size of the vector's data.<br>\nDue to allocator overhead, all the small bits of string data would also together likely need considerably more space than that one big chunk.</p></li>\n<li><p>You copy the prefix on calling <code>find_prefix()</code>. Better pass a view.</p></li>\n<li><p>When you know where the range you want starts, you know it won't end earlier.</p></li>\n<li><p><code>++prefix.back();</code> is blatantly wrong.</p>\n\n<ol>\n<li><p>If the prefix is empty, it's Undefined Behavior.</p></li>\n<li><p>If it causes signed overflow, it's Undefined Behavior.</p></li>\n<li><p>If it causes unsigned wrap-around, you simply get a completely wrong end-position, which might even lie before the start-position.</p></li>\n</ol>\n\n<p>I suggest simply writing your own comparator and using <code>std::upper_bound()</code> too, as it is intended to be used.</p>\n\n<p>Be aware that <code>char</code> is treated as <code>unsigned char</code> for comparison by <code>std::char_traits&lt;char&gt;</code>. You probably want to mirror that, especially as you used that rule when sorting... I won't go to the trouble of staying that general.</p></li>\n<li><p><code>std::equal_range()</code> with a custom comparator does what you want:</p>\n\n<pre><code>template &lt;class RandomAccessIterator&gt;\nauto find_prefix(RandomAccessIterator first, RandomAccessIterator last, std::string_view prefix) {\n return std::equal_range(first, last, prefix,\n [n = prefix.size()](std::string_view a, std::string_view b) noexcept {\n return a.substr(0, n) &lt; b.substr(0, n);\n });\n}\n</code></pre></li>\n<li><p>You don't need <code>std::make_tuple</code> in C++17. Just use <code>std::tuple</code> directly:</p>\n\n<pre><code>return std::tuple{low, up};\n</code></pre></li>\n<li><p>By the way, <code>return 0;</code> is implicit for <code>main()</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T02:37:36.980", "Id": "220784", "ParentId": "220752", "Score": "9" } } ]
{ "AcceptedAnswerId": "220784", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T18:41:37.730", "Id": "220752", "Score": "6", "Tags": [ "c++", "performance", "strings" ], "Title": "Find words with this prefix" }
220752
<p>I'm working on a new API written in Swift 5 and I wanted to play with the new <code>Result</code>. I wanted to know what you guys think about this syntax: </p> <pre class="lang-swift prettyprint-override"><code>enum NetworkRequestError: Error { case hostNotAvailable case accountNotAvailable func finish&lt;T&gt;() -&gt; Result&lt;T, NetworkRequestError&gt; { return .failure(self) } } public class NetworkClient: TestableAPI { var host: String? func fetch(result: @escaping (Result&lt;(any: [Any], any1: [Any]), NetworkRequestError&gt;) -&gt; Void) { guard host != nil else { result(NetworkRequestError.hostNotAvailable.finish()) return } } } </code></pre>
[]
[ { "body": "<p>I would not recommend this pattern. I see no compelling reason to encumber <code>NetworkRequestError</code> (and presumably every other <code>Error</code> enumeration throughout your project) with this <code>finish</code> cruft. </p>\n\n<p>So, instead of:</p>\n\n<pre><code>enum NetworkRequestError: Error {\n case hostNotAvailable\n case accountNotAvailable\n\n func finish&lt;T&gt;() -&gt; Result&lt;T, NetworkRequestError&gt; {\n return .failure(self)\n }\n}\n\nfunc fetch(result: @escaping (Result&lt;(any: [Any], any1: [Any]), NetworkRequestError&gt;) -&gt; Void) {\n guard host != nil else {\n result(NetworkRequestError.hostNotAvailable.finish())\n return\n }\n\n ...\n}\n</code></pre>\n\n<p>I’d instead suggest:</p>\n\n<pre><code>enum NetworkRequestError: Error {\n case hostNotAvailable\n case accountNotAvailable\n}\n\nfunc fetch(result: @escaping (Result&lt;(any: [Any], any1: [Any]), NetworkRequestError&gt;) -&gt; Void) {\n guard let host = host else {\n result(.failure(.hostNotAvailable))\n return\n }\n\n ...\n}\n</code></pre>\n\n<p>This is more concise, conforms to established patterns (making it easier to reason about) and it doesn’t entangle <code>Error</code> types and <code>Result</code> types. </p>\n\n<p>Also you’re undoubtedly checking <code>host</code> because you’re going to use it later in this method, so you might as well do <code>guard let</code>, like above. It saves you from having to do subsequent unwrapping of the optional.</p>\n\n<hr>\n\n<p>I’m assuming your question was primarily about the <code>Error</code> type and this <code>finish</code> method. I must say that I am equally uneasy about the <code>.success</code> associated type, namely the tuple of <code>[Any]</code> arrays. Perhaps this was just a placeholder in your example, but I generally find references to <code>Any</code> to be code smell. Often specific types or generics would be better than <code>Any</code> to types in one’s code. If you have a question about why you’re using a “success” type which is two arrays of <code>Any</code>, that might warrant its own question, showing why you did that. It, too, could probably be improved. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:44:51.157", "Id": "426626", "Score": "0", "body": "Thanks for you clear and detailed answer Rob ! I will follow what you suggest, that was my primary implementation of the result block but I'm using it 3 times in the function so I was wondering if I could shorten my guard statements.But this `it doesn’t entangle Error types and Result types` made it. For the [Any] part, I am not using them in real life, I'm using real objects, but thanks for your concern !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T02:23:42.173", "Id": "220782", "ParentId": "220754", "Score": "4" } } ]
{ "AcceptedAnswerId": "220782", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T18:57:00.043", "Id": "220754", "Score": "5", "Tags": [ "error-handling", "swift", "generics", "networking", "enum" ], "Title": "Enum for handling network request errors in Swift" }
220754
<p>My objective is to find a hash collision of my modified hash function. Assuming my modified hash only outputs the first 36 bits of SHA-1. As we know, SHA-1 is a 160-bit hash value, hence, we only need to output 9 characters out of 40 characters for comparison. </p> <p>How i begin my program is by hashing a string (I have a SHA-1 algorithm running and i will name it as sha1. I have also ensured that the output of the SHA-1 algorithm is correct.)</p> <p>Firstly, i would hardcode 2 string and extract out 9 characters out of 40 characters since i require only the first 36 bits of SHA-1. The function below basically return a true if a collision is found and false if a collision is not found</p> <pre><code>public static boolean findCollision(int x1, int x2) { String message1 = "I tried " + x1 + " iteration to find a collision"; String message2 = "I tried " + x2 + " iteration to find a collision"; //hashing my string and extracting 9 characters String message_hash1 = sha1(message1); String message_hash2 = sha1(message2); String modified_hash1 = message_hash1.substring(0, 9); String modified_hash2 = message_hash2.substring(0, 9); if (modified_hash1.equals(modified_hash2)) return true; else return false; } </code></pre> <p>Lastly, i will have a main function that will random Integers up to MAX_VALUE in a infinite loop and will break out if and only if a hash is found.</p> <pre><code>public static void main(String[] args) { Random random = new Random(); int x1 = 0; int x2 = 0; int counter = 0; while (true) { while(true){ x1 = random.nextInt(Integer.MAX_VALUE); x2 = random.nextInt(Integer.MAX_VALUE); if (x1 != x2) break; } if (findCollision(x1, x2) == true) { break; } counter++; } System.out.println("\nNumber of trials: " + counter); } </code></pre> <p>If i tried taking only the first 24 bits of SHA-1, i could easily find a collision. However, i'm unable to find a collision for 36 bits instead despite running it for hours. Hence, I'm wondering what is other alternative way for me to find a collision with just 36 bits of SHA-1.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T19:46:27.267", "Id": "426555", "Score": "0", "body": "Out of curiosity, why are you trying to do this? Is it because you want to see if your modified algorithm is good?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T19:54:03.687", "Id": "426557", "Score": "0", "body": "You should mention this in your question, I believe it's important :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T19:56:04.807", "Id": "426558", "Score": "0", "body": "i have done so. thanks!" } ]
[ { "body": "<p><strong>I realized that while typing this, you should look into the <a href=\"https://en.wikipedia.org/wiki/Birthday_attack\" rel=\"nofollow noreferrer\">Birthday Attack</a>, which will probably much more elaborated than my answer, lol.</strong></p>\n\n<p>Considering your have 36 bits of data, it means you have a total number of possibilities of <span class=\"math-container\">\\$2^{36} = 68719476736\\$</span>. Based on the <a href=\"https://en.wikipedia.org/wiki/Pigeonhole_principle\" rel=\"nofollow noreferrer\">Pigeonhole principle</a>, if you compared the hashed of 68719476736 different strings, you'd get a collision.</p>\n\n<p>So that's easy! All you need to do is run this (pseudocode): </p>\n\n<pre><code>hashset = (new hashset that uses your hashing algorithm)\nfor(i = 0; i &lt; 68719476736 + 1; i++) {\n\n if hashset.contains(string(i)) break; \n\n hashset.add(string(i));\n}\n\nprint(\"This took \" + i + \" tried!\")\n</code></pre>\n\n<p>With this, you're <strong>guaranteed</strong> to get a collision. <strong>But</strong> there's a problem. If every iteration took 100 milliseconds, you'd need about 217 years to get a solution. Tell your teacher your great-great-grandchildren will get back to you with a solution. You could also buy 2000 computers to run this in ~40 days.</p>\n\n<p>My algorithm is pretty much guaranteed to finish (assuming none of the computers crash in any way), yours isn't. This is more of a lesson on \"how to test things\", which is valuable for developers. When you want to test something, try not to be random. The thing with your algorithm is that maybe you wouldn't ever get collisions. I understand that you kind of need randomness if you want this to finish running this one day.</p>\n\n<p>So the question is, what could we do to make this better?</p>\n\n<p>We could check about how many different strings we'd need to get a good enough chance there's a collision. It's kind of the <a href=\"https://en.wikipedia.org/wiki/Birthday_problem\" rel=\"nofollow noreferrer\">Birthday Problem</a> which gives us an easy way to calculate what are the chances n different persons have the same birthday in a group of m persons.</p>\n\n<p>We can use the formula under <em>Approximation of number of people</em> and adapt it to our problem to understand that if we had 68719476736 + 1 strings in our possession (for example, every number between 1 and 68719476736 + 1), you'd need to pick 308652 of those to have about 50% chances of having a collision.</p>\n\n<p>What you could try is randomly take 308652 numbers between 1 and 68719476736 + 1 and hash them to find a collision. Repeat this as long as you don't have a collision. </p>\n\n<p>The pseudocode would look like this :</p>\n\n<pre><code>generator = RandomBigIntGenerator()\nnumbers = []\n\nfor(i = 0; i &lt; 308652; i++) {\n numbers.add(generator.random(1,68719476736+1))\n}\n\nhashset = {} (With your hashing function)\nfor n in numbers {\n if hashset.contains(n) {\n print(\"yay done\");\n break;\n }\n hashset.add(m);\n}\n</code></pre>\n\n<p>All in all, you can hope to have collisions, but you need computing power.</p>\n\n<p>In a code review point of view :</p>\n\n<ul>\n<li>You need to keep track of the strings you already tried, they give you valuable information that can actually help you find collision.</li>\n<li>Don't be <em>too</em> random when you create your strings.</li>\n<li>Understand that 68719476736 is a biiggg number, but still so much smaller than the <strong>1461501637330902918203684832716283019655932542976</strong> possible values the SHA1 have :)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:04:14.183", "Id": "426567", "Score": "0", "body": "I will try this birthday paradox method right now. Hopefully it will work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-28T15:53:57.300", "Id": "427658", "Score": "0", "body": "@AstralZhang don't forget to mark an answer as accepted if it helped you resolve your problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:43:31.903", "Id": "220761", "ParentId": "220756", "Score": "3" } }, { "body": "<p>With 24 bits, there are approximately 16.8 million possible hashes, so on average, you'd have to try 8.4 million pairs until you find a collision. With 36 bits, the numbers have to be multiplied by 4096, which yields 68 respectively 34 billion. You can cut this in half by not computing two hashes during each iteration, but instead computing one before the loop and keeping it constant.</p>\n\n<p>However, that is probably still more time than you want to spend. One way to reduce that time is to utilize the Birthday Paradox (<a href=\"https://en.m.wikipedia.org/wiki/Birthday_problem\" rel=\"nofollow noreferrer\">https://en.m.wikipedia.org/wiki/Birthday_problem</a>). By computing a list of hashes and comparing each one with each other your chances of finding a collision are much higher. I won't try to type a complete algorithm on this phone screen, though :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:57:09.463", "Id": "220764", "ParentId": "220756", "Score": "3" } } ]
{ "AcceptedAnswerId": "220761", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T19:20:59.107", "Id": "220756", "Score": "7", "Tags": [ "java", "time-limit-exceeded", "cryptography", "hashcode" ], "Title": "Finding collisions of the first few bits of a SHA-1 hash" }
220756
<p>I'm trying to extend my coding skills to other languages by doing projects. (learned Java in school) and since python is very popular right now thats what I ended up choosing for this project, though I'm fairly new to it. Does this code follow common best practices? Is there anything I can do to improve this program so it's more readable/ understandable.</p> <pre class="lang-py prettyprint-override"><code>import re, json, os, requests import browsercookie class Hackerrank_Session: LOGIN_DATA = { 'login': '', 'password': '', } HEADERS = { 'x-csrf-token': '', 'cookie': '', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36' } BASE_URL = 'https://www.hackerrank.com/' URL_HACKERRANK_PTS = 'https://www.hackerrank.com/domains/algorithms?filters%5Bstatus%5D%5B%5D=unsolved&amp;badge_type=problem-solving' URL = '' SUBMISSIONS = {} LANGUAGE = { 'python3': { 'main': "if __name__ == '__main__':", 'import': ["#!/bin/python3", "import(.*?)(\n)+"], 'extension': "py", 'comment': "#" }, 'java8': { 'main': r"private static final Scanner scanner = new Scanner(System.in);", 'import': ["", "import(.*?)(\n)+"], 'extension': "java", 'comment': "//" }, 'java': { 'main': r"private static final Scanner scanner = new Scanner(System.in);", 'import': ["", "import(.*?)(\n)+"], 'extension': "java", 'comment': "//" }, 'C': { 'main': "int main()", 'import': ["", "#include(.*?)(\n)+"], 'extension': "c", 'comment': "//" }, 'JavaScript': { 'main': "function main()", 'import': ["", "'use strict';(.*?)// Complete"], 'extension': "js", 'comment': "//" } } def __init__(self): return # Gets the needed cookies to keep a session active on www.hackerrank.com def getHackerrankCookies(self): Chrome_Cookies = str(browsercookie.chrome()._cookies) if not re.findall("name='hackerrank_mixpanel_token', value='(.*?)'", Chrome_Cookies) and re.findall("name='_hrank_session', value='(.*?)'", Chrome_Cookies): raise Exception("No Hackerrank Cookie Found. Signed In Required.") else: cookie_hk = 'hackerrank_mixpanel_token=' cookie_hk += re.findall("name='hackerrank_mixpanel_token', value='(.*?)'", Chrome_Cookies)[0] + '; ' cookie_hk += '_hrank_session=' cookie_hk += re.findall("name='_hrank_session', value='(.*?)'", Chrome_Cookies)[0] + '; ' self.HEADERS['cookie'] = cookie_hk # Gets token from www.hackerrank.com def getHackerrankToken(self): login = requests.post(self.BASE_URL + '/rest/auth/login', data = self.LOGIN_DATA ) if re.findall('Invalid login or password', login.text): print("ERROR: Invalid login or password.") else: if 'csrf_token' not in login.json(): raise Exception("csrf_token not found.") else: login.json()['csrf_token']: token = str(login.json()['csrf_token']) self.HEADERS['x-csrf-token'] = token # Gets www.hackerrank.com scores. def getScores(self): scores_page = requests.get(self.URL_HACKERRANK_PTS, headers=self.HEADERS) scores = re.findall('class="value"&gt;(.*?)&lt;', scores_page.text) if not scores: raise Exception("No scores found.") return scores # Add the scores and rank on hackerrank to a JSON file. def scoresToJson(self): scores = self.getScores() scores_json = {} if not os.path.exists("HackerRankScores.json"): with open("HackerRankScores.json", 'w') as score_json: score_json.write(" ") with open("HackerRankScores.json", 'r') as scores_file: scores_json = json.load(scores_file) last_element = (list(scores_json.keys())[-1]) if scores_json[last_element]['rank'] == int(scores[0]) or scores_json[last_element]['points'] == int(re.split('/', scores[1])[0]): print("ERROR: JSON not updated, rank or scores value same as previous session.") else: scores_json[str(int(last_element) + 1)] = {'rank': int(scores[0]), 'points': int(re.split('/', scores[1])[0])} with open("HackerRankScores.json", 'w') as scores_file: json.dump(scores_json, scores_file) # Gets the url for the successful challenges. def getSubmissions(self): get_track = requests.get(url='https://www.hackerrank.com/rest/contests/master/submissions/?offset=0&amp;limit=1000', headers=self.HEADERS) data = json.loads(get_track.content) for i in range(len(data['models'])): name = data['models'][i]['challenge']['name'] sub_url = 'https://www.hackerrank.com/rest/contests/master/challenges/' + data['models'][i]['challenge']['slug'] + '/submissions/' + str(data['models'][i]['id']) if data['models'][i]['status'] == "Accepted" and name not in self.SUBMISSIONS: self.SUBMISSIONS[name] = sub_url # Gets the code from successful challenges. all(bool) get either the last or all the successful submissions' code, imp(bool) write the import statements or not, main(bool) write the main function or not. def getCode(self, all=True, imp=False, main=False): # If no submissions url get the submissions. if len(self.SUBMISSIONS) == 0: self.getSubmissions() # Gets the code of the last successful submission/all the last successful submissions. if all: all = len(list(self.SUBMISSIONS.keys())) else: all = 1 for i in range(all): key = list(self.SUBMISSIONS.keys())[i] get_sub = requests.get(url=self.SUBMISSIONS[key], headers=self.HEADERS) code = get_sub.json()['model']['code'] lang = get_sub.json()['model']['language'] name = get_sub.json()['model']['name'] difficulty_Url = re.split('submissions', self.SUBMISSIONS[key])[0] difficulty = requests.get(url=difficulty_Url, headers=self.HEADERS).json()['model']['difficulty_name'] # Create a description of the challenge: Type of challenge - Name of track - Difficulty. description = get_sub.json()['model']['track']['track_name'] + " - " + name + " - " + difficulty code = re.sub(self.LANGUAGE[lang]['comment']+'(.*?)(\n)', '', code) # Remove the import tags. if not imp: code = re.sub(self.LANGUAGE[lang]['import'][0], '', code) code = re.sub(self.LANGUAGE[lang]['import'][1], '', code) # Remove the main function. if not main: code = re.split(self.LANGUAGE[lang]['main'], code)[0] # Checks if the corresponding language file exits in the directory. if not os.path.exists('hackerrank_file.' + self.LANGUAGE[lang]['extension']): with open('hackerrank_file.' + self.LANGUAGE[lang]['extension'], 'w') as f: f.write('') # Checks if the challenge has already been written in the corresponding language file. hackerrank_file = '' with open('hackerrank_file.' + self.LANGUAGE[lang]['extension'], 'r') as f: hackerrank_file = f.read() # write the challenge code to the corresponding language file. if not name in hackerrank_file: code = '\n' + self.LANGUAGE[lang]['comment'] + " " + description + code with open('hackerrank_file.' + self.LANGUAGE[lang]['extension'] , 'a') as f: f.write(code) if __name__ == "__main__": s = Hackerrank_Session() s.getHackerrankCookies() s.getSubmissions() s.getCode(last=True, imp=False, main=False) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:06:45.740", "Id": "426568", "Score": "4", "body": "Welcome to Code Review! Please also include the description of what you want to accomplish also in the question, not just in the title." } ]
[ { "body": "<p>Such pile of code just \"tears out my eyes\" ppl say. </p>\n\n<ul>\n<li>all constant string must be extracted as variables and not pop up in middle of methods </li>\n<li>at <em>cookie_hk +=</em> are you sure you must build string with your own format and dont use someth. directly like it is in source?</li>\n<li>do not repeat the same twice and try to generalize tasks end extract it to separate methods</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T01:41:13.673", "Id": "220778", "ParentId": "220763", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T20:51:02.843", "Id": "220763", "Score": "1", "Tags": [ "python", "beginner", "web-scraping" ], "Title": "Python program that gets my hackerrank code and scores using requests" }
220763
<p>I've written this function to give the neighbours of a vertex in a graph:</p> <pre class="lang-hs prettyprint-override"><code>import Data.Matrix (Matrix, getRow, ncols) import Data.Vector ((!)) type AdjacencyMatrix = Matrix Bool -- Input: the graph's adjacency matrix and a vertex. -- Output: the list of neighbours of that vertex. neighbours :: AdjacencyMatrix -&gt; Int -&gt; [Int] neighbours mat n = filter (\m -&gt; row ! m) [0..(ncols mat)-1] where row = getRow n mat </code></pre> <p>Someone suggested <a href="https://codereview.stackexchange.com/questions/220595/3-function-program-computing-connected-components-of-a-point-cloud-given-a-dista/220660?noredirect=1#comment426386_220660">here</a> to replace my partial calls to <code>getRow</code> and <code>(!)</code> with calls to <code>zip</code> and/or <code>fold</code>. I can't really see how this would be done. Does anyone have suggestions of how to improve this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:09:25.683", "Id": "426618", "Score": "2", "body": "Are you looking for a review or a rewrite? Keep in mind this is Code *Review* and please take a look at our [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T14:02:32.107", "Id": "426686", "Score": "0", "body": "I think I was initially looking for a rewrite, though I would be glad to receive anyone's review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T12:09:40.073", "Id": "426879", "Score": "1", "body": "`neighbours n = findIndices id . getRow n`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T19:54:44.833", "Id": "427016", "Score": "0", "body": "Thanks, @Gurkenglas. I think I need to familiarize myself a bit better with some of the utility functions in these libraries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T16:42:25.950", "Id": "427515", "Score": "1", "body": "I made that suggestion under the assumption that the `matrix` package would offer a function like `rows :: Matrix a -> [[a]]` or `Matrix a -> Vector (Vector a)`. The output of such a function could be easily consumed with list transforms to produce the graph. Sadly `matrix` doesn't offer any functions like these." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:04:05.910", "Id": "220766", "Score": "0", "Tags": [ "haskell", "functional-programming" ], "Title": "Rewrite a Haskell function to be total" }
220766
<p><a href="https://leetcode.com/problems/minimum-cost-to-hire-k-workers/" rel="nofollow noreferrer">https://leetcode.com/problems/minimum-cost-to-hire-k-workers/</a></p> <blockquote> <p>There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].</p> <p>Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:</p> <ol> <li>Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.</li> <li>Every worker in the paid group must be paid at least their minimum wage expectation.</li> </ol> <p>Return the least amount of money needed to form a paid group satisfying the above conditions.</p> <pre><code>Example 1: Input: quality = [10,20,5], wage = [70,50,30], K = 2 Output: 105.00000 Explanation: We pay 70 to 0-th worker and 35 to 2-th worker. Example 2: Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3 Output: 30.66667 Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately. </code></pre> <p>Note:</p> <ol> <li>1 &lt;= K &lt;= N &lt;= 10000, where N = quality.length = wage.length</li> <li>1 &lt;= quality[i] &lt;= 10000</li> <li>1 &lt;= wage[i] &lt;= 10000</li> <li>Answers within <span class="math-container">\$10^{-5}\$</span> of the correct answer will be considered correct.</li> </ol> </blockquote> <p>This is one of the hardest problems I met on leetcode</p> <p>Please review the code as if this was 45 minute interview. Performance is the main issue here. this solution is same as the leetcode solution, I have one question also is why not use use maxHeap and do the &quot;trick&quot; of multiplying the quality with -1, before pushing into the heap?</p> <pre><code>using System; using Heap; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/minimum-cost-to-hire-k-workers/ /// &lt;/summary&gt; [TestClass] public class MinimumCostToHirekWorkers { [TestMethod] public void MinCost2() { int[] quality = { 10, 20, 5 }; int[] wage = { 70, 50, 30 }; int k = 2; Assert.AreEqual(105.0, MincostToHireWorkersHeap(quality, wage, k)); } [TestMethod] public void MinCost3() { int[] quality = { 3, 1, 10, 10, 1 }; int[] wage = { 4, 8, 2, 2, 7 }; int k = 3; Assert.AreEqual(30.66667, MincostToHireWorkersHeap(quality, wage, k), 0.001); } public double MincostToHireWorkersHeap(int[] quality, int[] wage, int K) { Worker[] workers = new Worker[quality.Length]; for (int i = 0; i &lt; quality.Length; i++) { workers[i] = new Worker(quality[i], wage[i]); } //we sort the workers by their ratio, low ratio X low quality == low cost Array.Sort(workers); double ans = double.MaxValue; int sumq = 0; BinaryHeap heap = new BinaryHeap((uint)quality.Length); foreach (var worker in workers) { //we push into the min heap the negative value of quality // this is a max heap after that heap.InsertKey(-1 * worker.Quality); sumq += worker.Quality; //if we have more than k we will remove the biggest negative value // which is the height quality if (heap.Count &gt; K) { sumq += heap.ExtractMin(); } // we compute the sum with this worker ratio if (heap.Count == K) { ans = Math.Min(ans, sumq * worker.Ratio); } } return ans; } } public class Worker : IComparable&lt;Worker&gt; { public int Quality; public int Wage; public Worker(int q, int w) { Quality = q; Wage = w; } public double Ratio { get { return (double)Wage / Quality; } } public int CompareTo(Worker other) { if (Ratio &gt; other.Ratio) { return 1; } if (Ratio &lt; other.Ratio) { return -1; } return 0; } } } </code></pre> <p>This is the code for the MinHeap no need to review it, I assume that you don't need to implement this is a 45 minutes interview</p> <pre><code> public class BinaryHeap { private readonly int[] _harr;// pointer to array of elements in heap private readonly uint _capacity; // maximum possible size of min heap public uint _heapSize; // Current number of elements in min heap public BinaryHeap(uint capacity) { _capacity = capacity; _heapSize = 0; _harr = new int[capacity]; } public void InsertKey(int key) { if (_heapSize == _capacity) { throw new StackOverflowException(&quot;overflow can't insert key&quot;); } //insert the new key at the end _heapSize++; uint i = _heapSize - 1; _harr[i] = key; //fix the heap as min heap // Fix the min heap property if it is violated while (i != 0 &amp;&amp; _harr[Parent(i)] &gt; _harr[i]) //bubble is generic specific { Swap(i, Parent(i)); i = Parent(i); } } /// &lt;summary&gt; /// This function deletes key at index i. It first reduced value to minus /// infinite, then calls extractMin() /// &lt;/summary&gt; public void DeleteKey(uint i) { DecreaseKey(i, Int32.MinValue); ExtractMin(); } public void DecreaseKey(uint i, int newValue) { _harr[i] = newValue; while (i != 0 &amp;&amp; _harr[Parent(i)] &gt; _harr[i]) //bubble is generic specific { Swap(i, Parent(i)); i = Parent(i); } } /// &lt;summary&gt; /// you switch the root with the last index in the array, the end of the heap /// and you heapify the root node. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public int ExtractMin() { if (_heapSize &lt;= 0) { return Int32.MaxValue; } if (_heapSize == 1) { _heapSize--; return _harr[0]; } // Store the minimum value, and remove it from heap int root = _harr[0]; _harr[0] = _harr[_heapSize - 1]; _heapSize--; Heapify(0); return root; } /// &lt;summary&gt; /// the first call is done with index 0, /// since this is recursive function you compare to right subtree and left subtree /// you choose the lower node and swap the root with it, than you call /// the same function from the last index you swapped with /// &lt;/summary&gt; /// &lt;param name=&quot;i&quot;&gt;&lt;/param&gt; private void Heapify(uint i) { uint l = Left(i); uint r = Right(i); uint smallest = i; if (l &lt; _heapSize &amp;&amp; _harr[l] &lt; _harr[i]) { smallest = l; } if (r &lt; _heapSize &amp;&amp; _harr[r] &lt; _harr[smallest]) { smallest = r; } if (smallest != i) { Swap(i, smallest); Heapify(smallest); } } private uint Right(uint i) { return 2 * i + 2; } private uint Left(uint i) { return 2 * i + 1; } private uint Parent(uint i) { return (i - 1) / 2; } private void Swap(uint key1, uint key2) { int temp = _harr[key2]; _harr[key2] = _harr[key1]; _harr[key1] = temp; } public int GetMin() { return _harr[0]; } public uint Count { get { return _heapSize; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T00:30:03.513", "Id": "426590", "Score": "0", "body": "\"this solution is same as the leetcode solution, I have one question\" - so is this _your_ code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T03:31:32.707", "Id": "426598", "Score": "0", "body": "Yes this is my code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T15:00:50.053", "Id": "426701", "Score": "1", "body": "`Worker.CompareTo` does not check if `other` is null. Also, you could simply defer to double's CompareTo as in `return Ratio.CompareTo(other.Ratio)`." } ]
[ { "body": "<blockquote>\n <p>Please review the code as if this was 45 minute interview.</p>\n</blockquote>\n\n<p>I don't know what you expect from answerers with this statement.\nThe evaluation of some code produced within 45 minutes is subjective,\nhighly dependent on the company and position,\nand dozens of other factors.\nWhether a reviewer says \"good job in 45 minutes\" or \"poor job in 45 minutes\",\nI think it's going to be meaningless.</p>\n\n<p>I suggest to focus on writing the best possible code, and post just that.\nBy doing this exercise a lot,\nyour performance within 45 minutes will also naturally improve.\nAnd performance within 45 minutes is never the end goal anyway for any job.</p>\n\n<blockquote>\n <p>I have one question also is why not use use maxHeap and do the \"trick\" of multiplying the quality with -1, before pushing into the heap?</p>\n</blockquote>\n\n<p>I don't understand this question.\nBut maybe I can still help.\nConsider a heap as a collection + a comparator function.\nThen there is no more \"max heap\" and \"min heap\",\nsimply a heap, where the top element is determined by the function.</p>\n\n<p>The \"trick\" of multiplying elements by -1 seems fragile to me.\nI think the implied context here is that the elements are numbers,\nand the comparator function is the natural ordering of numbers.\nAs such, the behavior is a \"min heap\": the element is the smallest one.\nIf you insert values multiplied by -1, and then when you remove the top element and multiply it by -1, it has the effect as if the behavior is changed to a \"max heap\".</p>\n\n<p>I find this fragile because you have to remember to multiply values when adding and removing. Such behavior is best encapsulated somewhere.\nAnd that's what the comparator function can do for you.\nUsing an appropriate comparator function will allow you to use the heap naturally, adding and removing values without extra manipulation.</p>\n\n<h3>Improving <code>Worker</code></h3>\n\n<p><code>Wage</code> is only used to compute <code>Ratio</code>.\nThe ratio is recomputed every time <code>Ratio</code> is called.\nIt would be better to compute the ratio ones,\nstore it,\nand drop the <code>Wage</code> field.</p>\n\n<h3>Where to put the comparator logic?</h3>\n\n<p>In the posted code the comparator logic is in the <code>Worker</code>.\nAnd that's fine, the program works.\nBut is this ordering an inherent property of the <code>Worker</code>?\nNot really.\nOn the other hand, it's a crucial piece to understanding how the solution works.\nSo instead of the comment at <code>Arrays.Sort</code>,\nI would define the sorting function there.\nIt would make the solution easier to read and understand,\nthe comment would become unnecessary,\nand if later you need another kind of sorting of workers,\nyou will be free to define a different appropriate comparator.</p>\n\n<h3>Getting rid of <code>if (heap.Count == K)</code></h3>\n\n<p>I think it's a code smell when a condition in a loop will be false for the first couple of values, and then always true.\nIt would be better to reorganize the code to avoid unnecessary evaluations.</p>\n\n<p>Consider this alternative:</p>\n\n<ul>\n<li>add to heap the first <code>K</code> values</li>\n<li>compute <code>sumq</code> as the sum of the first <code>K</code> values</li>\n<li>initialize <code>minCost</code> as <code>sumq</code> multiplied by the ratio of the <code>K</code>-th worker</li>\n<li>loop from <code>K</code> until the last worker\n\n<ul>\n<li>add to heap the quality <code>q</code> of the current worker</li>\n<li><code>sumq += q - heap.poll()</code> (this assumes that the ordering of heap is defined as the reverse of natural ordering (largest number on top), and that quality values are added as they are, without multiplying by -1)</li>\n<li><code>minCost = Math.Min(minCost, sumq * worker.Ratio)</code></li>\n</ul></li>\n</ul>\n\n<p>Notice that in this alternative organization there is no more need for the useless assignment <code>double ans = double.MaxValue;</code> (and I renamed <code>ans</code> to <code>minCost</code>).</p>\n\n<h3>A word on <code>BinaryHeap</code></h3>\n\n<blockquote>\n <p>This is the code for the MinHeap no need to review it</p>\n</blockquote>\n\n<p>If no need to review it, then it would have been better to post just the definition of the interface.\nAnd I think it would have guided you in a good direction.\nFor example, even in this text, you refer to it as \"MinHeap\",\nbut the class is actually called \"BinaryHeap\",\nwhich is an implementation detail, irrelevant in the implementation of the solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T20:52:07.457", "Id": "427356", "Score": "0", "body": "thanks for your great reviews, I will give it another try!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T10:45:50.750", "Id": "221051", "ParentId": "220767", "Score": "4" } } ]
{ "AcceptedAnswerId": "221051", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:14:45.153", "Id": "220767", "Score": "3", "Tags": [ "c#", "programming-challenge", "heap", "priority-queue" ], "Title": "LeetCode: Minimum cost to hire k workers" }
220767
<p>I have quickly written some code for a task in which takes a name of an 'earthling', their age and then applies a random operator with a random value in between 0 and 100. If their new age is below 0 or above 120, they die. The operator, name, previous and new age must be printed to the screen.</p> <p>Code:</p> <pre><code>import operator import random ops_table = { "+": operator.add, "-": operator.sub, "*": operator.mul } def get_earthlings(): earthlings = [[], []] print("Disclaimer: Input XXX as a name to end the naming loop.") while True: name = input("Please enter a name: ") if name == "XXX": break while True: try: age = int(input("What is the age of " + name + "? ")) if age &lt;= 120 and age &gt;= 0: break else: print("Please enter an age between 0 and 120.") except ValueError: print("Please input a valid integer. Try again.") earthlings[0].append(name) earthlings[1].append(age) return earthlings def random_op(): return ops_table[random.choice(list(ops_table))] def is_dead(age): if age &gt; 120: return True return False def get_op_name(operator): for name, func in ops_table.items(): if func == operator: return name def main(): earthlings = get_earthlings() for index, earthling in enumerate(earthlings[0]): operator = random_op() random_value = random.randint(0, 100) new_age = operator(earthlings[1][index], random_value) if is_dead(new_age): print(earthling, "at previous age", earthlings[1][index], "(new age", str(new_age) + ") had operator '" + get_op_name(operator) + "' applied with paramater", random_value, "and died.") else: print(earthling, "at previous age", earthlings[1][index], "(new age", str(new_age) + ") had operator '" + get_op_name(operator) + "' applied with paramater", random_value, "and lived.") if __name__ == "__main__": main() </code></pre> <p>Is this code efficient? How can I improve it (other than adding comments)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:38:17.083", "Id": "426573", "Score": "0", "body": "Note, I and potentially others are writing reviews, and it is not allowed to alter code once it's been posted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:44:47.770", "Id": "426575", "Score": "0", "body": "Sorry. New to this 'forum', just quickly realized those two parts were completely useless." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T04:43:23.197", "Id": "426603", "Score": "0", "body": "@Carcigenicate thats not correct. As long as there has been no answers the OP can edit his/her code. What an asker shouldn't do is to edit his/her code every few minutes (then it would be better to delete the question and after the editing is finished to undelete it)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T13:22:54.620", "Id": "426678", "Score": "0", "body": "@Heslacher I could have sworn I read a Meta post suggesting the restrictions were much stricter than that. I'm us able to find it though." } ]
[ { "body": "<p>First, you code is actually bugged. <code>isDead</code> isn't checking if the age is less than zero. It's also more complicated than it needs to be. You can just return the result of the condition directly. It would be better written as:</p>\n\n<pre><code>def is_dead(age):\n return age &lt; 0 or age &gt; 120\n # Or return not (0 &lt;= age &lt;= 120)\n</code></pre>\n\n<p>and along the same lines, the age check in <code>get_earthlings</code> could be reduced to <code>if 0 &lt;= age &lt;= 120:</code>.</p>\n\n<hr>\n\n<p>Storing the names and ages as two separate lists, nested inside another list is needlessly confusing. This is an example of maintaining <a href=\"https://stackoverflow.com/questions/5559159/what-is-meant-by-parallel-lists-in-python?lq=1\">\"parallel\" lists</a> to maintain data, and most of the time, it should be avoided. What if you remove data from one list and forget to remove it from the other? Now you have weird bugs.</p>\n\n<p>This is the perfect case for a class with <code>age</code> and <code>name</code> fields:</p>\n\n<pre><code>class Earthling:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n # A simple Higher Order helper method\n # Not really necessary, but a good example\n def change_age(self, f, other_num): # f is an operator\n self.age = f(self.age, other_num)\n\n # I flipped the check because it works out a little nicer\n def is_alive(self):\n return 0 &lt;= self.age &lt;= 120\n</code></pre>\n\n<p>Then, use it like:</p>\n\n<pre><code>e = Earthling(\"Name\", 10)\ne.change_age(operator.sub, 20)\nprint(e.age) # Prints -10\nprint(e.is_alive()) # False\n</code></pre>\n\n<p>Or, just have a single list of tuples where the first element in the tuple is the name, and the second is the age. Just keep the data grouped together when they're a part of the same conceptual object.</p>\n\n<hr>\n\n<pre><code>if is_dead(new_age):\n print(earthling, \"at previous age\", earthlings[1][index], \"(new age\", str(new_age) + \") had operator '\" + get_op_name(operator) + \"' applied with paramater\", random_value, \"and died.\")\nelse:\n print(earthling, \"at previous age\", earthlings[1][index], \"(new age\", str(new_age) + \") had operator '\" + get_op_name(operator) + \"' applied with paramater\", random_value, \"and lived.\")\n</code></pre>\n\n<p>These lines contain <em>lots</em> of duplication. Whenever you see code that's identical like this in multiple places, stop and think if you can make the code simpler. If you ever need to update the code in the future, you have multiple places to change, and that's not ideal.</p>\n\n<p>In this case, it's actually very easy to fix this up:</p>\n\n<pre><code># Pick the status here\nstatus_str = \"lived\" if e.is_alive() else \"died\"\n\n# Then plug it in here\nprint(e.name, \"at previous age\", previous_age, \"(new age\", str(new_age) + \") had operator '\"\n + get_op_name(operator) + \"' applied with paramater\", random_value, \"and\", status_str)\n</code></pre>\n\n<p>I'm picking what the status to print is ahead of time since that's the only part that changes in the two cases, then I just plug that in at the end.</p>\n\n<p>Unfortunately, with the change to classes, this messes up maintaining the previous age. You could do something like <code>old_age = e.age</code> before changing it, or even save the old age in <code>e</code>; although the latter seems a little smelly.</p>\n\n<hr>\n\n<p><code>get_op_name</code> is pretty inefficient, but it doesn't really need to be efficient. That function will likely never be a performance concern, but if it ever was, you could using some form of \"two-way\" dictionary idea. Either maintain two dictionaries, or store both \"directions\" of translations in a single dictionary. Both ways suffer from the downside of having data duplicated, but since the data likely won't change during the operation of the program, that shouldn't be a big deal.</p>\n\n<hr>\n\n<p>For picking the random operation, I find this to be a little neater:</p>\n\n<pre><code>random.choice(list(ops_table.values()))\n</code></pre>\n\n<p>Unfortunately, <code>values</code> doesn't return a sequence, so it needs to be converted into a list (or another sequence type) before being given to <code>choice</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T13:14:47.580", "Id": "426674", "Score": "0", "body": "@MathiasEttinger Fixed. That was clumsy wording. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T22:03:20.300", "Id": "220771", "ParentId": "220768", "Score": "3" } }, { "body": "<p>There are just two minor points that I would like to add on top of <a href=\"https://codereview.stackexchange.com/users/46840/carcigenicate\">@Carcigenicate</a>'s <a href=\"https://codereview.stackexchange.com/a/220771/92478\">answer</a>.</p>\n\n<hr>\n\n<p>In the answer, a class was introduced as possible way to structure the code. While not limited to classes, practice has proven that at least a short bit of documentation can often work wonders. As you may know, Python has an official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a>, which also has some recommendations on function/method documentation. It <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">recommendeds</a> to have at least a short oneliner in <code>\"\"\"triple quotes\"\"\"</code> immediately after the function definition.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Earthling:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def change_age(self, f, age_update):\n \"\"\"combine the earthlings age with the update using the given operator f\"\"\"\n self.age = f(self.age, age_update)\n\n def is_alive(self):\n \"\"\"Check if the earthling is still alive, i.e. between 0 and 120 years old\"\"\"\n return 0 &lt;= self.age &lt;= 120\n</code></pre>\n\n<p>Though it might seem overkill in this simple example, I find it a reasonable exercise to try to convey the gist of the method in question in a few words. This may also help to make sure that your functions are not to complex. Of course you are not limited to a single line and can also write longer documentation strings. To quote from the style guide:</p>\n\n<blockquote>\n<pre><code>\"\"\"Return a foobang\n\nOptional plotz says to frobnicate the bizbaz first.\n\"\"\"\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Another pet peeve of mine is string formatting. You were advised to use</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(e.name, \"at previous age\", previous_age, \"(new age\", str(new_age) + \") had operator '\"\n + get_op_name(operator) + \"' applied with paramater\", random_value, \"and\", status_str)\n</code></pre>\n\n<p>which closely follows your original use of <code>print</code>. I personally don't like the implicit whitespace put between the arguments of <code>print</code> when used this way. I prefer to use explicit string formatting. Since you have not indicated the Python version in use, I will present you two variants. The first way may only be used in Python 3.6 (see <a href=\"https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498\" rel=\"nofollow noreferrer\">What's new in Python 3.6</a>?) and higher, and looks as follows:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"{e.name} at previous age {previous_age} (new age {new_age}) had operator\"\n f\"'{get_op_name(operator)}' applied with paramater {random_value} and {status_str}\")\n</code></pre>\n\n<p>These are called f-strings for short.</p>\n\n<p>The second and older way which works in Python 2.7 and all of the versions of Python 3 I'm aware of uses <code>.format(...)</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\n \"{} at previous age {} (new age {}) had operator '{}' applied with paramater {} and {}\".format(\n e.name, previous_age, new_age, get_op_name(operator), random_value, status_str)\n)\n</code></pre>\n\n<p>By the look and feel I prefer f-strings, though you sometimes just cannot have them if you have to be backwards compatible with Python 2.7.</p>\n\n<p>You can read more about the topic at <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">this blog post</a>, which has a nice comparison of the different ways strings can be formatted in Python.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T17:19:58.143", "Id": "220855", "ParentId": "220768", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:21:43.220", "Id": "220768", "Score": "3", "Tags": [ "python" ], "Title": "\"Alien\" challenge" }
220768
<p>Please review the code readability, I would like to have an easier to follow code. Thanks</p> <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/ /// &lt;/summary&gt; [TestClass] public class RotateMatrix90 { [TestMethod] public void Rotate3x3Test() { int[,] mat = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[,] expected = { {3, 6, 9}, {2, 5, 8}, {1, 4, 7} }; rotateMatrix(mat); for (int r = 0; r &lt; mat.GetLength(0); r++) { for (int c = 0; c &lt; mat.GetLength(1); c++) { Assert.AreEqual(expected[r, c], mat[r, c]); } } } void rotateMatrix(int[,] mat) { int size = mat.GetLength(0); for (int x = 0; x &lt; size / 2; x++) { for (int y = x; y &lt; size - x - 1; y++) { int temp = mat[x, y]; // save 1 mat[x, y] = mat[y, size - x - 1]; // move 3 into 1 mat[y, size - x - 1] = mat[size - x - 1, size - y - 1]; // move 9 into 3 mat[size - x - 1, size - y - 1] = mat[size - y - 1, x]; // move 7 into 9 mat[size - y - 1, x] = temp; } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T22:21:52.377", "Id": "426579", "Score": "1", "body": "Obligatory xkcd: https://xkcd.com/184/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T09:41:55.197", "Id": "426644", "Score": "1", "body": "@Acccumulation omg that's the best!! funny man!" } ]
[ { "body": "<p>A simple improvement for readability could be to eliminate the <code>- 1</code> in the indices by replacing <code>size</code> with <code>max = mat.GetLength(0) - 1;</code>:</p>\n\n<pre><code>void rotateMatrix(int[,] mat)\n{\n int max = mat.GetLength(0) - 1;\n for (int x = 0; x &lt; (max + 1) / 2; x++)\n {\n for (int y = x; y &lt; max - x; y++)\n {\n int temp = mat[x, y]; // save 1\n mat[x, y] = mat[y, max - x]; // move 3 into 1\n mat[y, max - x] = mat[max - x, max - y]; // move 9 into 3\n mat[max - x, max - y] = mat[max - y, x]; // move 7 into 9\n mat[max - y, x] = temp;\n }\n }\n}\n</code></pre>\n\n<p>You could also make a pair of vars for <code>max - x</code> and <code>max - y</code> as :</p>\n\n<pre><code>void rotateMatrixReview(int[,] mat)\n{\n int max = mat.GetLength(0) - 1;\n for (int x = 0; x &lt; (max + 1) / 2; x++)\n {\n for (int y = x; y &lt; max - x; y++)\n {\n int xmax = max - x;\n int ymax = max - y;\n int temp = mat[x, y]; // save 1\n mat[x, y] = mat[y, xmax]; // move 3 into 1\n mat[y, max - x] = mat[xmax, ymax]; // move 9 into 3\n mat[xmax, ymax] = mat[ymax, x]; // move 7 into 9\n mat[max - y, x] = temp;\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Just for the fun: another approach could be:</p>\n\n<pre><code>void Swap(int[,] mx, int r1, int c1, int r2, int c2)\n{\n int tmp = mx[r1, c1];\n mx[r1, c1] = mx[r2, c2];\n mx[r2, c2] = tmp;\n}\n\nvoid rotateMatrix(int[,] mat)\n{\n int m = mat.GetLength(0) - 1;\n\n // l = level in the matrix from outer = 0 to inner \n for (int l = 0; l &lt; (m + 1) / 2; l++)\n {\n // o = offset along rows and cols\n for (int o = 0; o &lt; m - 2 * l; o++)\n {\n Swap(mat, l, l + o, l + o, m - l);\n Swap(mat, m - l - o, l, m - l, m - l - o);\n Swap(mat, l + o, m - l, m - l - o, l);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T07:28:54.230", "Id": "220796", "ParentId": "220769", "Score": "1" } } ]
{ "AcceptedAnswerId": "220796", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T21:39:12.933", "Id": "220769", "Score": "2", "Tags": [ "c#", "programming-challenge", "matrix" ], "Title": "GeeksforGeeks: Rotate matrix by 90 degrees" }
220769
<p><strong>The task</strong></p> <p>is taken from <a href="https://leetcode.com/problems/reverse-vowels-of-a-string/" rel="nofollow noreferrer">leetcode</a></p> <blockquote> <p>Write a function that takes a string as input and reverse only the vowels of a string.</p> <p><strong>Example 1:</strong></p> <p>Input: "hello"</p> <p>Output: "holle"</p> <p><strong>Example 2:</strong></p> <p>Input: "leetcode"</p> <p>Output: "leotcede"</p> <p>Note: The vowels does not include the letter "y".</p> </blockquote> <p><strong>My first solution</strong></p> <pre><code>/** * @param {string} s * @return {string} */ var reverseVowels = function(s) { const LEN = s.length; const str = [...s]; const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']; const rev = []; for (let i = 0; i &lt; LEN; i++) { if (vowels.includes(s[i])) { rev.push(s[i]); } } for (let i = 0; i &lt; LEN; i++) { if (vowels.includes(str[i])) { str[i] = rev.pop(); } } return str.join(''); }; </code></pre> <p><strong>My second solution</strong></p> <pre><code>/** * @param {string} s * @return {string} */ var reverseVowels = function(s) { if (s.length &lt;= 1) { return s; } const sForward = [...s]; const sBackward = [...s].reverse(); const LEN = s.length - 1; let left = -1, right = -1; const VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']; const findVowel = start =&gt; (x, i) =&gt; start &lt; i &amp;&amp; VOWELS.includes(x); while(true) { left = sForward.findIndex(findVowel(left)); right = sBackward.findIndex(findVowel(right)); if (left &gt;= LEN - right || left === -1 || right === -1) { return sForward.join(''); } [sForward[left], sForward[LEN - right]] = [sBackward[right], sForward[left]]; } return sForward.join(''); }; </code></pre> <p><strong>My third solution</strong></p> <pre><code>/** * @param {string} s * @return {string} */ var reverseVowels = function(s) { if (s.length &lt;= 1) { return s; } const str = [...s]; let left = 0; let right = s.length - 1; const VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']; while(left &lt; right) { if (VOWELS.includes(str[left]) &amp;&amp; VOWELS.includes(str[right])) { [str[right], str[left]] = [str[left], str[right]]; left++; right--; } else if (VOWELS.includes(str[left])) { right--; } else { left++; } } return str.join(''); }; </code></pre> <p><strong>My fourth solution</strong></p> <pre><code>/** * @param {string} s * @return {string} */ var reverseVowels = function(s) { if (s.length &lt;= 1) { return s; } const str = [...s]; let left = 0; let right = s.length - 1; const map = new Map(); map.set('a', true); map.set('e', true); map.set('i', true); map.set('o', true); map.set('u', true); map.set('A', true); map.set('E', true); map.set('I', true); map.set('O', true); map.set('U', true); while(left &lt; right) { if (map.get(str[left]) &amp;&amp; map.get(str[right])) { [str[right], str[left]] = [str[left], str[right]]; left++; right--; } else if (map.get(str[left])) { right--; } else { left++; } } return str.join(''); }; </code></pre> <p><strong>My fifth solution</strong></p> <pre><code>/** * @param {string} s * @return {string} */ var reverseVowels = function(s) { if (s.length &lt;= 1) { return s; } const str = [...s]; let left = 0; let right = s.length - 1; const set = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']); while(left &lt; right) { if (set.has(str[left]) &amp;&amp; set.has(str[right])) { [str[right], str[left]] = [str[left], str[right]]; left++; right--; } else if (set.has(str[left])) { right--; } else { left++; } } return str.join(''); }; </code></pre>
[]
[ { "body": "<p>I recommend using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype\" rel=\"nofollow noreferrer\">Array.prototype</a> methods. </p>\n\n<p>These lend themselves to adopting a <a href=\"https://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow noreferrer\">functional style of programming</a>.</p>\n\n<p>Functional programming is a lot easier to test, as a pure function always returns the same result and never mutate objects. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const vowels = ['a','e','i','o','u']; \nfunction vowelStringReverse(str) {\n \n //split the string into an array of chars, that includes their index position\n const strArray = str.split('').map((v,i) =&gt; ({\n value: v, \n i: i, \n isVowel: vowels.includes(v)\n })); \n \n //For just the vowels, \n //Create index position lookup, where the index positions are reversed\n const vowelsReverseIndexLookup = strArray.filter(v =&gt; v.isVowel)\n .reduce((acc, cur, i, array) =&gt; {\n return {\n ...acc, \n [array[array.length-1-i].i]: cur.value\n }; \n \n }, {}); \n \n //Now iterate through the string, and look up the vowel from the lookup. \n const strReversed = strArray.map((v,i) =&gt; {\n if (v.isVowel) {\n return vowelsReverseIndexLookup[i]\n }\n else {\n return v.value; \n }\n }); \n \n return strReversed.join(''); \n \n}\n\n\nconsole.log(vowelStringReverse('hello')); \nconsole.log(vowelStringReverse('leetcode')); </code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>In this example I've given, if you wanted, you could then pull out the anonymous functions I've declared, and write tests for them: </p>\n\n<p>for example: </p>\n\n<pre><code>const vowelsReverseIndexLookup = strArray.filter(v =&gt; v.isVowel)\n.reduce(reverseIndexReducer, {}); \n\n//elsewhere: \n\nconst reverseIndexReducer = (acc, cur, i, array) =&gt; {\n return {\n ...acc, \n [array[array.length-1-i].i]: cur.value\n }; \n\n}; \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T08:59:24.690", "Id": "220808", "ParentId": "220773", "Score": "1" } } ]
{ "AcceptedAnswerId": "220808", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T22:50:04.883", "Id": "220773", "Score": "1", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6" ], "Title": "Reverse Vowels of a String" }
220773
<p>I am new to programming and I am trying to develop a machine learning approach for image segmentation (<a href="https://en.wikipedia.org/wiki/Image_segmentation" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Image_segmentation</a>) and here I want to evaluate the predicted (output) segmentation. In order to do this, I am using multiple (common) metrics (dice score, jacquard index, surface distance Hausdorff distance, diameter error and volume error). </p> <p>The code works, but it really looks bad! I heard that one of the best practices is to avoid repetition in the code. For my piece I have to create multiple arrays which will all have different usage, but generating a lot of repetitions, and I am sure there might be better way to get better performance for this piece of code. </p> <p>Do you have an idea of how to optimize this for speed and readability?</p> <p>The details of the code:</p> <p><code>folder = glab()</code> : gets the name of the different folders containing the arrays that I want to open (<code>glab() = glob()</code> with natural sorting)</p> <p><code>prediction</code>/<code>ground_truth</code> : loads the predicted segmentation and ground_truth to be compared</p> <p><code>scores()</code> : calculates the different metrics (dice score, jacquard index, sensibility and specificity) between the ground truth and prediction</p> <p><code>surfd()</code> : calculates the surface distance between ground truth and prediction</p> <p><code>diam_vol</code> : calculates the diameter/volume and error between ground truth and prediction</p> <p>Since I am evaluating multiple cases I want to know the <code>mean()</code> metrics to assess my model that's why I call for <code>np.mean()</code> for all the values at the end.</p> <pre><code>def metrics(savedir): """3D metrics for segmentation evaluation: dice score : https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient jacquard index : https://en.wikipedia.org/wiki/Jaccard_index sensibility &amp; specificity : https://en.wikipedia.org/wiki/Sensitivity_and_specificity diameter and volume error Surface distance : https://www.cs.ox.ac.uk/files/7732/CS-RR-15-08.pdf Hausdorff distance : https://en.wikipedia.org/wiki/Hausdorff_distance """ folder = glab(savedir+"/OutputData/*/") # array initialization np_dice = np.zeros([len(folder)]) np_jacq = np.zeros([len(folder)]) np_sens = np.zeros([len(folder)]) np_spec = np.zeros([len(folder)]) np_surf = np.zeros([len(folder)]) np_haus = np.zeros([len(folder)]) np_diam_GT = np.zeros([len(folder)]) np_diam_pred = np.zeros([len(folder)]) np_diam_err = np.zeros([len(folder)]) np_vol_GT = np.zeros([len(folder)]) np_vol_pred = np.zeros([len(folder)]) np_vol_err = np.zeros([len(folder)]) for number, folder_name in enumerate(folder): prediction = np.load(folder_name+"prediction.npy") ground_truth = np.load(folder_name+"test_label.npy") scores = scoring(ground_truth, prediction) surface_distance = surfd(prediction, ground_truth, [0.625, 0.625, 0.625], 1) diam_vol = diam(prediction, ground_truth) np_dice[number] = scores[0] np_jacq[number] = scores[1] np_sens[number] = scores[2] np_spec[number] = scores[3] np_surf[number] = surface_distance.mean() np_haus[number] = surface_distance.max() np_diam_GT[number] = diam_vol[0] np_diam_pred[number] = diam_vol[1] np_diam_err[number] = diam_vol[2] np_vol_GT[number] = diam_vol[3] np_vol_pred[number] = diam_vol[4] np_vol_err[number] = diam_vol[5] mean_dice = np.mean(np_dice) mean_jacq = np.mean(np_jacq) mean_sens = np.mean(np_sens) mean_spec = np.mean(np_spec) mean_surf = np.mean(np_surf) mean_haus = np.mean(np_haus) mean_diam_GT = np.mean(np_diam_GT) mean_diam_pred = np.mean(np_diam_pred) mean_diam_err = np.mean(np_diam_err) mean_vol_GT = np.mean(np_vol_GT) mean_vol_pred = np.mean(np_vol_pred) mean_vol_err = np.mean(np_vol_err) return ([mean_dice, mean_jacq, mean_sens, mean_spec, mean_surf, mean_haus, mean_diam_GT, mean_diam_pred, mean_diam_err, mean_vol_GT, mean_vol_pred, mean_vol_err]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T03:11:08.787", "Id": "426596", "Score": "0", "body": "Welcome to Code Review. Please read [ask]. Tell us what this code accomplishes. By `glab()`, do you mean `glob()`? Is this real working code? What do `scoring_baby()`, `surfd()` and `diam()` do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T04:20:48.913", "Id": "426599", "Score": "1", "body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T04:24:49.663", "Id": "426600", "Score": "2", "body": "Hi, and thank you very much for your time. glab() is glob() with natural sorting (so I can find myself more easily in my data folder); scoring_baby() calculates the dice score, jacquard index, sensibility and specificity between a ground truth label (binary mask) and a predicted label (binary mask as well), surfd() calculates the surface distance between the two lables, and diam() calculates the different diameter and volume of the 3D segmentation. All the code is working, I just wanted to improve and understand more how to write proper code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T08:28:26.200", "Id": "426836", "Score": "0", "body": "It would be nice if you provide a description or link to explain *segmentation*, for those who know Python but don't have the same domain knowledge of the problem space." } ]
[ { "body": "<p>Realy, dud its childish!</p>\n\n<p>only ones:</p>\n\n<pre><code>lenf = len(folder)\n</code></pre>\n\n<p>just one 2d array:</p>\n\n<pre><code>len_types = 12\narr = np.zeros([lenf , 12])\n</code></pre>\n\n<p>learn how to work with numpy arrays, you will avoid the loop as well. And for example the mean can be done in one line for 2d array:</p>\n\n<pre><code>means = np.mean(arr, axis = 1)\n</code></pre>\n\n<p><a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html\" rel=\"nofollow noreferrer\">https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T02:59:45.990", "Id": "426595", "Score": "0", "body": "Thank you very much, sorry I am new to this and clearly need improvement on the manipulation of matrices with numpy. Using you advice I was able to correct my code [see EDIT first post]. But I feel more can be done, do you have other suggestions ? (sorry for the noobism here)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T14:52:43.660", "Id": "426698", "Score": "0", "body": "wait a bit, i can create good numpy tutorial from this example and ll post here later" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T01:48:44.417", "Id": "220779", "ParentId": "220774", "Score": "2" } }, { "body": "<h1>return lists</h1>\n\n<p>your functions seem to return lists or tuples. For 2 or 3 values, this is ok, but <code>diam</code> returns 6 values, <code>metrics</code> 12. This is very unclear, and unstable when you want to add, reorder or remove a metric. Better would be then to either return a <code>dict</code> or a <code>namedtuple</code></p>\n\n<h1>spacing</h1>\n\n<p>pep-8 recommends <code></code> around operators (<code>+</code>,...) I use a code formatter (<a href=\"https://github.com/python/black\" rel=\"nofollow noreferrer\">black</a>) to format my code, so I don't have to worry about this sort of details any more</p>\n\n<h1>variable naming</h1>\n\n<p>longer variable names don't make your program slower. And if you use a capable IDE, it doesn't slow the coding either. abbreviated variable names on the other hand make code more unclear. There is no need to shorten <code>jacquard</code> to <code>jack</code></p>\n\n<h1>magical values</h1>\n\n<p><code>[0.625, 0.625, 0.625], 1</code> as arguments to <code>surface_distance</code> are magical values, and very unclear what they mean. Easier would be to replace them with a variable with a clear name, or use keyword arguments.</p>\n\n<h1>containers</h1>\n\n<p>If you have a lot of metrics, it is generally cleaner to keep them in 1 data structure (<code>dict</code> for example) instead of 12 different variables, and 12 other variables for the means.</p>\n\n<h1>pandas</h1>\n\n<p>Instead of using <code>numpy</code> directly, why not use a <a href=\"http://pandas.pydata.org/pandas-docs/stable/getting_started/index.html\" rel=\"nofollow noreferrer\"><code>pandas</code></a> DataFrame as data structure? This will allow you to work with labeled data.</p>\n\n<pre><code>import pandas as pd\n\n\ndef metrics(savedir):\n\n \"\"\"3D metrics for segmentation evaluation:\n\n dice score : https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient\n jacquard index : https://en.wikipedia.org/wiki/Jaccard_index\n sensibility &amp; specificity : https://en.wikipedia.org/wiki/Sensitivity_and_specificity\n diameter and volume error\n Surface distance : https://www.cs.ox.ac.uk/files/7732/CS-RR-15-08.pdf\n Hausdorff distance : https://en.wikipedia.org/wiki/Hausdorff_distance\n \"\"\"\n\n folder = glab(savedir + \"/OutputData/*/\")\n results = pd.DataFrame(\n index=folder,\n columns=[\n \"dice\",\n \"jacquard\",\n \"sensibility\",\n \"specificity\",\n \"surface\",\n \"hausdorff\",\n \"diam_GT\",\n \"diam_pred\",\n \"diam_err\",\n \"vol_GT\",\n \"vol_pred\",\n \"vol_err\",\n ],\n dtype=float,\n )\n for folder_name in folder:\n prediction = np.load(folder_name + \"prediction.npy\")\n ground_truth = np.load(folder_name + \"test_label.npy\")\n\n scores = scoring(ground_truth, prediction)\n surface_distance = surfd(\n prediction, ground_truth, [0.625, 0.625, 0.625], 1\n )\n diam_vol = diam(prediction, ground_truth)\n results.loc[folder_name] = pd.Series(\n {\n \"dice\": scores[0],\n \"jacquard\": scores[1],\n \"sensibility\": scores[2],\n \"specificity\": scores[3],\n \"surface\": surface_distance.mean(),\n \"hausdorff\": surface_distance.max(),\n \"diam_GT\": diam_vol[0],\n \"diam_pred\": diam_vol[1],\n \"diam_err\": diam_vol[2],\n \"vol_GT\": diam_vol[3],\n \"vol_pred\": diam_vol[4],\n \"vol_err\": diam_vol[5],\n }\n )\n\n return results.mean().to_dict()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T03:12:10.803", "Id": "427050", "Score": "0", "body": "Thank you very much for you answer. Your solution is clean and very nice but I would try to use numpy as much as I can because I am learning and I feel like I am missing some of the basic mechanics of numpy which could help me in the future. But I'll look more into panda because I know that the dataframe class in panda can be interesting to work with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T05:39:07.817", "Id": "427053", "Score": "0", "body": "Pandas uses numpy under the hood. For the thing you want to do, with the support of labelled data, it's way better suited then raw numpy" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T01:36:08.020", "Id": "427193", "Score": "0", "body": "Noted, I look more into it. But I noticed that when I use your method I have different results that doesn't seem correct (nothing else was changed but the piece of code you provided). And I don't know why. I'll keep investigating. Thank you very much" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T06:10:00.660", "Id": "427209", "Score": "0", "body": "Possibly, you need to add `axis=1` as argument to mean" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-24T11:34:31.033", "Id": "220903", "ParentId": "220774", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T23:03:05.727", "Id": "220774", "Score": "3", "Tags": [ "python", "python-3.x", "array", "file", "numpy" ], "Title": "3D metrics for segmentation evaluation" }
220774