0

I need a algorithm which will pop the array element from the first index and push the next element (from the original array at last index) until the matching set of elements found.

Like below:

Original array : {10,20,30,40,50,60,70,80,90,100,110,120}

1st iteration : 10,20,30,40
2nd iteration : 20,30,40,50
3rd iteration : 30,40,50,60
4th iteration : 40,50,60,70 .... and so on until the matching criteria set found.

Logic should iterate until the required set of array element found.(based on some calculations on elements)

3
  • This seems like quite a trivial problem, what code have you already tried? Commented Feb 7, 2017 at 7:20
  • 2
    Why dont you simply use a counter that increments by 1 till array.Length - 5 Commented Feb 7, 2017 at 7:22
  • While you can modify the array, if you're just looking for a subset of 5 elements, there's no need to. Iterate through it using begin/end indexes 5 elements apart and/or leverage ArraySegment to do easy calculations on the set of 5. Commented Feb 7, 2017 at 7:42

1 Answer 1

4

Your question is vague one; if you want to shift the starting point:

   int array = new[] {10,20,30,40,50};

   for (int shift = 0; shift < array.Length; ++shift) {
     for (int i = shift; i < array.Length; ++i) {
       int value = array[i];

       Console.Write(value);
       Console.Write(", ");
     }

     Console.WriteLine();  
   }

Outcome:

   10, 20, 30, 40, 50, 
   20, 30, 40, 50,
   30, 40, 50,
   40, 50,
   50, 

If you want to rotate the array I suggest modulo arithmetics:

   for (int shift = 0; shift < array.Length; ++shift) {
     for (int index = 0; index < array.Length; ++index) {
       int i = (shift + index) % array.Length;  

       int value = array[i];

       Console.Write(value);
       Console.Write(", ");
     } 

     Console.WriteLine();   
   }

Outcome:

   10, 20, 30, 40, 50, 
   20, 30, 40, 50, 10, 
   30, 40, 50, 10, 20,
   40, 50, 10, 20, 30,
   50, 10, 20, 30, 40, 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.