Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A class which maps a fixed size array of integer bijective to a single integer.
namespace Hediet.Math
{
public class BijectivMap
{
private readonly int[] lowerKeyBounds;
private readonly int[] upperKeyBounds;
public BijectivMap(int[] lowerKeyBounds, int[] upperKeyBounds)
{
this.lowerKeyBounds = lowerKeyBounds;
this.upperKeyBounds = upperKeyBounds;
if (upperKeyBounds.Length != lowerKeyBounds.Length)
throw new ArgumentException("upperKeyBounds.length is invalid");
}
public int Minimum { get { return 0; } }
public int Maximum
{
get
{
return lowerKeyBounds.Select((c, i) => upperKeyBounds[i] - c + 1).Aggregate(1, (a, b) => a * b) - 1;
}
}
public int[] GetKeys(int value)
{
int[] result = new int[lowerKeyBounds.Length];
for (int i = result.Length - 1; i >= 0; i--)
{
int factor = (upperKeyBounds[i] - lowerKeyBounds[i] + 1);
result[i] = (value % factor) + lowerKeyBounds[i];
value /= factor;
}
return result;
}
public int GetValue(params int[] keys)
{
if (keys.Length != lowerKeyBounds.Length)
throw new ArgumentException("keys.length is invalid");
int result = 0;
for (int i = 0; i < keys.Length; i++)
{
result = result * (upperKeyBounds[i] - lowerKeyBounds[i] + 1)
+ (keys[i] - lowerKeyBounds[i]);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.