我不太清楚如何做到这一点。
伪代码:
array1 = {"a","b", "c", "d", "e","f", "g","h", "i","j"} //there might be more values.
take c
loop =>c+3 =f
f+3 =i
i+3 =b
b+3 =e
......
end loop
我需要将此array1
用作圈,并找到添加3(f,i,b,e等)的字母。
答案 0 :(得分:6)
使用mod(%
),然后index
可以是任何正值,它将包围:
int index;
array1[index % array1.Length]
答案 1 :(得分:1)
你需要写"找到添加3"自己的功能就像:
new_index = (current_index+3)%length_of_array
答案 2 :(得分:0)
正如其他答案所说,%
运算符是实现它的关键。这是实施。
private string[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
private IEnumerable<string> GetStringWrapped(int position)
{
int current = position - 1;
while (true)
{
yield return strings[current];
current += position;
current %= strings.Length;
}
}
将其用作
void SomeMethod()
{
var resultArray = GetStringWrapped(3).Take(5).ToArray();
//resultArray contains c,f,i,b,e
}
注意Take
很重要,否则你的方法永远不会结束,它会永远循环。
答案 3 :(得分:0)
我们可以使用%
运算符来计算数组中的循环索引,然后我们可以在类中抽象它
class CircularList<T> : List<T>
{
public new T this[int index]
{
get { return base[index%Count]; }
set { base[index%Count] = value; }
}
public T this[T item, int distance]
{
get
{
var index = IndexOf(item);
return this[index + distance];
}
set
{
var index = IndexOf(item);
this[index + distance] = value;
}
}
}
用法:
var arr = new CircularList<string> { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
var b = arr[8 + 2];
var b2 = arr["i", 2];