在C#中,如何按指定的位数向右旋转列表? [英] In C#, how do I rotate a list to the right by the specified number of places?
本文介绍了在C#中,如何按指定的位数向右旋转列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我特别给出了这行代码:
I'm given this line of code in particular:
public void Test8(List<int> items, int places)
这个问题的任务是提出解决方案,我可以通过指定的位数向右旋转List。 List旋转可以看作是圆形,这意味着末尾的元素会回绕到开头,反之亦然。
我该怎么做正确的方法?是否有多种方法可以手动执行此操作而不使用任何类型的花式代码?
示例:
The tasks for this problem is to come up with solution where I am able to rotate the List to the right by the specified number of places. A List rotation can be seen as circular, which means the elements that fall of the end would wrap around to the beginning, and vice versa.
How can I do this the correct way? Is there multiple ways to do this manually without using any sort fancy code?
Example:
Initial Array or List: 20, 30, 40, 50,60, 70
Rotated to the right by 3 places: 50, 60, 70, 20, 30, 40.
我尝试过:
What I have tried:
public void Test8(List<int> items, int places)
{
int rotate = places;
int[] results = new int[items.Count];
for (int i = 0; i < items.Count; i++)
{
results[i] = items[(i + rotate) % items.Count];
}
}
推荐答案
试试这个:
Try this:
public void Test8(List<int> items, int places)
{
int nItem;
for (int i = 0; i < places; i++)
{
nItem = items[items.Count - 1]; // get the last item of the list
items.RemoveItem(items.Count - 1); // remove this item from the end ...
items.InsertItem(0, nItem); // ... and insert this (last) item in front of the list
}
}
你基本上有2种技巧
- 旋转并复制到新列表
- 旋转到位
旋转副本是解决方案1的技巧。
要计算元素的新位置,你有应用公式:
NewPosition =(OldPosition + Rotation)%SizeOfList
轮换到位
仅轮换1和-1是实用的。您只需根据需要重复多次。
- 伪代码
You have basically 2 techniques
- Rotation with copy to a new list
- Rotation in place
Rotation with copy is the technique of solution 1.
To calc to new positionof an element, you have to apply the formula:
NewPosition= (OldPosition+ Rotation) % SizeOfList
Rotation in place
Only rotation of 1 and -1 are practical. You just have to repeat as many times as needed.
- pseudo code
if (rotation== -1)
{
tmp= list[0]
for scan= 1; scan < list.count; scan++)
{
list[scan-1]= list[scan];
}
list[list.count-1]= tmp;
}
else
{
tmp= list[list.count-1]
for scan= list.count-1; scan >=0; scan--)
{
list[scan]= list[scan-1];
}
list[0]= tmp;
}
解决方案1的稍微高效的版本:
A slightly more efficient version of Solution 1:
public void Test8(List<int> items, int places)
{
// Handle cases where the number of places is greater than or equal to the number of items:
places %= items.Count;
if (places == 0) return;
int[] range = new int[places];
items.CopyTo(items.Count - places, range, 0, places);
items.RemoveRange(items.Count - places, places);
items.InsertRange(0, range);
}
这篇关于在C#中,如何按指定的位数向右旋转列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文