遇到一個挺經典的題,從0開始以1遞增,給定一個頂點top,求輸出1~top,然後top-1 到1,一直反覆下去...

要求:
1、從0開始以1遞增,給定一個頂點top,求輸出1~top,然後top-1 到1,一直反覆下去...
2、只能使用一個表達式

難度:※※※
看似簡單,實則費腦...

int top = 7;   // top可以是任一值,需要高兼容性
for (int i = 0; i < 1000; i++)
{
    // 只能使用1個表達式、儘可能的簡短
    // 輸出:1 2 3 4 5 6 7 6 5 4 3 2 1 2 3 ...

}

當然,大家可以嘗試去做一下~~

在此,感謝羣裏的每一位討論,獻上他們的答案:

using static System.Linq.Enumerable;
using Range = System.Range;

int top = 7;
for (int i = 0; i < 20; i++)   // 爲了更可觀的輸出,這裏將 1000 調整 20,不影響
{
    // 南京-開發-   得出:76543212345676...
    Console.WriteLine((Math.Abs(i % 12) - 6) + 1);
    // 調整過來:
    Console.WriteLine(Math.Abs(Math.Abs((i % 12) - 6) - 6) + 1);
    // 簡單來講 思路是123456765432 看成一個整體來就行了,提高兼容性後:
    Console.WriteLine(Math.Abs(Math.Abs((i % ((top * 2) - 2)) - (top - 1)) - (top - 1)) + 1);

    // 日後再說 第一版,缺點很明顯,擴展性不行
    Console.WriteLine(8 - (((i / 6) % 2) != 0 ? top++ : top--));
    // 第二版,不使用絕對值的方式,是另一種優雅
    Console.WriteLine((((i / (top - 1)) % 2) != 0 ? top - ((i) % (top - 1)) : ((i) % (top - 1)) + 1));

    // 我的 wosperry
    Console.WriteLine(top - Math.Abs(i % (top * 2 - 2) - top + 1));
    // 原理:
    //1.abs是一個V
    //2.所以-abs是個^
    //3.0對應1      6對應7,通過座標變換  y-7 = -abs(x-6) 移動過去
    //4.因爲是到2就結束,掰手指算出來一共12位,於是 y = -abs(x%12-6) +7

    // 平淡最真,和我的有異曲同工之妙
    Console.WriteLine(top - Math.Abs(i % (top * 2 - 2) - top + 1) % top);

    // 一夜夢驚人
    // Console.WriteLine((i / 7) % 2 == 0 ? i % 7 + 1 : 6 - i % 7);
    Console.WriteLine((i / top) % 2 == 0 ? i % top + 1 : top - 1 - i % top);

    // 左邊
    Console.WriteLine(Range(1, 6).Concat(Range(2, 6).Reverse()).ElementAt(i % 12) + " ");
}

當然,答案不止一種,大家還有其他答案的話,可以踊躍留言~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章