Recent Entries 10
- debug minor 112d agoImplementation of fixed size queue using a ring (cyclic) bufferI found myself in need of a fixed size queue and decided to implement one using a ring (cyclic) buffer. I have tried my best to match the API of `std::queue` with the addition of `full()` to test if the queue is full and unable to accept another element. The code compiles cleanly with: `-Wall -Wextra -pedantic --std=c++14 -lgtest -lgtest_main`, it runs and all tests pass on clang 3.9.1. Unfortunately at least GCC 4.9.4 and below cannot compile the header file due to a bug where a `noexcept` specification can't refer to a member. All comments welcome. File: `xtd/fixed_queue.hpp` ``` #ifndef GUARD_INCLUDE_XTD_FIXED_QUEUE_HPP #define GUARD_INCLUDE_XTD_FIXED_QUEUE_HPP #include #include #include namespace xtd { template class fixed_queue { public: using value_type = T; using reference = value_type&; using const_reference = const value_type&; using size_type = std::size_t; fixed_queue() = default; fixed_queue(const fixed_queue& other) { *this = other; } fixed_queue(fixed_queue&& other) { *this = std::move(other); } ~fixed_queue() { clear(); } fixed_queue& operator=(const fixed_queue& other) { clear(); auto i = other.m_read_idx; while (i != other.m_write_idx) { emplace(*other.get(i)); i = other.increment_index(i); } return *this; } fixed_queue& operator=(fixed_queue&& other) { clear(); while (!other.empty()) { emplace(std::move(other.front())); other.pop(); } return *this; } size_type capacity() const { return N; } size_type size() const { if (empty()) { return 0; } else if (m_write_idx > m_read_idx) { return m_write_idx - m_read_idx; } else { return N - m_read_idx + m_write_idx + 1; } } void clear() { while (!empty()) { pop(); } } bool full() const { return size() == capacity(); } bool empty() const { return m_write_i
- debug minor 112d agoFixed size dictionary to achieve performance goalsIn my open source project, I have code that uses a dictionary very intensively so a system dictionary implementation did not suit me due to performance reasons. Therefore, I decided to write my own implementation that uses unsafe code. Fortunately, I can use integers as dictionary keys and I always know the max dictionary size. Here is the implementation of the specific collection: ``` using System.Collections; using System.Collections.Generic; using System.Linq; namespace logviewer.logic.support { public unsafe class FixedSizeDictionary : IDictionary { private readonly int count; private int[] indexes; private T[] store; public FixedSizeDictionary(int count) { this.count = count; this.store = new T[count]; this.indexes = new int[count]; } public IEnumerator> GetEnumerator() { for (var i = 0; i (i, this.store[i]); } } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public void Add(KeyValuePair item) { this.Add(item.Key, item.Value); } public void Clear() { this.store = new T[this.count]; this.indexes = new int[this.count]; } public bool Contains(KeyValuePair item) { return this.indexes[item.Key] > 0 && Equals(this.store[item.Key], item.Value); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { for (var i = arrayIndex; i (i, this.store[i]); } } } public bool Remove(KeyValuePair item) { return this.Remove(item.Key); } public int Count { get { var result = 0; for (var i = 0; i false; public bool ContainsKey(int key) {
- pattern minor 112d agoRemove duplicate elements from array along with element using Java 1.7I need to write a method where a int[] will be supplied as an input and it should return an array, but with all of the numbers that occur more than n times removed entirely. Input: ``` (int list) data = [1, 2, 2, 3, 3, 3, 4, 5, 5] ``` Output: ``` (int list) [1, 4] ``` These are the steps i have tried: - Copy the int array to ArrayList (inputList). - Create a LinkedHashset to find unique values - Iterate LH and find the collection frequency of ArrayList with iterator. ``` int[] intArray = new int[0]; ArrayList inputList = new ArrayList(data.length); //System.out.println(Arrays.toString(data)); for (int i = 0; i lhs = new LinkedHashSet<>(inputList); intArray = new int[lhs.size()]; int i=0; int j=0; Iterator itr = lhs.iterator(); while(itr.hasNext()){ Integer shiftNumber = itr.next(); if(Collections.frequency(inputList, shiftNumber)==1) { intArray[i++] = shiftNumber.intValue(); j++; } } intArray = Arrays.copyOf(intArray, j); return intArray; } } return intArray; ``` I am able to achieve the results with the above snippet.However, I need suggestions in reducing the piece of code and improving performance by using any algorithms or other collection objects.
- pattern minor 112d agoc++ std::array implementationJust after a review of my implementation of std::array. I created this to find the sweet spot between speed and nice code. I would really appreciate any guidance towards improving. Note: I use parts of my meta-programming library you can find: https://github.com/sigma-blight/sigma_api [sigma_api/sigma/meta/]. ``` /* Static Size Container Array * * Wrapper class to a c-array of Tp_[n_] * * @tparam Tp_ -> element type * @tparam n_ -> size of array */ template class Array { /* EnableCMem * check for the ability to * use `memcpy` and `memmove` * from a type Vp_ to a type Tp_ */ template using EnableCMem = meta::BoolConstant::value && std::is_pod::value >; /* Store size of data array in type * for zero overhead */ using DataSize = meta::SizeConstant; /* Raw Data */ Tp_ _data[n_]; public: //============================================ // ** Initialisation ** //============================================ /* Maintain default initialisation * from compilier * * default: * ~ Default Ctor * ~ Copy Ctor * ~ Move Ctor * ~ Destructor * ~ Copy Assignment Operator * ~ Move Assignment Operator */ Array(void) = default; Array(const Array &) = default; Array(Array &&) = default; ~Array(void) = default; Array & operator = (const Array &) = default; Array & operator = (Array &&) = default; /* Values Constructor * * move a variadic list of values into the raw data * * enabled when exactly n_ many values are provided * * @tparam Tps_ -> parameter pack of arguments to move assign * * ASSERT: Every Tps_ is move assignable */ template == n_ >> Array(Tps_ && ... values) : _data{ std::move(values) ... } {} //============================================ // **
- pattern minor 112d agoFind a Value in a ContainerI have created a simple function to determine if a container contains a value. It allows for certain conditions to be set as well: where to to start searching for value, which way to search, whether to find the first or the last occurrence of the value, and whether or not to include the starting point. I want its return value to be either the index of the matching element, or -1 if no matches were found. ``` template int Vec_Find(const Container& c, int size, const T& val, int pivot_idx = 0, bool find_first = true, bool ltr = true, bool include_pivot = true) { if (find_first && ltr) { if (include_pivot) pivot_idx++; int i = std::distance(std::begin(c), std::find(std::begin(c) + pivot_idx, std::end(c), val)); if (i != size) return i; } else if (find_first && !ltr) { if (!include_pivot) pivot_idx--; int i = std::distance(std::find(std::rbegin(c) + (size - pivot_idx - 1), std::rend(c), val), std::rend(c) - 1); if (i != -1) return i; } else if (!find_first && ltr) { if (include_pivot && (c[pivot_idx] == val)) return pivot_idx; int i = std::distance(std::find(std::rbegin(c), std::rend(c) - (pivot_idx + 1), val), std::rend(c) - 1); if (i != pivot_idx) return i; } else { if (include_pivot) pivot_idx++; int i = std::distance(std::begin(c), std::find(std::begin(c), std::begin(c) + pivot_idx, val)); if (i != pivot_idx) return i; } return -1; } ``` I am a student to C++ and am looking for ways to code better, I appreciate all suggestions. To Editors: I wasn't sure if I should leave my long lines on one line or fit to screen, please let me know if they should be on one line, and I will update it.
- pattern minor 112d agoFixedStack of the Container hierarchy in JavaIntroduction/Disclaimer This is a project for educational purposes. I'm not intending to replace the "award-winning" Collections Framework in `java.util`. I'm just looking for constructive criticism. For obvious reasons, I'm tagging it as reinventing-the-wheel. I'd like to see someone break my code. Preferably in a multi-threaded environment. (My code is not thread-safe) Overview The `Container` class defines the minimal skeletal structure for all Data Structures that I implement. Depending on the requirement, I'm providing two implementations: Fixed capacity implementations and implementations using Linked Lists. For this question, I'm limiting the discussion to `FixedStack` and all the related classes. `Container.java` ``` package astrobleme.core.datastructures; import java.util.Arrays; import java.util.StringJoiner; /** * This is the root of the Container hierarchy. This contains methods * that provide a common skeletal structure to all implementations. The * modifying methods will have different names, depending on the type of * data structure it is. * * @author Subhomoy Haldar * @version 2017.02.15 */ public abstract class Container { /** * Returns the number of elements currently in the Container. It is * guaranteed to be a non-negative number. * * NOTE: If the number of elements exceeds * {@link Long#MAX_VALUE Long#MAX_VALUE}, then it will return * {@code Long#MAX_VALUE}. * * @return The number of elements in this Container. */ abstract long size(); /** * Returns {@code true} if the number of elements in this Container is * within the allowed maximum size for arrays, and hopefully, it might * be able to create an array out of it. * * However, it depends on the amount of memory allocated by the VM and * even smaller sizes may cause a {@link OutOfMemoryError}. It is advised * to re-start the VM with different arguments to allow for allocation * of
- pattern minor 112d agoEnumerable Custom Collections in VBA with Dictionary features like ExistsTo Collect or Hash The `VBA.Collection` has a number of limitations, but it is enumerable and you can refer to items by index or key. But the VBA implementation of a Collection is 1-based, and they don't have any way of confirming membership, and the `Item` method returns a `Variant`, so they're loosely typed. Did I say `Item` method? Yes, that's right, `Item` is a method. Let's make it a property while we're at it. Dictionaries aren't enumerable, but they have useful methods like `Exists` and `RemoveAll`. They're implemented as hash-tables behind the scenes, so they're faster than Collections for retrieving members and/or for confirming membership. What if I could combine the best features of Collections and Dictionaries? - 0 or 1 based (user configurable) - Strongly typed `Item` method - `Item` method is default member, and it's a property - `Exists` method for membership checks - Enumerable - Add a Widget to the collection without having to specify a key And why not throw in a factory method too, although some might argue it's a return to the year 2000. In order to get the enumerable features of a Collection, I'll have to use a Collection behind the scenes, but I'll augment that with a Dictionary that keeps track of the keys used in the Collection. Then, when I want to test the `Exists` method, I can check the Dictionary (and get all of it's hash-tabled goodness) instead of enumerating the Collection or suppressing a potential error by checking the index/key directly. I also want to make the Collection configurable so that it can be 0 or 1 based according to preference. I've made this setting private to the Collection, so it's up to the developer to adjust for the purpose at hand, but it could easily be exposed as property or set in a factory method. Pass the Widget First, we need a class for the objects that we'll put into our custom collection. A `Widget` will do nicely. Nothing special here - just a class with a few encapsulated fields, and a bonu
- pattern minor 112d agoBasic generic priority queue using an unsorted listI am aware that there are other ways of implementing a priority queue e.g. using a sorted array/list. Would appreciate some comments on my implementation of a basic priority queue supporting three simple operations: `Insert, Min, Max` ``` public class QueueEntry : IComparable> where TKey : IComparable { public QueueEntry(TKey key, TValue value) { Key = key; Value = value; } public TKey Key { get; } public TValue Value { get; } public int CompareTo(QueueEntry other) { if (EqualityComparer>.Default.Equals(this, other)) return 0; if (other == null) throw new ArgumentNullException(); return Key.CompareTo(other.Key); } public override string ToString() => $"Key = {Key}, Value = {Value}"; } public sealed class PriorityQueue where TKey : IComparable { private List> items; private TKey minKey; private TKey maxKey; private int minIndex; private int maxIndex; public PriorityQueue(int capacity) { items = new List>(capacity); minKey = default(TKey); maxKey = default(TKey); minIndex = maxIndex = 0; } public PriorityQueue() : this(10) { } public void Insert(QueueEntry entry) { if (entry == null) throw new ArgumentNullException(nameof(entry)); var key = entry.Key; if (items.Count == 0) // first item { minKey = key; maxKey = key; } else if (key.CompareTo(minKey) 0) // a new max key { maxKey = key; maxIndex = items.Count; } items.Add(entry); } public int Count => items.Count; public bool IsEmpty => items.Count == 0; //Delete the entry with the min key; O(n). public void DeleteMin() { if (IsEmpty) throw new InvalidOperationException("Queue is empty"); items.Remove(items[minIndex]); if (!IsEmpty) { minIndex = 0;
- pattern minor 112d agoDetermine Groups and Children In CollectionI am currently looking into improving code efficiency while working with a flat string collection in C#. The strings in this collection can be considered a "group" or a "child". The problem is that the API for this collection is exposed in such a way that the type of each String in the collection is not directly retrievable and must be determined through other properties. An example collection: `[0] Group Item [1] Child Item [2] Child Item [3] Child Item [4] Child Item [5] Group Item [6] Child Item [7] Child Item [8] Group Item [9] Child Item [10] Child Item [11] Child Item ` For the collection the following is true: - Position 0 is always a group item - There can be 0 to N child items between two group items - The content of the string does not indicate if a string is a child or a group The following data is available to determine group/child types: - ItemCount (The total amount of strings in the collection) - GroupCount (The total amount of group strings in the collection) - GetChildCount(int groupIndex) (The amount of child items after the group with groupIndex before the next group item) The data I need to determine is: - Group position (The position of a group item based on its zero based index. For example: The group index of 2 should return position 8 from the example collection) - Child position (The position of a child item based on its zero based group index and child index. For example: The group index of 0 and child index of 3 should return position 4 from the example collection, and a group index of 2 and a child index of 0 should return position 9) - The reverse of the above (The indexes for the positions) Currently I have created up the following methods to determine these values: ``` public bool IsGroupPosition(int position) { int currPosition = 0; for(int i = 0;i position) { return false; //We passed the position, this is no group item } else { return true; //The p
- pattern minor 112d agoJava Singly Linked ListHere is a naive version of a singly linked list in Java. It implements only `Collection` and `Iterable` interfaces. Any comments and suggestions are welcome. SinglyLinkedList.java: ``` package com.ciaoshen.thinkinjava.newchapter17; import java.util.*; public class SinglyLinkedList implements Collection, Iterable { private int size = 0; private Node head = new Node(); // constructor public SinglyLinkedList() { head.setNext(head); } public SinglyLinkedList(Collection c) { this(); addAll(c); } // unmodifiable collection (except remove() method) public Iterator iterator() { return new Iterator() { Node cursor = head; Node previous = head; public boolean hasNext() { return cursor.getNext() != head; } public E next() { if (! hasNext()) { throw new IndexOutOfBoundsException("Iterator has reached the end of the list!"); } Node toReturn = cursor.getNext(); previous = cursor; cursor = toReturn; return toReturn.getInfo(); } public void remove() { // only remove once the last node return by next() method. if (cursor == previous) { throw new IndexOutOfBoundsException("Cannot remove current node. Last node returned by next() already removed, or reach the head of the list!"); } previous.setNext(cursor.getNext()); cursor.setNext(null); cursor = previous; size--; } }; } public int size() { return size; } public String toString() { if (isEmpty()) { return "[]"; } StringBuilder sb = new StringBuilder(); Iterator ite = iterator(); sb.append("["); while (ite.hasNext()) { sb.app