fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public class Test
  6. {
  7. private static IEnumerable<T> Swap<T>(IEnumerable<T> source, int smallerIndex, int greaterIndex) {
  8. using (IEnumerator<T> e = source.GetEnumerator()) {
  9. IList<T> saved = new List<T>(greaterIndex-smallerIndex+1);
  10. int index = 0;
  11. while (e.MoveNext()) {
  12. // If we're outside the swapped indexes, yield return the current element
  13. if (index < smallerIndex || index > greaterIndex) {
  14. index++;
  15. yield return e.Current;
  16. } else if (index == smallerIndex) {
  17. var atSmaller = e.Current;
  18. // Save all elements starting with the current one into a list;
  19. // Continue until you find the last index, or exhaust the sequence.
  20. while (index != greaterIndex && e.MoveNext()) {
  21. saved.Add(e.Current);
  22. index++;
  23. }
  24. // Make sure we're here because we got to the greaterIndex,
  25. // not because we've exhausted the sequence
  26. if (index == greaterIndex) {
  27. // If we are OK, return the element at greaterIndex
  28. yield return e.Current;
  29. }
  30. // Enumerate the saved items
  31. for (int i = 0 ; i < saved.Count-1 ; i++) {
  32. yield return saved[i];
  33. }
  34. // Finally, return the item at the smallerIndex
  35. yield return atSmaller;
  36. index++;
  37. }
  38. }
  39. }
  40. }
  41. public static void Main()
  42. {
  43. var data = new[] {0,1,2,3,4,5,6};
  44. foreach (var x in Swap(data, 2, 5)) {
  45. Console.WriteLine(x);
  46. }
  47.  
  48. }
  49. }
Success #stdin #stdout 0.03s 33984KB
stdin
Standard input is empty
stdout
0
1
5
3
4
2
6