Introduction
We all have used matrices, tables, or an array of arrays (2-dimensional array) as data structures. However, we're often faced with the very common problem of representing elements with two distinct keys while using matrices. For example, when traversing over every element of the matrix, we need to have two loops, one on rows and the other on columns. To access an element in a matrix, you need to know two keys the row index and the column index of the element. This property of matrices makes it trickier to use in certain algorithms and we end up switching the data structure. There is a way to represent the position of an element in a matrix with one value rather than using two indexes/keys.
In this article, we will unify the two keys in a matrix into a single key. The only thing is that we need to know is the number of columns in the matrix. This unified key will help us to travel from left to right, continuing for each row just like reading a book. It's a very simple technique to get a unified key. We just have to multiply the row index to the number of columns, then add it to the column index, i.e...
- unifiedIndex = rowIndex * numberOfColumns + columnIndex;
Now the question is: How can we get back the row and column index from this unified key? Again, it's easy. To get the row index, we just have to divide the unified key by the number of columns and the modulus of the unified key by the number of columns and this will give us the column index, i.e...
- rowIndex = unifiedIndex / numberOfColumns;
- columnIndex= unifiedIndex % numberOfColumns;
Here’s the code in C# that demonstrates the implementation and usage of a unified index:
- using System.Collections.Generic;
-
- namespace UnifiedMatrixIndexing
- {
- static class Program
- {
- static int GetUnifiedIndex(this int[,] matrix, int rowIndex, int columnnIndex)
- {
- return rowIndex * matrix.Length + columnnIndex;
- }
- static Dictionary<string, int> GetIndexes(this int[,] matrix, int unifiedIndex)
- {
- return new Dictionary<string, int>()
- {
- {"ROW", unifiedIndex / matrix.Length },
- {"COLUMN", unifiedIndex % matrix.Length }
- };
- }
- static void Main(string[] args)
- {
- int[,] matrix = new int[,] {
- { 1, 2, 3, 4 },
- { 5, 6, 7, 8 },
- { 9, 10, 11, 12 }
- };
-
- int unifiedIndex = matrix.GetUnifiedIndex(2, 1);
-
- Dictionary<string, int> coordinates = matrix.GetIndexes(unifiedIndex);
-
- int element = matrix[coordinates["ROW"], coordinates["COLUMN"]];
-
- }
- }
- }