Skip to content

Instantly share code, notes, and snippets.

@jshbrntt
Last active August 29, 2015 14:03
Show Gist options
  • Save jshbrntt/4c3a66baf063ae88983d to your computer and use it in GitHub Desktop.
Save jshbrntt/4c3a66baf063ae88983d to your computer and use it in GitHub Desktop.
Utility functions for swapping a 1D / 2D matrix ordering.
/**
* |0|3|6| => 0 3 6
* | | | | => -----
* |1|4|7| => 1 4 7
* | | | | => -----
* |2|5|8| => 2 5 8
*
* [0,1,2,3,4,5,6,7,8] => [0,3,6,1,4,7,2,5,8]
*
*/
public static function verticalToHorizontalOrder(arr:Array, width:uint, height:uint):Array
{
if (!arr)
return null;
var newArr:Array = new Array();
for (var i:int = 0; i < arr.length; ++i)
{
newArr[i] = arr[Math.floor(i / width) + height * (i % width)];
}
return newArr;
}
/**
* 0 1 2 => |0|1|2|
* ----- => | | | |
* 3 4 5 => |3|4|5|
* ----- => | | | |
* 6 7 8 => |6|7|8|
*
* [0,1,2,3,4,5,6,7,8] => [0,3,6,1,4,7,2,5,8]
*/
public static function horizontalToVerticalOrder(arr:Array, width:uint, height:uint):Array
{
if (!arr)
return null;
var newArr:Array = new Array();
for (var i:int = 0; i < arr.length; ++i)
{
newArr[i] = arr[Math.floor(i / height) + width * (i % height)];
}
return newArr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment