Beispiel #1
0
        /// <summary>
        /// Serializes a data document instance into a Subarray&lt;byte&gt; delimited chunk of thread-local buffer.
        /// Because sub-arrays are used for thread-local optimizations, this method should be used in a synchronous-only
        /// thread-bound flows, such as serializing payload into Pile and the returned object must be consumed right away as subsequent calls
        /// to this method will overwrite the previous content as the same thread local physical buffer is re-used.
        /// </summary>
        public static Subarray <byte> SerializeToSubarray(TypedDoc doc)
        {
            var stream = ts_WriteStream;
            var writer = ts_Writer;
            var result = ts_Subarray;

            if (stream == null)
            {
                stream = new MemoryStream(INITIAL_BUFFER_CAPACITY);
                writer = SlimFormat.Instance.GetWritingStreamer();
                writer.BindStream(stream);
                result         = new Subarray <byte>();
                ts_WriteStream = stream;
                ts_Writer      = writer;
                ts_Subarray    = result;
            }

            stream.Position = 0;
            Serialize(doc, writer, true);

            result.Set(stream.GetBuffer(), (int)stream.Position);

            //don't let large hunk dangling in the TLS
            if (stream.Capacity > BUFFER_TRIM_CAPACITY)
            {
                stream.SetLength(0);
                stream.Capacity = INITIAL_BUFFER_CAPACITY;
            }

            return(result);
        }
Beispiel #2
0
        public void PutSubarray()
        {
            using (var pile = new DefaultPile(NOPApplication.Instance))
            {
                pile.Start();

                var src = new byte[] { 1, 6, 9, 250 };
                var sub = new Subarray <byte>();
                sub.Set(src, 2);

                var ptr1 = pile.Put(sub);
                sub.Set(src, 4);
                var ptr2 = pile.Put(sub);
                var got1 = pile.Get(ptr1) as byte[];
                var got2 = pile.Get(ptr2) as byte[];

                Aver.IsNotNull(got1);
                Aver.AreEqual(2, got1.Length);
                Aver.AreEqual(1, got1[0]);
                Aver.AreEqual(6, got1[1]);

                Aver.IsNotNull(got2);
                Aver.AreEqual(4, got2.Length);
                Aver.AreEqual(1, got2[0]);
                Aver.AreEqual(6, got2[1]);
                Aver.AreEqual(9, got2[2]);
                Aver.AreEqual(250, got2[3]);
            }
        }
        public static Subarray FindSmallestSequentiallyCoveringSubset(List <string> paragraph, List <string> keywords)
        {
            // Maps each keyword to its index in the keywords array.
            var keywordToIdx = new Dictionary <string, int>();

            // Since keywords are uniquely identified by their indices in keywords
            // array, we can use those indices as keys to lookup in a vector.
            var latestOccurrence = new List <int>();

            // For each keyword (identified by its index in keywords array), stores the
            // length of the shortest subarray ending at the most recent occurrence of
            // that keyword that sequentially cover all keywords up to that keyword.
            var shortestSubarrayLength = new List <int>();

            // Initializes latestOccurrence , shortestSubarrayLength , and keywordToIdx.
            for (var i = 0; i < keywords.Count; ++i)
            {
                latestOccurrence.Add(-1);
                shortestSubarrayLength.Add(int.MaxValue);
                keywordToIdx[keywords[i]] = i;
            }

            var shortestDistance = int.MaxValue;
            var result           = new Subarray(-1, -1);

            for (var i = 0; i < paragraph.Count; ++i)
            {
                if (keywordToIdx.ContainsKey(paragraph[i]))
                {
                    var keywordIdx = keywordToIdx[paragraph[i]];
                    if (keywordIdx == 0) // First keyword.
                    {
                        shortestSubarrayLength[0] = 1;
                    }
                    else if (shortestSubarrayLength[keywordIdx - 1] != int.MaxValue)
                    {
                        var distanceToPreviousKeyword = i - latestOccurrence[keywordIdx - 1];
                        shortestSubarrayLength[keywordIdx] =
                            distanceToPreviousKeyword + shortestSubarrayLength[keywordIdx - 1];
                    }

                    latestOccurrence[keywordIdx] = i;

                    // Last keyword, look for improved subarray.
                    if (keywordIdx == keywords.Count - 1 &&
                        shortestSubarrayLength[shortestSubarrayLength.Count - 1] < shortestDistance)
                    {
                        shortestDistance = shortestSubarrayLength[shortestSubarrayLength.Count - 1];
                        result.Start     = i - shortestSubarrayLength[shortestSubarrayLength.Count - 1] + 1;

                        result.End = i;
                    }
                }
            }

            return(result);
        }
Beispiel #4
0
        // Solution One
        public static Subarray FindSmallestSubarrayCoveringSet(List <string> paragraph, HashSet <string> keywords)
        {
            var keywordsToCover = new Dictionary <string, int>();

            foreach (var keyword in keywords)
            {
                keywordsToCover[keyword] = keywordsToCover.ContainsKey(keyword) ? keywordsToCover[keyword] + 1 : 1;
            }

            var result           = new Subarray(-1, -1);
            var remainingToCover = keywords.Count;

            var left = 0;

            for (var right = 0; right < paragraph.Count; ++right)
            {
                if (keywordsToCover.ContainsKey(paragraph[right]))
                {
                    var keywordCount = keywordsToCover[paragraph[right]];

                    keywordsToCover[paragraph[right]] = --keywordCount;
                    if (keywordCount >= 0)
                    {
                        --remainingToCover;
                    }
                }

                // Keeps advancing left until it reaches end or keywordsToCover does not
                // have all keywords.
                while (remainingToCover == 0)
                {
                    if ((result.Start == -1 && result.End == -1) ||
                        right - left < result.End - result.Start)
                    {
                        result.Start = left;
                        result.End   = right;
                    }

                    if (keywordsToCover.ContainsKey(paragraph[left]))
                    {
                        var keywordCount = keywordsToCover[paragraph[left]];

                        keywordsToCover[paragraph[left]] = ++keywordCount;
                        if (keywordCount >= 0)
                        {
                            ++remainingToCover;
                        }
                    }
                    ++left;
                }
            }

            return(result);
        }
Beispiel #5
0
        // Solution Two
        public static Subarray FindSmallestSubarrayCoveringSubset(IEnumerator <string> iter, List <string> queryStrings)
        {
            var dict = new Dictionary <string, int>();

            foreach (var s in queryStrings)
            {
                dict[s] = int.MinValue;
            }

            var numStringsFromQueryStringsSeenSoFar = 0;

            var result = new Subarray(-1, -1);
            var idx    = 0;
            var loc    = new List <string>();

            while (iter.MoveNext())
            {
                var s = iter.Current ?? string.Empty;

                if (dict.ContainsKey(s))
                {
                    // s is in queryStrings.
                    var it = dict[s];
                    if (it == int.MinValue)
                    {
                        // First time seeing this string from queryStrings.
                        numStringsFromQueryStringsSeenSoFar++;
                    }

                    loc.Remove(s);
                    dict[s] = idx;
                    loc.Add(s);
                }

                if (numStringsFromQueryStringsSeenSoFar == queryStrings.Count)
                {
                    // We have seen all strings in queryStrings, let’s get to work.
                    if ((result.Start == -1 && result.End == -1) ||
                        idx - dict[loc.First()] < result.End - result.Start)
                    {
                        result.Start = dict[loc.First()];
                        result.End   = idx;
                    }
                }
                ++idx;
            }
            return(result);
        }
Beispiel #6
0
        public void Given_ArrayWithPositiveValues_Expect_NumberInArrayWithSmallestMagnitude(int[] i, int e)
        {
            int a = Subarray.FindLargestSumOfContiguousSubarray(i);

            Assert.True(a == e, "Actual: " + a);
        }
Beispiel #7
0
 public void Given_InvalidArray_Expect_ThrowsArgumentException(int[] i)
 {
     Assert.Throws <ArgumentException>(() => Subarray.FindLargestSumOfContiguousSubarray(i));
 }
Beispiel #8
0
        public void Given_ValidArray_Expect_LargestSum(int[] i, int e)
        {
            int a = Subarray.FindLargestSumOfContiguousSubarray(i);

            Assert.True(a == e, "Actual: " + a);
        }
        public void Given_ValidArray_Expect_ReturnsMaximumProduct(int[] d, int e)
        {
            int a = Subarray.MaximumProduct(d);

            Assert.True(a == e, "Expected: " + e + " Actual: " + a);
        }
 public void Given_NullOrEmptyArray_Expect_ThrowsArguementException(int[] i)
 {
     Assert.Throws <ArgumentException>(() => Subarray.MaximumProduct(i));
 }