Skip to content

Commit 33b8c02

Browse files
committed
Vec3: +flatten_index
1 parent d6dd522 commit 33b8c02

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

src/kg/include/kg/Vec3.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,3 +440,29 @@ using Int3 = Vec3<int>;
440440
using UInt3 = Vec3<unsigned int>;
441441
using Float3 = Vec3<float>;
442442
using Double3 = Vec3<double>;
443+
444+
/**
445+
* @brief Flattens a vec of indices into a single, row-major index.
446+
*
447+
* For example,
448+
* ```c++
449+
* Int3 idx{0, 1, 1};
450+
* Int3 dims{1, 8, 2};
451+
* int flat_idx = flatten_index(idx, dims);
452+
* assert(flat_idx == 3);
453+
* ```
454+
* @tparam T scalar type (likely `int`)
455+
* @tparam N number of elements
456+
* @param idx indices along each dimension
457+
* @param dims lengths of each dimension
458+
* @return the flat index
459+
*/
460+
template <typename T, std::size_t N>
461+
KG_INLINE T flatten_index(const kg::Vec<T, N>& idx, const kg::Vec<T, N>& dims)
462+
{
463+
T flat = idx[0];
464+
for (int i = 1; i < N; i++) {
465+
flat = flat * dims[i] + idx[i];
466+
}
467+
return flat;
468+
}

0 commit comments

Comments
 (0)