Usually we need to traverse the array, usually we only traverse from beginning to end,
But sometimes, when we need to traverse the array from end to end and then from end to end, like a circle, the first way we think of is to judge whether the current traversal is forward or backward. In this way, the logic of the code will become complicated. I accidentally saw a way of writing. I personally feel very good and share it with everyone. (Here I use C # demo)
//创建一个数组
static int[] arrary = { 1, 2, 3, 4, 5, 6,7};
//数组遍历的第一项
static int curr = 2;
static void Main(string[] args)
{
while (true)
{
string s = Console.ReadLine();
if (s.Equals("Q"))
{
break;
}
Console.WriteLine("输出为:"+(arrary[++curr%arrary.Length]));
}
}
After the execution, we see the following result. The array begins to rotate from the position of subscript 3, eliminating the need to judge whether it is forward traversal or backward traversal.
Such algorithms not only work in arrays, but also in various environments that require rotation.