题
在最近的一次采访中,人们提出了一个特殊的问题
a[]= { 1,2,3,4,5,6,7,8,9,10}
当给定具有指定起始索引的数组时,我必须迭代它直到我遍历 所有元素。
我的意思是假设起始指数是“5”。我必须从 6,7,8,9,10,5,4,3,2,1
开始。请仔细查看序列,如何创建Reset(),
当前,等等,等等...?
但是面试官按照他的要求执行了序列。他没有显示代码。
我们真的能为这种奇怪的要求制定逻辑吗?
解决方案
只需使用两个循环。
IEnumerable<int> ForwardsBackwards(int[] a, int start) {
for(int i=start; i<a.Length; i++)
yield return a[i];
for(int i=start-1; i>=0; i--)
yield return a[i];
}
编辑: 使用linq更好:
IEnumerable<int> ForwardBackward(int[] a, int start) {
return a.Skip(start).Concat(a.Take(start).Reverse());
}
其他提示
易于维护(?):
int[] a= {1,2,3,4,5,6,7,8,9,10};
int StartIndex=5;
for (int iCount = StartIndex; iCount < a.Count() + StartIndex; iCount++)
{
Debug.WriteLine(a[(iCount + a.Count()) % a.Count()]);
}
输出是:
6 7 8 9 10 1 2 3 4 5
编辑:刚发现您的序列,当您达到上限时它会反转。如果那是指定的问题那就太讨厌了。
这是一个旧线程,但我需要相同的算法,并找到了一个很好的解决方案。溶液
- 可以从数组 的任何元素开始
- 可以开始迭代到任何方向
- 将从行动方向的NEXT开始传递所有元素
- 当达到border元素时,将重叠到第一个/最后一个 醇>
所有魔法都与 for 循环运算符一致,其他代码是为了方便预览。
// Example program
#include <iostream>
#include <string>
int a[] = {0,1,2,3,4,5};
int Count = sizeof(a)/sizeof(int);
void LoopFromMidWithDirection ( int curIdx , int motion )
{
std::cout << "\nNextFrom=" << curIdx << " motion =" << motion << "\n";
curIdx +=motion;
for (int i = curIdx; (i - curIdx) * motion < Count ; i += motion)
std::cout << a[(i + Count) % Count] << " ";
std::cout << "\n";
}
int main()
{
LoopFromMidWithDirection(4, +1);
LoopFromMidWithDirection(6, +1);
LoopFromMidWithDirection(0, -1);
}
输出
NextFrom=4 motion =1
5 0 1 2 3 4
NextFrom=6 motion =1
1 2 3 4 5 0
NextFrom=0 motion =-1
5 4 3 2 1 0
解决方案的灵感来自@Neil Kimber
是的,您必须实施 IEnumerator 自定义类的接口。将逻辑写入MoveNext方法,该方法检测数组的结束,然后从数组的开头开始,记住中间的起点。
遵循Microsoft的这些代码示例模板。
(DEFINE (traverse length start call)
(DEFINE (flow index motion)
(cond ((> index length)
(flow (- start 1) -1))
((> index -1)
((call index) (flow (+ index motion) motion)))))
(flow start +1))
(traverse 9 5 job)
我喜欢这个问题的9到5个方面。我想知道他们是否暗指某事?假设 job
打印出数组索引,这将产生678954321。
在C中,我很想使用for循环(不像我在编辑之前那样使用while循环);
int a[]= { 1,2,3,4,5,6,7,8,9,10};
int length = 10;
int start = 5;
int motion = 1; //increment
for( int index = start; index >= 0; index += motion ) {
if(index > (length-1)) {
motion = -1; //decrement
index = start -1;
else {
printf("%d", a[index]);
}
}
只有在打印零索引后才能完成此过程。您没有遍历阵列的唯一时间是超出它。当发生这种情况时,返回起始索引(-1)并反转动作。
不隶属于 StackOverflow