Monday, July 18, 2016

index for multi-dimensional array

01234
56789

01234
56789

01234
56789

01234
56789

ij
12 = 1*5 + 2 = 7
11 = 1*5 + 1 = 6
13 = 1*5 + 3 = 8
--
25
mn

ijk
112 = 1*(2*5) + 1*(5) + 2 = 17
302 = 3*(2*5) + 0*(5) + 2 = 32
312 = 3*(2*5) + 1*(5) + 2 = 37
314 = 3*(2*5) + 1*(5) + 4 = 39
---
425
mno

i j k
m n o
index = i*no + j*o + k
index(indices, dimensions):
    if dimensions == null || dimensions.length() == 0:
        throw
    if indices == null || indices.length() != dimensions.length():
        throw
    index = 0
    multiplier = 1
    for i = indices.length() -1, i >= 0, i--:
        checked:
            index += multiplier * indices[i]
            if i == 0:
                break
            multiplier *= dims[i]
    return index
[Hat tip to M]

No comments:

Post a Comment