Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array iteration starting from the middle

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?

like image 844
udana Avatar asked Dec 04 '22 14:12

udana


2 Answers

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());
}
like image 200
recursive Avatar answered Dec 19 '22 13:12

recursive


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.

like image 29
Neil Kimber Avatar answered Dec 19 '22 14:12

Neil Kimber