Ere*_*rez 5 .net c# arrays algorithm
我有一个家庭作业:
需要实现一个获取INT数组和数字的函数(RotateRight):
int[] res = RotateRight(new int[] { 1, 2, 3, 4, 5, 6 }, 2);
//so then res will be {5,6,1,2,3,4}
Run Code Online (Sandbox Code Playgroud)
并根据给出的数字将所有项目向右旋转后返回数组,在我们的例子中为2.
而且我必须在内存空间方面有效地做到这一点.
我最好的想法是:
如果给出的数字是x,则使用x大小的新int [] tmpArray将所有最后x个项目复制到它.然后使用for循环将int的所有其余部分向右移动.最后将tmpArray中的项目复制到原始数组的开头.
提前感谢任何建议或帮助
您可以使用Linq语言的优点来返回IEnumerable而不处理数组大小:
/// <summary>
/// Get c = a mod (b) with c in [0, b[ like the mathematical definition
/// </summary>
public static int MathMod(int a, int b)
{
int c = ((a % b) + b) % b;
return c;
}
public static IEnumerable<T> ShiftRight<T>(IList<T> values, int shift)
{
for (int index = 0; index < values.Count; index++)
{
yield return values[MathMod(index - shift, values.Count)];
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
[TestMethod]
public void TestMethod1()
{
var res = ShiftRight(new [] { 1, 2, 3, 4, 5, 6 }, 2).ToArray();
Assert.IsTrue(res.SequenceEqual(new[] { 5, 6, 1, 2, 3, 4 }));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5047 次 |
| 最近记录: |