Skip to content

Instantly share code, notes, and snippets.

@hediet
Created March 9, 2015 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hediet/ce2ce9104f34ac38caf3 to your computer and use it in GitHub Desktop.
Save hediet/ce2ce9104f34ac38caf3 to your computer and use it in GitHub Desktop.
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