...あれ? どぉやんだ? (東方算程譚) より。
名前と得点をメンバに持つExamの集合がある。
得点順にソートし、30点以上80点未満を列挙せよ。
これを System.Collections.Generic.List<Exam> でやろうとすると
どないになるんす?
というわけで、やってみた。(なぜかあっちのコメント投稿が通らなかったので...)
using System;
using System.Collections.Generic;
namespace test
{
class Exam : IComparable<Exam>
{
private string name;
private int score;
public Exam(string name_, int score_)
{
name = name_;
score = score_;
}
int IComparable<Exam>.CompareTo(Exam other)
{
if ( score < other.score )
return -1;
else if ( score > other.score )
return 1;
return 0;
}
public override string ToString()
{
return name + ":" + score;
}
}
class Program
{
public static void Main(string[] args)
{
List<Exam> exam = new List<Exam>();
exam.Add(new Exam("相川", 35));
exam.Add(new Exam("井上", 20));
exam.Add(new Exam("上村", 80));
exam.Add(new Exam("江口", 50));
exam.Add(new Exam("小田", 75));
exam.Sort();
int from = exam.BinarySearch(new Exam("", 30));
int to = exam.BinarySearch(new Exam("", 80));
from = from < 0 ? ~from : from;
to = to < 0 ? ~to : to;
while ( from != to )
Console.WriteLine(exam[from++]);
Console.ReadKey();
}
}
}
List<T>.BinarySearch(T) は要素が見つからなかった場合に、それよりも大きい要素のindex(がなければCount)のビット毎の補数 を返すらしいので、bit反転だけでらくらくいけちゃいますね。





コメントする