Home > Software design >  C# Boolean Window Most Common
C# Boolean Window Most Common

Time:04-15

I'm looking to create a moving window that stores boolean values and outputs the most common boolean value.

I want to be able to add new values on the fly, for example:

bool[] window = { false, false, true, true, true };

New 'false' value added, array shifted:

bool[] window = { false, true, true, true, false };

Expected output would be 'true'.

What is the best/most efficient way to go about this? should I use LINQ? any examples would be much appreciated. Thank you.

CodePudding user response:

public class BoolWindow : IEnumerable<bool>
{
    private static int MaxSize = 5;
    private Queue<bool> data = new Queue<bool>(MaxSize);

    public void Add(bool newValue)
    {
        if (data.Count >= MaxSize) data.Dequeue();
        data.Enqueue(newValue);
    }

    public bool MostFrequentValue()
    {
        //What do you want if the size is even and both true and false are the same?
        return data.Select(b => b?1:-1).Sum() > 0;

        // Also: we could optimize this by looping manually until one value
        // is > Count/2, but that's probably more trouble than it's worth
    }    

    public IEnumerator<bool> GetEnumerator()
    {
       return data.GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

CodePudding user response:

According to the question, it is enough to record sum of bool values, if it is true 1, if false - 1. And if aggregated values is > 0 - you have true

public class BoolWindow
{
    private long _counter;

    public void Add(bool newValue)
    {
        if (newValue)
          _counter  = 1;
        else
          _counter -= 1;
    }

    public bool MostFrequentValue()
    {
        return _counter > 0;
    }
}
  • Related