Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I believe the most optimal way to do this is to create a "LINQ-like" extension methods using an iterator block. This allows you to perform the calculation doing a single pass over your data. Note that performance isn't important at all if you just want to perform the calculation on a small array of numbers. Of course this is really your for loop in disguise.</p> <pre><code>static class Extensions { public static IEnumerable&lt;Tuple&lt;T, Int32&gt;&gt; ToRunLengths&lt;T&gt;(this IEnumerable&lt;T&gt; source) { using (var enumerator = source.GetEnumerator()) { // Empty input leads to empty output. if (!enumerator.MoveNext()) yield break; // Retrieve first item of the sequence. var currentValue = enumerator.Current; var runLength = 1; // Iterate the remaining items in the sequence. while (enumerator.MoveNext()) { var value = enumerator.Current; if (!Equals(value, currentValue)) { // A new run is starting. Return the previous run. yield return Tuple.Create(currentValue, runLength); currentValue = value; runLength = 0; } runLength += 1; } // Return the last run. yield return Tuple.Create(currentValue, runLength); } } } </code></pre> <p>Note that the extension method is generic and you can use it on any type. Values are compared for equality using <code>Object.Equals</code>. However, if you want to you could pass an <code>IEqualityComparer&lt;T&gt;</code> to allow for customization of how values are compared.</p> <p>You can use the method like this:</p> <pre><code>var numbers = new[] { 4, 1, 1, 3, 3, 2, 5, 3, 2, 2 }; var runLengths = numbers.ToRunLengths(); </code></pre> <p>For you input data the result will be these tuples:</p> <pre> 4 1 1 2 3 2 2 1 5 1 3 1 2 2 </pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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