Search the Community
Showing results for tags 'map index to array'.
-
I was reading a recent post about converting a 2D array into a 1D array. The OP, from my understanding, more-or-less wanted to extract a single column of data and format it in a 1D array. The solutions were proper and efficient compared to what I wanted to share, but I figured I'd share as it's a good lesson and a neat, purely mathematical approach to mapping an index to a 2D array. As-is, this only works for 2D arrays. By knowing how big a 2D array is, an index can be calculated for each indices/subscript. The functions below define a random sized 2D array, and calculate an index that matches the indices on the 2D array. #include "Array.au3" $iRow = Random(2,10,1) $iCol = Random(2,10,1) $iRandomIndex = Random(0,($iRow*$iCol)-1,1) $sIndicies = _IndexTo2DIndicies($iRandomIndex, $iRow, $iCol) _2DArrayTo1DIndexes($iRow, $iCol, $iRandomIndex & " = $aArr" & $sIndicies) Func _2DArrayTo1DIndexes($iRow = 1, $iCol = 1, $sMsg = Default) $iRow = Int($iRow) $iCOl = Int($iCol) Local $aData[$iRow][$iCol] For $iY = 0 to $iRow - 1 For $iX = 0 to $iCol - 1 Local $iIndex ;Index = ($iColMax * $iY) + $iX $aData[$iY][$iX] = ($iCol * $iY) + $iX Next Next If $sMsg = Default Then $sMsg = "1D Indexes of 2D Array Indicies" _ArrayDisplay($aData,$sMsg) EndFunc Func _IndexTo2DIndicies($iIndex = 0, $iRow = 0, $iCol = 0) $iIndex = Int($iIndex) $iRow = Int($iRow) $iCol = Int($iCol) If $iIndex = 0 Then Return "[0][0]" If $iIndex >= $iRow * $iCol Then Return SetError(1,0,0) Local $iX = Mod($iIndex, $iCol) ;Local $iY = ($iIndex-$iX) / $iCol Local $iY = Int($iIndex / $iCol) ;Thanks Chimp Return "[" & $iY & "][" & $iX & "]" EndFunc I used this type of approach before with a pixel array. I had a 1D array for storing individual pixel information, then mapped the pixels to an X|Y grid (2D array or XY coords). Now if the purpose is just to flatten an array, the most efficient way I am aware of would be to create a new 1D array the size of the total number of indices in the 2D array (RowMax * ColMax), and loop through the array. I suppose these methods (above) would be particularly useful if you need to randomly or programmatically access indices in a non-linear fashion. Anyways, just wanted to share a fun exercise with arrays.