re: Daily Challenge #152 - Strongest Number in an Interval VIEW POST

re: Don't write functions that already exist... let strongestIn (n:int) (m:int) = seq {n..m} |> Seq.maxBy BitOperations.TrailingZeroCount ...

Available since .NET Core 3.0 ... nice touch! Also in F# the Sequence generation is SO MUCH easier.
In C# you'd be better off with a simple for-loop.

public static long StrongestNumber(long start, long end)
   long strongestNum = 0;
   int bitCount = -1;
   for (long i = start; i<=end; ++i)
       int currentBitCount = BitOperations.TrailingZeroCount(i);
       if (currentBitCount > bitCount)
           bitCount = currentBitCount;
           strongestNum = i;
   return strongestNum;

Well, my F# solution translated to C# would be something like this;

static int StrongestIn(int n, int m)
    return Enumerable.Range(n, (m-n))
        .Aggregate((a,b) => BitOperations.TrailingZeroCount(a) > BitOperations.TrailingZeroCount(b)
            ? a : b);

There is no built in "MaxBy" in the C#, so here I replaced it with an Aggregate. (The TrailingZeroCount method will use intrinsics (e.g. a CPU instruction) if its available, so I'm not worried about calling it repeatedly for the accumulator.)

Code of Conduct Report abuse