-
Notifications
You must be signed in to change notification settings - Fork 0
/
IComparer.dib
128 lines (99 loc) · 2.28 KB
/
IComparer.dib
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!markdown
# IComparer
#!markdown
### Plain Class
#!csharp
public static void PrintList<T>(List<T> data)
{
Console.WriteLine("----->");
foreach (var item in data)
{
Console.WriteLine(item);
}
Console.WriteLine("<-----");
}
#!csharp
public class ComplexNumber: IComparable<ComplexNumber>
{
public int Imaginary { get; set; }
public int Real { get; set; }
public ComplexNumber(int real, int imaginary)
{
Imaginary = imaginary;
Real = real;
}
public override string ToString()
{
return $"{Real} + {Imaginary}i";
}
public int CompareTo(ComplexNumber other)
{
int result = Real.CompareTo(other.Real);
if (result != 0)
{
return result;
}
result = Imaginary.CompareTo(other.Imaginary);
return result;
}
}
#!markdown
### IComparer implementation
#!csharp
public class CompareOnlyReal : IComparer<ComplexNumber>
{
public int Compare(ComplexNumber x, ComplexNumber y)
{
return x.Real.CompareTo(y.Real);
}
}
public class CompareOnlyImaginary : IComparer<ComplexNumber>
{
public int Compare(ComplexNumber x, ComplexNumber y)
{
return x.Imaginary.CompareTo(y.Imaginary);
}
}
public class CompareWithOrder : IComparer<ComplexNumber>
{
public bool Descending { get; set; }
public CompareWithOrder(bool descending) { Descending = descending; }
public int Compare(ComplexNumber x, ComplexNumber y)
{
int result = x.CompareTo(y);
return Descending ? -result : result;
}
}
#!csharp
display("");
List<ComplexNumber> numbers = new List<ComplexNumber>()
{
new ComplexNumber(0, 1),
new ComplexNumber(0, 4),
new ComplexNumber(1, 0),
new ComplexNumber(1, 2),
new ComplexNumber(0, 2),
new ComplexNumber(-1, 0)
};
Console.WriteLine("Original");
PrintList(numbers);
#!csharp
numbers.Sort(new CompareOnlyReal());
Console.WriteLine("Only real comparison");
PrintList(numbers);
#!csharp
numbers.Sort(new CompareOnlyImaginary());
Console.WriteLine("Only imaginary comparison");
PrintList(numbers);
#!csharp
numbers.Sort(new CompareWithOrder(true));
Console.WriteLine("Descending");
PrintList(numbers);
#!csharp
numbers.Sort(new CompareWithOrder(false));
Console.WriteLine("Ascending");
PrintList(numbers);
#!csharp
numbers.Sort();
Console.WriteLine("Normal sort");
PrintList(numbers);