If you must have an 50% distribution across the two values i.e if a
was returned before, next time it should be b
, you may consider the below logic.
I have used lock to support thread safety. You can remove them if there is no multi threading requirement. I have used a singleton pattern instead of static variable. Based on your need, you may simplify the code to use static variables instead of singleton.
The first determination is done by the checking the second the object is creating is odd or even.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(Singleton.Instance.Randomization("one", "two"));
Console.WriteLine(Singleton.Instance.Randomization("one", "two"));
Console.WriteLine(Singleton.Instance.Randomization("one", "two"));
Console.WriteLine(Singleton.Instance.Randomization("one", "two"));
Console.WriteLine(Singleton.Instance.Randomization("one", "two"));
Console.WriteLine(Singleton.Instance.Randomization("one", "two"));
}
}
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get
{
return lazy.Value;
}
}
private static readonly object _lock = new Object();
private bool _counter;
private Singleton()
{
this._counter = DateTime.Now.Second % 2 == 0;
}
public string Randomization(string a, string b)
{
lock (_lock)
{
_counter = !_counter;
return _counter ? a : b;
}
}
}