Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/rob-blackbourn/jetblack.arrayindexing
Multi dimensional indexing of one dimensional arrays in C#
https://github.com/rob-blackbourn/jetblack.arrayindexing
Last synced: about 1 month ago
JSON representation
Multi dimensional indexing of one dimensional arrays in C#
- Host: GitHub
- URL: https://github.com/rob-blackbourn/jetblack.arrayindexing
- Owner: rob-blackbourn
- License: mit
- Created: 2015-05-15T10:25:21.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2015-05-15T10:41:13.000Z (over 9 years ago)
- Last Synced: 2024-03-15T00:56:04.658Z (8 months ago)
- Language: C#
- Homepage:
- Size: 133 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: License.txt
Awesome Lists containing this project
README
# JetBlack.ArrayIndexing
# Use Case
I had a task where I was presented with a large one-dimensional array, which
represented an n-dimensional matrix. I wanted to be able to index into the
matrix without rebuilding it as multi-dimensional.# Example
The following test demonstates the behaviour.
```cs
var array3D = new IndexableArray(
new[]
{
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,12, 13, 14, 15,
16, 17, 18, 19,
20, 21, 22, 23
},
4, 3, 2);Assert.AreEqual(0, array3D[0, 0, 0]);
Assert.AreEqual(20, array3D[0, 2, 1]);
Assert.AreEqual(23, array3D[3, 2, 1]);
```# Algorithm
The following algorithm is used to transform the n-dimensional indices into a 1-dimensional index.
```cs
public int ToIndex(int[] bounds, params int[] indices)
{
var index = indices[0];
for (int i = 1, sum = bounds[i - 1]; i < indices.Length; ++i, sum *= bounds[i - 1])
index += sum * indices[i];
return index;
}
```It should be clear that the sum of the bounds at each dimension can be
precomputed. The `ArrayIndexer` class does this optimisation.