東方算程譚

Oriental Code Talk ── επιστημηが与太をこく、弾幕とは無縁のシロモノ。

目次

Blog 利用状況

ニュース

著作とお薦めの品々は

著作とお薦めの品々は
東方熱帯林へ。

あわせて読みたい

わんくま

  1. 東京勉強会#2
    C++/CLI カクテル・レシピ
  2. 東京勉強会#3
    template vs. generics
  3. 大阪勉強会#6
    C++むかしばなし
  4. 東京勉強会#7
    C++むかしばなし
  5. 東京勉強会#8
    STL/CLRによるGeneric Programming
  6. TechEd 2007 @YOKOHAMA
    C++・C++/CLI・C# 適材適所
  7. 東京勉強会#14
    Making of BOF
  8. 東京勉強会#15
    状態遷移
  9. 名古屋勉強会#2
    WinUnit - お気楽お手軽UnitTest

CodeZine

  1. Cで実現する「ぷちオブジェクト指向」
  2. CUnitによるテスト駆動開発
  3. SQLiteで組み込みDB体験(2007年版)
  4. C++/CLIによるCライブラリの.NET化
  5. C# 1.1からC# 3.0まで~言語仕様の進化
  6. BoostでC++0xのライブラリ「TR1」を先取りしよう (1)
  7. BoostでC++0xのライブラリ「TR1」を先取りしよう (2)
  8. BoostでC++0xのライブラリ「TR1」を先取りしよう (3)
  9. BoostでC++0xのライブラリ「TR1」を先取りしよう (4)
  10. BoostでC++0xのライブラリ「TR1」を先取りしよう (5)
  11. C/C++に対応した、もうひとつのUnitTestFramework ─ WinUnit
  12. SQLiteで"おこづかいちょう"
  13. STL/CLRツアーガイド
  14. マージ・ソート : 巨大データのソート法
  15. ヒープソートのアルゴリズム
  16. C++0xの新機能「ラムダ式」を次期Visual Studioでいち早く試す
  17. .NETでマンデルブロ集合を描く
  18. .NETでマンデルブロ集合を描く(後日談)
  19. C++/CLI : とある文字列の相互変換(コンバージョン)
  20. インテルTBBによる選択ソートの高速化
  21. インテルTBB3.0 によるパイプライン処理
  22. Visual C++ 2010に追加されたSTLアルゴリズム
  23. Visual C++ 2010に追加されたSTLコンテナ「forward_list」
  24. shared_ptrによるObserverパターンの実装
  25. .NETでマンデルブロ集合を描く(番外編) ── OpenCLで超並列コンピューティング
  26. StateパターンでCSVを読む
  27. 状態遷移表からStateパターンを自動生成する
  28. 「ソートも、サーチも、あるんだよ」~標準C++ライブラリにみるアルゴリズムの面白さ
  29. インテルTBBの同期メカニズム
  30. なぜsetを使っちゃいけないの?
  31. WPFアプリケーションで腕試し ~C++でもWPFアプリを
  32. C++11 : スレッド・ライブラリひとめぐり
  33. Google製のC++ Unit Test Framework「Google Test」を使ってみる
  34. メールでデータベースを更新するココロミ
  35. Visitorパターンで遊んでみたよ
  36. Collection 2題:「WPFにバインドできる辞書」と「重複を許す検索set」
  37. Visual C++ 2012:stateless-lambdaとSQLiteのぷち拡張
  38. 「Visual C++ Compiler November 2012 CTP」で追加された6つの新機能

@IT

  1. Vista時代のVisual C++の流儀(前編)Vista到来。既存C/C++資産の.NET化を始めよう!
  2. Vista時代のVisual C++の流儀(中編)MFCから.NETへの実践的移行計画
  3. Vista時代のVisual C++の流儀(後編) STL/CLRによるDocument/Viewアーキテクチャ
  4. C++開発者のための単体テスト入門 第1回 C++開発者の皆さん。テスト、ちゃんとしていますか?
  5. C++開発者のための単体テスト入門 第2回 C++アプリケーションの効率的なテスト手法(CppUnit編)
  6. C++開発者のための単体テスト入門 第3回 C++アプリケーションの効率的なテスト手法(NUnit編)

AWARDS


Microsoft MVP
for Visual Developer - Visual C++


Wankuma MVP
for いぢわる C++


Nyantora MVP
for こくまろ中国茶

Xbox

Links

記事カテゴリ

書庫

日記カテゴリ

複数のキーでソート

ネタ元 → 複数キーによるソートについて

まず年齢の昇順に並べ、同年齢なら名前の昇順で... なんてケースですなたぶん。
よくあるケースです。

だいぶ手慣れてきたC#でやってみた。

using System;

namespace MultiKey_cs {

  /*
   * ぶっちゃけキモはこいつだけ。
   */
  class MultiKeyComp<T> {
    Comparison<T>[] comps;

    public MultiKeyComp(params Comparison<T>[] c) {
      comps = c;
    }

    private int compare(T x, T y) {
      int result = 0;
      foreach ( Comparison<T> c in comps ) {
        if ( (result = c(x, y)) != 0 ) break;
      }
      return result;
    }

    // Comparison<T> への暗黙の変換
    public static implicit operator Comparison<T>(MultiKeyComp<T> arg) {
      return arg.compare;
    }
  }

  public struct データ {
    public string key1;
    public string key2;
    public string key3;
  }

  public class Program {
    public static void Main() {
      int N  = 10;
      データ[] data = new データ[N];
      Random r = new Random();
      for ( int i = 0; i < N; ++i ) {
        データ datum = new データ();
        datum.key1 = r.Next(10).ToString();
        datum.key2 = r.Next(10).ToString();
        datum.key3 = r.Next(10).ToString();
        data[i] = datum;
      }

      Console.WriteLine("ソート前");
      Array.ForEach(data,
        x => Console.WriteLine("{0} {1} {2}", x.key1, x.key2, x.key3));
      Console.WriteLine();

      Comparison<データ> c =
        new MultiKeyComp<データ>(
          (x,y) => x.key1.CompareTo(y.key1), // key1:昇順
          (x,y) => 0,                        // key2:don't care
          (x,y) => y.key3.CompareTo(x.key3)  // key3:降順
        );
      Array.Sort(data, c);

      Console.WriteLine("ソート後");
      Array.ForEach(data,
        x => Console.WriteLine("{0} {1} {2}", x.key1, x.key2, x.key3));
      Console.WriteLine();
    }
  }
}

lambdaらぶ♪
未だLINQ脳が未発達なもので ^^;

投稿日時 : 2008年8月23日 11:02

コメントを追加

# re: 複数のキーでソート 2008/08/23 11:28 なちゃ

比較クラスのインスタンスを作る前提なら、IComparer系を実装する方が素直じゃないかな~
必要ならComparizonはプロパティとかで取れるようにすればいいですし。
まあ暗黙変換でもいいんですけど。

# re: 複数のキーでソート 2008/08/23 12:03 επιστημη

いやま思いついたままのやっつけcodingですんで ^^;

# re: 複数のキーでソート 2008/08/23 12:16 R・田中一郎

ICompare もそうですけど、複数キーになったとしても、結局のところ比較ロジックの中でゴニョゴニョするところがキモってだけの話なんですよね。

わかっちゃえば「なるほど~」となる訳ですけど、最初は戸惑っちゃうんでしょうね。

# re: 複数のキーでソート 2008/08/23 12:23 επιστημη

↓ですよねー

class MultiKeyComp<T> : System.Collections.Generic.IComparer<T> {
 private Comparison<T>[] comps;
 public MultiKeyComp(params Comparison<T>[] c) {
  comps = c;
 }
 public int Compare(T x, T y) {
  int result = 0;
  foreach ( Comparison<T> c in comps ) {
   if ( (result = c(x, y)) != 0 ) break;
  }
  return result;
 }
}
...
 Array.Sort(data,
  new MultiKeyComp<データ>(
   (x,y) => x.key1.CompareTo(y.key1),
   (x,y) => 0,
   (x,y) => y.key3.CompareTo(x.key3))
 );

# re: 複数のキーでソート 2008/08/23 15:13 NyaRuRu

題意を読み間違えてるかもしれませんが,こんな感じですか?

static IEnumerable<T> Repeat<T>(T value)
{
  while(true) yield return value;
}

static void Main(string[] args)
{
  const int N = 100;
  var data = Repeat(new Random())
    .Select(r => new
    {
      key1 = r.Next(10).ToString(),
      key2 = r.Next(10).ToString(),
      key3 = r.Next(10).ToString(),
    })
    .Take(N)
    .ToArray();

  var sorted = data.OrderBy(d => d.key1).ThenByDescending(d => d.key3);

  foreach (var x in sorted)
  {
    Console.WriteLine("{0} {1} {2}", x.key1, x.key2, x.key3);
  }
}

# re: 複数のキーでソート 2008/08/23 23:12 επιστημη

ほほーなるほど。おもろいなー。
ときにふと気になったんですけど、
LINQ内で行われる(であろう)ソートって"安定"なんでしょか?
# 高速/不安定 or 低速/安定 を選べるとか。

# re: 複数のキーでソート 2008/08/23 23:29 NyaRuRu

>LINQ内で行われる(であろう)ソートって"安定"なんでしょか?

LINQ の(緩い)セマンティクスでは未定義です.
より正確には,LINQ が相手にするデータソースの中に,そもそも stable-sort を定義できないものが存在します.(例えば SQL Server とか)
OrderBy は (緩い意味で) 並べ替えることのみを保証します.

ただし,LINQ to Object の Microsoft 実装において,OrderBy が stable-sort として実装されていることは明言されています.
http://blogs.wankuma.com/episteme/archive/2008/02/15/123281.aspx#123391

# re: 複数のキーでソート 2008/08/24 10:01 επιστημη

うあぁぁぁ、半年前に引き金引いてた orz

# re: 複数のキーでソート 2008/10/15 17:02 ぼぼ

C#で複数キーのソートをしたく、辿り着きました。C#の基礎知識も無い初心者ですが、ご紹介されていましたソースで何とか実行させたいのですが、テスト以前に記述が分からずコンパイルも通っていません・・。

どこが悪いのかご教授いただけないでしょうか?

for (int index = 0; index < _list.MaxCount; index++) {
Data _job = (Data)list.get[index];
sortJobList datum = new sortJobList();
datum.key1 = _job.id;
datum.key2 = _job.name;
datum.key3 = _job.Text;
datum.job = _job;
}
//上記記述ミスがあるかもしれませんが、実際のソースは正常に格納されてます。このデータをkey1~key3を全て昇順で行いたいのですが・・。
Comparison<sortJobList> c = new MultiKeyComp<sortJobList>(
x.key1.CompareTo(y.key1),
x.key2.CompareTo(y.key2),
x.key3.CompareTo(y.key3));
Array.Sort(data, c);

お分かりになりましたら、よろしくお願いします。

# re: 複数のキーでソート 2008/10/16 7:41 επιστημη

MultiKeyComp<T> のコンストラクタには
Comparison<T> を(カンマ区切りで)与えます。

# I read this piece of writing fully concerning the resemblance of most up-to-date and previous technologies, it's awesome article. 2021/09/03 16:59 I read this piece of writing fully concerning the

I read this piece of writing fully concerning the resemblance of most up-to-date and previous technologies, it's awesome article.

# Hi, after reading this amazing article i am too delighted to share my experience here with mates. 2021/09/05 5:30 Hi, after reading this amazing article i am too de

Hi, after reading this amazing article i am too delighted to share my
experience here with mates.

# Hi, after reading this amazing article i am too delighted to share my experience here with mates. 2021/09/05 5:31 Hi, after reading this amazing article i am too de

Hi, after reading this amazing article i am too delighted to share my
experience here with mates.

# Hi, after reading this amazing article i am too delighted to share my experience here with mates. 2021/09/05 5:32 Hi, after reading this amazing article i am too de

Hi, after reading this amazing article i am too delighted to share my
experience here with mates.

# Hi, after reading this amazing article i am too delighted to share my experience here with mates. 2021/09/05 5:33 Hi, after reading this amazing article i am too de

Hi, after reading this amazing article i am too delighted to share my
experience here with mates.

# Hello! I know this is kind of off topic but I was wondering which blog platform are you using for this website? I'm getting tired of Wordpress because I've had problems with hackers and I'm looking at alternatives for another platform. I would be fanta 2021/09/11 19:44 Hello! I know this is kind of off topic but I was

Hello! I know this is kind of off topic but I was wondering which
blog platform are you using for this website? I'm getting tired of Wordpress because I've had problems with hackers and I'm looking at alternatives for
another platform. I would be fantastic if you could point me in the direction of a good platform.
quest bars http://bitly.com/3C2tkMR quest bars

# Hmm is anyone else experiencing problems with the pictures on this blog loading? I'm trying to figure out if its a problem on my end or if it's the blog. Any responses would be greatly appreciated. 2021/10/25 21:19 Hmm is anyone else experiencing problems with the

Hmm is anyone else experiencing problems with the pictures on this blog loading?

I'm trying to figure out if its a problem on my end or
if it's the blog. Any responses would be greatly appreciated.

# Hello colleagues, good piece of writing and pleasant urging commented at this place, I am genuinely enjoying by these. 2021/11/12 12:30 Hello colleagues, good piece of writing and pleasa

Hello colleagues, good piece of writing and pleasant urging commented at
this place, I am genuinely enjoying by these.

# Hello colleagues, good piece of writing and pleasant urging commented at this place, I am genuinely enjoying by these. 2021/11/12 12:30 Hello colleagues, good piece of writing and pleasa

Hello colleagues, good piece of writing and pleasant urging commented at
this place, I am genuinely enjoying by these.

# Hello colleagues, good piece of writing and pleasant urging commented at this place, I am genuinely enjoying by these. 2021/11/12 12:31 Hello colleagues, good piece of writing and pleasa

Hello colleagues, good piece of writing and pleasant urging commented at
this place, I am genuinely enjoying by these.

# Hello colleagues, good piece of writing and pleasant urging commented at this place, I am genuinely enjoying by these. 2021/11/12 12:32 Hello colleagues, good piece of writing and pleasa

Hello colleagues, good piece of writing and pleasant urging commented at
this place, I am genuinely enjoying by these.

# price of ivermectin http://stromectolabc.com/
stromectol 3mg cost 2022/02/08 9:23 Busjdhj

price of ivermectin http://stromectolabc.com/
stromectol 3mg cost

# stromectol 3 mg tablet http://stromectolabc.com/
stromectol uk buy 2022/02/08 16:26 Busjdhj

stromectol 3 mg tablet http://stromectolabc.com/
stromectol uk buy

# purchase doxycycline online https://doxycyline1st.com/
doxycycline 100mg tablets 2022/02/26 19:49 Doxycycline

purchase doxycycline online https://doxycyline1st.com/
doxycycline 100mg tablets

# over the counter erectile dysfunction pills https://erectiledysfunctionpills.shop/ 2022/10/14 22:40 Erectile

over the counter erectile dysfunction pills https://erectiledysfunctionpills.shop/

# prednisone 10mg online https://prednisone20mg.icu/ 2022/10/15 13:13 Prednisone

prednisone 10mg online https://prednisone20mg.icu/

# connect singles https://datingtopreview.com/
worldwide internet dating 2022/10/17 20:30 Dating

connect singles https://datingtopreview.com/
worldwide internet dating

# prednisone 10mg buy online https://prednisone20mg.site/
purchase prednisone 2022/11/15 17:49 Prednisone

prednisone 10mg buy online https://prednisone20mg.site/
purchase prednisone

# over the counter prednisone cream https://prednisonepills.site/
buy prednisone online no script 2022/11/28 23:43 Prednisone

over the counter prednisone cream https://prednisonepills.site/
buy prednisone online no script

# good dating websites https://datingonlinehot.com/
amature dating co 2022/12/09 19:12 Dating

good dating websites https://datingonlinehot.com/
amature dating co

# best ed pills online https://edpills.science/
ed drug prices 2023/01/07 13:43 EdPills

best ed pills online https://edpills.science/
ed drug prices

# Misoprostol 200 mg buy online - https://cytotecsale.pro/# 2023/04/28 23:24 Cytotec

Misoprostol 200 mg buy online - https://cytotecsale.pro/#

# ed pills https://edpillsotc.store/# - mens erection pills 2023/10/07 21:12 EdPills

ed pills https://edpillsotc.store/# - mens erection pills

# buy valtrex without prescription https://valtrex.auction/ how can i get valtrex 2023/10/24 17:39 Valtrex

buy valtrex without prescription https://valtrex.auction/ how can i get valtrex

# ï»¿farmacia online migliore https://farmaciait.pro/ farmaci senza ricetta elenco 2023/12/04 7:03 Farmacia

farmacia online migliore https://farmaciait.pro/ farmaci senza ricetta elenco

# eva elfie full videos https://evaelfie.site/ eva elfie videos
2024/03/07 4:37 EvaElfie

eva elfie full videos https://evaelfie.site/ eva elfie videos

# sweet bonanza nas&#305;l oynan&#305;r https://sweetbonanza.bid/ - sweet bonanza yasal site
2024/03/27 22:09 Bonanzaj

sweet bonanza nas&#305;l oynan&#305;r https://sweetbonanza.bid/ - sweet bonanza yasal site

# pin up bet: https://pinupgiris.fun/ pin-up giri&#351;
2024/03/28 7:26 GirisUp

pin up bet: https://pinupgiris.fun/ pin-up giri&#351;

タイトル
名前
URL
コメント