*** SPOILER ALERT ***
I will soon post the explanation, hopefully, on my blog. It shouldn't be too hard if you followed the other exercise through. I still advise anyone who's interested to go through that exercise first, and get back here to solve it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyRotate
{
class Program
{
static int count_circles(int n, int k)
{
if (k <= 1) return 1;
if (n == k) return n;
return count_circles(k, k - (n % k));
}
static void swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
static int wrap(int i, int n)
{
return ((i % n) + n) % n;
}
static void rotate(int[] array, int k)
{
int n = array.Length;
k = wrap(k, n);
int count = count_circles(n, k);
int sub_n = n / count;
for (int i = 0; i < count; i++)
{
for (int j = sub_n - 2; j >= 0; j--)
{
int from = wrap((i + j * k), n);
int to = wrap((i + j * k + k), n);
Console.WriteLine("{0}-{1}", from, to);
swap(ref array[from], ref array[to]);
}
}
}
static void Main(string[] args)
{
Console.WriteLine("{0}", count_circles(11, 2));
Console.WriteLine("{0}", count_circles(10, 2));
Console.WriteLine("{0}", count_circles(10, 3));
Console.WriteLine("{0}", count_circles(10, 5));
int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
rotate(array, 2);
foreach (var i in array) Console.Write("{0} ", i);
Console.Write("\n");
}
}
}