In a recent interview one peculiar question has been asked
a[]= { 1,2,3,4,5,6,7,8,9,10}
When an array is given with specified starting index i have to iterate it till i traverse all elements.
I mean suppose the starting index is "5" i have to start from 6,7,8,9,10,5,4,3,2,1
.Please carefully look at the sequence ,how can one create Reset(),
Current,blah,blah...?.
But the interviewer executed the sequence as he asked.He did not show the code.
Can we really develop a logic for such a strange requirement?
Just use two loops.
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];
}
Edit: Even better with linq:
IEnumerable<int> ForwardBackward(int[] a, int start) {
return a.Skip(start).Concat(a.Take(start).Reverse());
}
Easier to maintain(?):
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()]);
}
Output is:
6 7 8 9 10 1 2 3 4 5
Edit: just spotted your sequence, it reverses when you reach the upper limit. That's nasty if that was the specified question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With