Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It strikes me that the first thing you should do is order the list. Then it's just a matter of walking through it, remembering the length of your current sequence and detecting when it's ended. To be honest, I <em>suspect</em> that a simple foreach loop is going to be the simplest way of doing that - I can't immediately think of any wonderfully neat LINQ-like ways of doing it. You could certainly do it in an iterator block if you really wanted to, but bear in mind that ordering the list to start with means you've got a reasonably "up-front" cost anyway. So my solution would look something like this:</p> <pre><code>var ordered = list.OrderBy(x =&gt; x); int count = 0; int firstItem = 0; // Irrelevant to start with foreach (int x in ordered) { // First value in the ordered list: start of a sequence if (count == 0) { firstItem = x; count = 1; } // Skip duplicate values else if (x == firstItem + count - 1) { // No need to do anything } // New value contributes to sequence else if (x == firstItem + count) { count++; } // End of one sequence, start of another else { if (count &gt;= 3) { Console.WriteLine("Found sequence of length {0} starting at {1}", count, firstItem); } count = 1; firstItem = x; } } if (count &gt;= 3) { Console.WriteLine("Found sequence of length {0} starting at {1}", count, firstItem); } </code></pre> <p>EDIT: Okay, I've just thought of a rather more LINQ-ish way of doing things. I don't have the time to fully implement it now, but:</p> <ul> <li>Order the sequence</li> <li>Use something like <a href="https://stackoverflow.com/questions/3683105/calculate-difference-from-previous-item-with-linq"><code>SelectWithPrevious</code></a> (probably better named <code>SelectConsecutive</code>) to get consecutive pairs of elements</li> <li>Use the overload of Select which includes the index to get tuples of (index, current, previous)</li> <li>Filter out any items where (current = previous + 1) to get anywhere that counts as the <em>start</em> of a sequence (special-case index=0)</li> <li>Use <code>SelectWithPrevious</code> on the result to get the <em>length</em> of the sequence between two starting points (subtract one index from the previous)</li> <li>Filter out any sequence with length less than 3</li> </ul> <p>I <em>suspect</em> you need to concat <code>int.MinValue</code> on the ordered sequence, to guarantee the final item is used properly.</p> <p>EDIT: Okay, I've implemented this. It's about the LINQiest way I can think of to do this... I used null values as "sentinel" values to force start and end sequences - see comments for more details.</p> <p>Overall, I wouldn't recommend this solution. It's hard to get your head round, and although I'm reasonably confident it's correct, it took me a while thinking of possible off-by-one errors etc. It's an interesting voyage into what you <em>can</em> do with LINQ... and also what you probably shouldn't.</p> <p>Oh, and note that I've pushed the "minimum length of 3" part up to the caller - when you have a sequence of tuples like this, it's cleaner to filter it out separately, IMO.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable&lt;TResult&gt; SelectConsecutive&lt;TSource, TResult&gt; (this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TSource, TResult&gt; selector) { using (IEnumerator&lt;TSource&gt; iterator = source.GetEnumerator()) { if (!iterator.MoveNext()) { yield break; } TSource prev = iterator.Current; while (iterator.MoveNext()) { TSource current = iterator.Current; yield return selector(prev, current); prev = current; } } } } class Test { static void Main() { var list = new List&lt;int&gt; { 21,4,7,9,12,22,17,8,2,20,23 }; foreach (var sequence in FindSequences(list).Where(x =&gt; x.Item1 &gt;= 3)) { Console.WriteLine("Found sequence of length {0} starting at {1}", sequence.Item1, sequence.Item2); } } private static readonly int?[] End = { null }; // Each tuple in the returned sequence is (length, first element) public static IEnumerable&lt;Tuple&lt;int, int&gt;&gt; FindSequences (IEnumerable&lt;int&gt; input) { // Use null values at the start and end of the ordered sequence // so that the first pair always starts a new sequence starting // with the lowest actual element, and the final pair always // starts a new one starting with null. That "sequence at the end" // is used to compute the length of the *real* final element. return End.Concat(input.OrderBy(x =&gt; x) .Select(x =&gt; (int?) x)) .Concat(End) // Work out consecutive pairs of items .SelectConsecutive((x, y) =&gt; Tuple.Create(x, y)) // Remove duplicates .Where(z =&gt; z.Item1 != z.Item2) // Keep the index so we can tell sequence length .Select((z, index) =&gt; new { z, index }) // Find sequence starting points .Where(both =&gt; both.z.Item2 != both.z.Item1 + 1) .SelectConsecutive((start1, start2) =&gt; Tuple.Create(start2.index - start1.index, start1.z.Item2.Value)); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload