Home > Enterprise >  Integer array to int as map of set bits (one line shorthand)
Integer array to int as map of set bits (one line shorthand)

Time:08-14

I need a map of positive values.

And looking for one-line equivalent of following example:

int[] workplace = new int[]{1, 3, 5, 0, 7, 0, 9, 0, 3, 2, 0, 4};
int map = 0;
for (int i = 0; i < workplace.Length; i  )
    map |= workplace[i] > 0 ? 1 << i : 0;

like:

int[] workplace = new int[]{1, 3, 5, 0, 7, 0, 9, 0, 3, 2, 0, 4};
int map = bla bla bla...;

CodePudding user response:

Int32 map = workplace.Select( ( n, idx ) => ( n > 0 ) ? ( 1 << idx ) : 0 ).Aggregate( seed: 0, func: ( agg, n ) => agg | n );

Works for me:

enter image description here

CodePudding user response:

I would suggest that you replace your current map calculation with a method call. By giving the method a descriptive name and clarifying your intention in the method body, I would argue that you are better off than by compressing logic inside a one-liner of code.

One possible approach is:

int[] workplace = new int[] { 1, 3, 5, 0, 7, 0, 9, 0, 3, 2, 0, 4 };

int map = GetPositiveFlagMapFor(workplace);
private static int GetPositiveFlagMapFor(int[] source)
{
    int map = 0;
    
    for (int i = 0; i < source.Length; i  )
    {
        if (source[i] > 0) // Easy to see that we only care about positive numbers
        {
            map |= 1 << i; // Easy to see what the calculation actually is
        }
    }
    
    return map;
}

(Without knowing the actual purpose of the map calculation, the suggested method name is most likely not on point, but I trust that you get my intention.)

  • Related