square puzzle solution

前端 未结 5 949
一生所求
一生所求 2021-01-01 02:51

Question: given an integer number n, print the numbers from 1 up to n2 like this:

n = 4

result is:

01 02 03 04
12 13 14 05
11 16 1         


        
5条回答
  •  囚心锁ツ
    2021-01-01 03:39

    Another way to do it, this time in C#:

    int number = 9;
    var position = new { x = -1, y = 0 };
    var directions = new [] { 
        new { x = 1, y = 0 },
        new { x = 0, y = 1 },
        new { x = -1, y = 0 },
        new { x = 0, y = -1 }
    };
    
    var sequence = (
        from n in Enumerable.Range(1, number)
        from o in Enumerable.Repeat(n, n != number ? 2 : 1)
        select o
    ).Reverse().ToList();
    
    var result = new int[number,number];
    
    for (int i = 0, current = 1; i < sequence.Count; i++)
    {
        var direction = directions[i % directions.Length];      
    
        for (int j = 0; j < sequence[i]; j++, current++)
        {
            position = new {
                x = position.x + direction.x,
                y = position.y + direction.y
            };
    
            result[position.y, position.x] = current;
        }
    }
    

提交回复
热议问题