[英]Most elegant way to get the array element by position?
我有一个数组:
private int[,] _blocks = new int[6, 4];
它代表一组水平为6深度,垂直为4深度的块。 图形上看起来像这样:
替代文字http://www.angryhacker.com/toys/array.png
我需要一个从1到24的数字,并返回匹配的数组元素的函数。 因此,对于数字14,我会返回_blocks [1、2];
我创建了一个简单的函数:
private int GetBlockByPosition(int position)
{
int count = 0;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 4; j++)
{
if (++count == position)
return _blocks[i, j];
}
}
return -1;
}
但这似乎很浪费,而且味道不好。 有没有更优雅,更快捷的方法?
在水平方向和垂直方向上,您都可以在数字表中看到一个模式。 您可以通过position / 6
确定水平位置,并通过position % 6
确定垂直位置-模运算。
private int GetBlockByPosition(int position)
{
return _blocks[((position + 6) / 6) - 1, position % 6];
}
这在数学上是有意义的。 除法以块为单位增加,而模(除法余数)一一增加。 数学很简单。
我不确定我是否遵循,但是为什么您不能仅根据位置计算他的索引? 像这样:
return _blocks[((position - 1) % 6),((position + 5) / 6) - 1];
我想你可以这样:
private int GetBlockByPosition(int position)
{
return _blocks[(position - 1 ) % 6 , (position - 1) / 6];
}
数组中的数字是ACTUALLY 1,2,3,...,还是仅以它们为例?
如果阵列中的数据没有任何可利用的模式,那么看起来简单化选项可能是最好的选择。
或者,您始终可以一次性传递整个结构,并构建一个哈希表以供后续调用使用...
根据您对优雅的定义,以下可能是解决问题的更实用的方法:
class Program
{
static void Main(string[] args)
{
var blocks = new int[,] {{1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18},{19,20,21,22,23,24}};
var position = blocks.FirstPositionOf(14);
Console.WriteLine(position.X + "," + position.Y + " has the element " + blocks[position.X,position.Y]);
}
}
class PositionTuple
{
public int X {get; set;}
public int Y {get; set;}
}
static class ArrayExtensions
{
public static IEnumerable<int> AsEnumerable(this int[,] someTwoDimensionalArray)
{
foreach (var num in someTwoDimensionalArray)
yield return num;
}
public static PositionTuple FirstPositionOf(this int[,] someTwoDimensionalArray, int someNumber)
{
return someTwoDimensionalArray
.AsEnumerable()
.Select((num, index) => new { Number = num, Tuple = new PositionTuple { X = index / (someTwoDimensionalArray.GetUpperBound(1) + 1), Y = index % (someTwoDimensionalArray.GetUpperBound(1)+1) }})
.Where(pair => pair.Number == someNumber)
.Select(pair => pair.Tuple)
.First();
}
}
如果需要,我会提供一个更灵活的功能,可以在其他地方使用
public static T Get2DArrayValueByPosition<T> (T[,] arr, int position)
{
// Gets the size of the array in first dimention
step = arr.GetUpperBound(0) + 1;
return arr[(position / step ), position % step];
}
考虑到极端情况的综合解决方案:
private int GetBlockByPosition(int position)
{
if(position % 6 == 0) { // last cells in each row. 6 gives [0,5]
return _blocks[(position / 6) - 1, (position - 1) % 6];
} else { // 11 gives [1,4]
return _blocks[position / 6 , (position % 6) - 1];
}
}
int result = GetByPosition(_blocks, 14);
private int GetByPosition(int[,] array, int position)
{
return GetByPositionBaseZero(array, position - 1);
}
private int GetByPositionBaseZero(int[,] array, int position)
{
int width = array.GetLength(0);
return array[position % width, position / width];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.