A library for bijectively mapping all ordered pairs
- Mathematical Model
- Forward Mapping (Pair → Index)
- Inverse Mapping (Index → Pair)
- Installation
- Quick Start
- API Reference
- Examples
- Edge Cases & Error Handling
- Contribution
- License
Define:
-
$N = |A|$ , the size of set A -
$M = |B|$ , the size of set B $L = \min(N, M)$ $H = \max(N, M)$ $P = N \times M$ $S = N + M$
For any pair
which ranges from
-
Region I (Ascending Triangle):
$2 \le w \le L+1$ -
Region II (Rectangle):
$L+2 \le w \le H$ (only if$H-L\ge2$ ) -
Region III (Descending Triangle):
$H+1 \le w \le S$
Define cumulative counts:
$C_1 = \sum_{s=2}^{L+1}(s-1) = \frac{L(L+1)}{2}$ -
$C_2 = C_1 + L,(H-(L+1))$ if$H-L\ge2$ , else$C_2=C_1$ $C_3 = P$
These are the total indices up to each region boundary.
Compute
- Base count:
-
Zig-zag offset:
- If
$(w-1)\bmod2=0$ , offset =$i$ . - Else, offset =
$j$ .
- If
-
Index:
- Diagonal index:
$d = w - (L+2)$ . - Each diagonal has
$L$ pairs. - Coordinate selector:
- Index:
- Mirror weight:
$w' = S - w + 2$ . - Compute
$B(w')$ and offset as in Region I. - Index:
Given
- If
$k\le C_1$ , Region I - Else if
$k\le C_2$ , Region II - Else, Region III
Then:
- Solve quadratic for weight:
- Compute offset: if
$(w-1)\bmod2=0$ ,$i = k-B(w), j=w-i$ ; else$j=k-B(w), i=w-j$ . - For Region III, set
$w'$ and invert mirror.
- Diagonal index:
$d = \lfloor(k-C_1-1)/L\rfloor$ - Weight:
$w = L+2 + d$ - Selector:
$\alpha = (k-C_1-dL)$ - Recover: if
$N<M$ ,$i=\alpha, j=w-i$ ; else$j=(M+1)-\alpha, i=w-j$ .
All formulas are closed-form integer ops (
Python:
pip install kombin-algo-pranavpatel-ca
C# (.NET):
dotnet add package Ca.Pranavpatel.Algo.Kombin
Java (Maven):
<dependency>
<groupId>ca.pranavpatel.algo</groupId>
<artifactId>kombin</artifactId>
<version>1.0.3</version>
</dependency>
TypeScript/JavaScript:
npm install kombin
Python
from kombin_algo_pranavpatel_ca import Table
t = Table(5,4,True)
idx = t.GetIndexOfElements(2,3)
ai,bi = t.GetElementsAtIndex(idx)
C# (.NET):
using Ca.Pranavpatel.Algo.Kombin;
var tbl = new Table(5,4,true);
var idx = tbl.GetIndexOfElements(2,3);
var (i,j) = tbl.GetElementsAtIndex(idx);
Java
Table tbl = new Table(5,4,true);
long idx = tbl.GetIndexOfElements(2,3);
Pair p = tbl.GetElementsAtIndex(idx);
Typescript
import {Table} from 'kombin';
const tbl = new Table(5,4,true);
const idx = tbl.GetIndexOfElements(2,3);
const [i,j] = tbl.GetElementsAtIndex(idx);
Constructor: Table(lengthOfA, lengthOfB, zeroBasedIndex)
Methods:
GetIndexOfElements(ai, bi) -> number
GetElementsAtIndex(index) -> [ai, bi]
# Enumerate all pairs by weight
t = Table(3,3,False)
for k in range(1,10): print(k, t.GetElementsAtIndex(k))
// Random access
long pos = tbl.GetIndexOfElements(4,2);
var pair = tbl.GetElementsAtIndex(7);
- Invalid indices throw errors.
- Sum > N+M invalid.
- Large N,M may overflow; implementations use checked arithmetic.
- Fork
- Branch
- Commit
- PR
MIT License. See LICENSE.