Rename REAMDE to README.md
[nit.git] / tests / bench_complex_sort.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2006-2008 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17
18 interface Elt
19 fun val1: Int is abstract
20 fun val2: Int do return val1
21 end
22
23 class A
24 super Elt
25 var a: Int
26 redef fun val1: Int do return _a
27
28 init(i: Int) do _a = i
29 redef fun to_s do return "Aa{a}"
30 end
31
32 class Elt2
33 super Elt
34 var b: Int
35 redef fun val1: Int do return _b/2
36 redef fun val2: Int do return _b
37 init initelt2(i: Int) do _b = i
38 end
39
40 class B
41 super Elt2
42 init(i: Int) do initelt2(i)
43 redef fun to_s do return "Bb{b}"
44 end
45
46 class C
47 super Elt
48 var c: Int
49 var d: Int
50 redef fun val1: Int do return _c end
51 redef fun val2: Int do return _d end
52
53 init init2(i: Int, j: Int) do
54 _c = i
55 _d = j
56 end
57 redef fun to_s do return "Cc{c}d{d}"
58 end
59
60 class D
61 super A
62 super Elt2
63 redef fun val1: Int do return _a end
64 redef fun val2: Int do return _b end
65
66 init init2(i: Int, j: Int) do
67 init(i)
68 initelt2(j)
69 end
70 redef fun to_s do return "Da{a}b{b}"
71 end
72
73 class E
74 super Elt2
75 redef fun val1: Int do return 5 end
76
77 init(i: Int) do initelt2(i)
78 redef fun to_s do return "Eb{b}"
79 end
80
81 class EltComparator
82 super Comparator
83 redef type COMPARED: Elt
84 redef fun compare(a, b)
85 do
86 if _is_val1 then
87 return a.val1 <=> b.val1
88 else
89 return a.val2 <=> b.val2
90 end
91 end
92
93 fun toggle
94 do
95 _is_val1 = not _is_val1
96 end
97
98 var is_val1: Bool = false
99
100 init do end
101 end
102
103 fun generator: Elt
104 do
105 var r = 5.rand
106 if r == 0 then
107 return new A(10.rand)
108 else if r == 1 then
109 return new B(10.rand)
110 else if r == 2 then
111 return new C.init2(10.rand, 10.rand)
112 else if r == 3 then
113 return new D.init2(10.rand, 10.rand)
114 else
115 return new E(10.rand)
116 end
117 end
118
119 srand_from(0)
120 var n = 20
121
122 if not args.is_empty then
123 n = args.first.to_i
124 end
125
126 var array = new Array[Elt].with_capacity(n)
127 for i in [0..n[ do
128 array.push(generator)
129 end
130
131 print array.join(", ")
132
133 var comparator = new EltComparator
134 for i in [0..n[ do
135 comparator.sort(array)
136 comparator.toggle
137 end
138
139 print array.join(", ")