巧妙的轮替数组中的值

平时我们时常需要遍历数组,一般我们只从头到尾遍历一遍,

但是有的时候,我们需要不断的从头到尾再从尾到头,像一个圆圈一样的遍历数组时,我们首先想到的办法是判断当前是正遍历,还是倒遍历。这样代码逻辑就会变得复杂,偶然间我看到一种写法,个人觉得非常不错,分享给大家。(这里我以C#演示)

        //创建一个数组
        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]));
            }
        }

执行之后,我们看到如下的结果,数组从下标3的位置开始轮替,免去了是正遍历,还是倒遍历的判断。


这样的算法不只是在数组中发挥作用,在各种需要轮替的环境中都能起到作用。

发布了25 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_37446649/article/details/80295132