challenge データの整列

(x, y) の座標情報を以下の2種類の方法で整列する機能を実現してください。

  • (x, y) の辞書順(まず x で昇順に整列して、x が同じデータに対して y で昇順に整列する)
  • (0, 0) からの距離の昇順

データの表現方法はタプルなり構造体/オブジェクトなり各自で適当に選んで下さい。

Posted feedbacks - C#

こんなかんじでいいのかな?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Collections.Generic;
static class Program {
    static void Main(String[] args) {
        List<Pair> plist = new List<Pair>();
        Random rand = new Random();
        for(int i = 0; i < 10; i++) plist.Add(new Pair(rand.Next(5), rand.Next(5)));
        Console.WriteLine("----- 元データ");
        foreach(Pair p in plist) Console.WriteLine(p);
        
        Console.WriteLine("----- 辞書順でソート");
        plist.Sort(delegate(Pair p1, Pair p2) {
            return p1.x != p2.x ? p1.x.CompareTo(p2.x) : p1.y.CompareTo(p2.y);
        });
        foreach(Pair p in plist) Console.WriteLine(p);
        
        Console.WriteLine("----- 距離順でソート");
        plist.Sort(delegate(Pair p1, Pair p2) {
            return (p1.x * p1.x + p1.y * p1.y).CompareTo(p2.x * p2.x + p2.y * p2.y);
        });
        foreach(Pair p in plist) Console.WriteLine(p);
    }
}
class Pair {
    public readonly int x, y;
    public Pair(int x, int y) {
        this.x = x; this.y = y;
    }
    public override string ToString() {
        return "(" + x + ", " + y + ")";
    }
}

LINQ使って判定してます

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class MyPoint
{
    public int x { get; set; }
    public int y { get; set; }
    public int dist { get; set; }
    public override string ToString() { return "(" + x + "," + y + ")"; }
}
class Program
{
    static void Main(string[] args)
    {
        ArrayList list = new ArrayList();
        Random rand = new Random();
        int x = 0, y = 0;
        for (int i = 0; i <= 5; i++)
        {
            x = rand.Next(10);
            y = rand.Next(10);
            list.Add(new MyPoint { x = x, y = y, dist = x * x + y * y });
        }

        Console.WriteLine("----------元データ");
        foreach (var point in list)
        {
            Console.WriteLine(point);
        }

        Console.WriteLine("----------辞書順ソート");
        var query = from MyPoint point in list
                    orderby point.x ascending, point.y ascending
                    select point;
        foreach (var point in query)
        {
            Console.WriteLine( point );
        }

        Console.WriteLine("----------距離順ソート");
        query = from MyPoint point in list
                    orderby point.dist ascending
                    select point;
        foreach (var point in query)
        {
            Console.WriteLine(point);
        }

        Console.ReadLine();
    }
}

Index

Feed

Other

Link

Pathtraq

loading...