2013年3月6日水曜日

開発環境

『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487312-194-7)の 第14章(ジェネリックとコレクション)14.6(練習問題)練習14-4.を解いてみる。

その他参考書籍

練習14-4.

コード

using System;
using System.Collections.Generic;

abstract class Animal : IComparable<Animal>
{
    private int weight;
    private string name;
    public Animal(int weight, string name)
    {
        this.weight = weight;
        this.name = name;
    }
    abstract public void Speak();
    abstract public void Move();
    public override string ToString()
    {
        return name + ", " + weight;
    }
    public bool Equals(Animal other)
    {
        if (this.weight == other.weight)
        {
            return true;
        }
        return false;
    }
    public static AnimalComparer GetComparer()
    {
        return new Animal.AnimalComparer();
    }
    public int CompareTo(Animal other)
    {
        return this.weight.CompareTo(other.weight);
    }
    public int CompareTo(Animal rhs, Animal.AnimalComparer.ComparisonType which)
    {
        switch (which)
        {
            case AnimalComparer.ComparisonType.Weight:
                return this.weight.CompareTo(rhs.weight);
            case AnimalComparer.ComparisonType.Name:
                return this.name.CompareTo(rhs.name);
            default:
                return 0;
        }
    }
    public class AnimalComparer : IComparer<Animal>
    {
        public enum ComparisonType
        {
            Weight, Name,
        };
        private Animal.AnimalComparer.ComparisonType whichComparison;
        public bool Equals(Animal x, Animal y)
        {
            return this.Compare(x, y) == 0;
        }
        public int Compare(Animal x, Animal y)
        {
            return x.CompareTo(y, WhichComparison);
        }
        public Animal.AnimalComparer.ComparisonType WhichComparison
        {
            get { return whichComparison; }
            set { whichComparison = value; }
        }
    }
}
class Dog : Animal
{
    public Dog(int weight, string name) :
        base(weight, name) { }
    public override void Speak()
    {
        Console.WriteLine("ワンワン");
    }
    public override void Move()
    {
        Console.WriteLine("てくてく");
    }
}
class Cat : Animal
{
    public Cat(int weight, string name) :
        base(weight, name) { }
    public override void Speak()
    {
        Console.WriteLine("ニャーニャー");
    }
    public override void Move()
    {
        Console.WriteLine("するする");
    }
}
class Tester
{
    public void Run()
    {
        Cat tama = new Cat(5, "Tama");
        Cat sora = new Cat(15, "Sora");
        Dog frisky = new Dog(10, "Frisky");
        Dog laika = new Dog(20, "Laika");
        Animal[] animals = { tama, sora, frisky, laika };
        List<Animal> animalList = new List<Animal>();
        Animal.AnimalComparer c = Animal.GetComparer();
        foreach (Animal animal in animals)
        {
            animalList.Add(animal);
        }
        Console.WriteLine("重さでソート");
        c.WhichComparison = Animal.AnimalComparer.ComparisonType.Weight;
        animalList.Sort(c);
        foreach (Animal animal in animalList)
        {
            Console.WriteLine(animal);
        }
        Console.WriteLine("アルファベット順にソート");
        c.WhichComparison = Animal.AnimalComparer.ComparisonType.Name;
        animalList.Sort(c);
        foreach (Animal animal in animalList)
        {
            Console.WriteLine(animal);
        }
    }
    static void Main()
    {
        Tester t = new Tester();
        t.Run();
    }
}

入出力結果(Console Window)

重さでソート
Tama, 5
Frisky, 10
Sora, 15
Laika, 20
アルファベット順にソート
Frisky, 10
Laika, 20
Sora, 15
Tama, 5
続行するには何かキーを押してください . . .

ちなみにJavaScriptの場合。

コード(BBEdit)

var Animal = function (weight, name) {
    var weight = weight
        name = name;
    this.getWeight = function () {
        return weight;
    },
    this.getName = function (  ) {
        return name;
    };
},
    Cat = function (  ) {
        Animal.apply(this, arguments);
    },
    Dog = function (  ) {
        Animal.apply(this, arguments);
    },
    animals = [],
    animalStack = [],
    animalQueue = [],
    tama, sora, frisky, laika, i, max;
    Animal.prototype.speak = function () {
        $('#pre0').append( "抽象speak\n" );
    },
    Animal.prototype.move = function (  ) {
        $('#pre0').append( "抽象move\n" );
    },
    Animal.prototype.toString = function(  ) {
        return this.getName() +", " + this.getWeight();
    },
    Cat.prototype = new Animal(),
    Cat.prototype.speak = function (  ) {
        $('#pre0').append("ニャーニャー\n");
    },
    Cat.prototype.move = function (  ) {
        $('#pre0').append("するする\n");
    },
    Dog.prototype = new Animal(),
    Dog.prototype.speak = function (  ) {
        $('#pre0').append("ワンワン\n");
    },
    Dog.prototype.move = function (  ) {
        $('#pre0').append("てくてく\n");
    },
    tama = new Cat(5, "Tama"),
    sora = new Cat(15, "Sora"),
    frisky = new Dog(10, "Frisky"),
    laika = new Dog(20, "Laika"),
    animals = [tama, sora, frisky, laika];
$('#pre0').append("重さでソート\n");
animals.sort(function ( x, y ) {
    return x.getWeight() - y.getWeight();
});
for (i = 0, max = animals.length; i < max; i += 1) {
    $('#pre0').append(animals[i] + "\n");
}
$('#pre0').append("名前でソート\n")
animals.sort(function ( x,y ) {
    if( x.getName() < y.getName() ) {
        return -1;
    } else if(x.getName() > y.getName() ) {
        return 1;
    } else {
        return 0;
    }
});
for (i = 0, max = animals.length; i < max; i += 1) {
    $('#pre0').append(animals[i] + "\n");
}


pythonの場合。

コード(BBEdit)

sample.py

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

class Animal:
    def __init__(self, weight, name):
        self._weight = weight
        self._name = name
    def getWeight(self):
        return self._weight
    def getName(self):
        return self._name
    def speak(self):
        raise Exception("Animal speak")
    def move(self):
        raise Exception("Animal move")
    def __str__(self):
        return "{0}, {1}".format(self._name, self._weight)

class Cat(Animal):
    def speak(self):
        print("ニャーニャー")
    def move(self):
        print("するする")

class Dog(Animal):
    def speak(self):
        print("ワンワン")
    def move(self):
        print("てくてく")

tama = Cat(5, "Tama")
sora = Cat(15, "Sora")
frisky = Dog(10, "Frisky")
laika = Dog(20, "Laika")
animals = [tama, sora, frisky, laika]
print("重さでソート")
animals.sort(key=lambda x:x.getWeight())
for animal in animals:
    print(animal)
print("アルファベット順でソート")
animals.sort(key=lambda x:x.getName())
for animal in animals:
    print(animal)

入出力結果(Terminal)

$ ./sample.py
重さでソート
Tama, 5
Frisky, 10
Sora, 15
Laika, 20
アルファベット順でソート
Frisky, 10
Laika, 20
Sora, 15
Tama, 5
$

0 コメント:

コメントを投稿