Spectra
❔ ✅ Dice Roll with Generic Math
Has someone use non-generic funcs with generic math... The solution that I have found is a bit hack.
There would be solutions that dont involves a bunch of conditionals?
public readonly struct Dice
{
public readonly int sides;
public Dice(int sides) => this.sides = sides;
public override string ToString() => sides.ToString();
public double GetAverage() => (sides + 1) / 2.0;
public int RollInt(Random rng) => rng.Next(1, sides + 1);
public long RollLong(Random rng) => rng.NextInt64() * sides + 1;
public float RollFloat(Random rng) => rng.NextSingle() * sides + 1;
public double RollDouble(Random rng) => rng.NextDouble() * sides + 1;
public T Roll<T>(Random rng) where T : INumber<T>
{
var type = typeof(T);
if (type == typeof(int))
return (T)(object)RollInt(rng);
if (type == typeof(long))
return (T)(object)RollLong(rng);
if (type == typeof(float))
return (T)(object)RollFloat(rng);
if (type == typeof(double))
return (T)(object)RollDouble(rng);
return T.One;
}
}
public readonly struct Dice
{
public readonly int sides;
public Dice(int sides) => this.sides = sides;
public override string ToString() => sides.ToString();
public double GetAverage() => (sides + 1) / 2.0;
public int RollInt(Random rng) => rng.Next(1, sides + 1);
public long RollLong(Random rng) => rng.NextInt64() * sides + 1;
public float RollFloat(Random rng) => rng.NextSingle() * sides + 1;
public double RollDouble(Random rng) => rng.NextDouble() * sides + 1;
public T Roll<T>(Random rng) where T : INumber<T>
{
var type = typeof(T);
if (type == typeof(int))
return (T)(object)RollInt(rng);
if (type == typeof(long))
return (T)(object)RollLong(rng);
if (type == typeof(float))
return (T)(object)RollFloat(rng);
if (type == typeof(double))
return (T)(object)RollDouble(rng);
return T.One;
}
}
58 replies