Saturday, April 8, 2017

Operate on subsets of arrays using LINQ

LINQ Take() and Skip() make it easy to operate on subsets of an array, or any IEnumerable.

Sample problem: I want to know if a number is a contiguous sequence of digits in ascending order

       
Sample solution using Skip() and Take()
private static bool isAsc(int tester)
        {
          char[] asc = tester.ToString().Replace("0", ":").ToCharArray();
         
           char prev = asc[0];
           foreach(char c in asc.Skip(1))
           {
             prev++;
             if(prev != c)
              return false;
           }
           return true;
        }


if i didn't have Skip() available i would have written that like this:
for(int i = 1; i < asc.Length; i++)

Now, what if I wanted to find out if a subset had the property? Let's say, I want to know if the 2nd-5th digits have the property. In this case i would use Skip() + Take()

private static bool isAsc(int tester)
        {
          char[] asc = tester.ToString().Replace("0", ":").ToCharArray();
         
           char prev = asc[0];
           foreach(char c in asc.Skip(1).Take(3))
           {
             prev++;
             if(prev != c)
              return false;
           }
           return true;
        }


Ref:
1. Code Wars kata i used Skip() on: https://www.codewars.com/kata/52c4dd683bfd3b434c000292







No comments:

Post a Comment

There was an error in this gadget