1 # This file is part of NIT (http://www.nitlanguage.org).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Example implemented from "The computer Language Benchmarks Game" - Chameneos-Redux
16 # http://benchmarksgame.alioth.debian.org/
18 # Complete description of the chameneos-redux :
19 # https://benchmarksgame.alioth.debian.org/u64q/chameneosredux-description.html#chameneosredux
20 module chameneosredux
is example
, no_warning
("missing-doc")
26 var place
: MeetingPlace
34 var p
= place
.meet
(id
, color
)
35 if p
== null then break
37 if p
.sameid
then samecount
+= 1
42 fun to_string
: String do return count
.to_s
+ " " + numbers
[samecount
]
51 var meetings_left
: Int
52 var firstcolor
: nullable Int
54 var current
: Future[Pair] is noinit
56 private var mutex
= new Mutex
58 fun meet
(id
, c
: Int): nullable Pair do
59 var new_pair
= new Future[Pair]
61 if meetings_left
== 0 then
65 if firstcolor
== null then
68 current
= new Future[Pair]
70 var color
= complements
[c
][firstcolor
.as(not null)]
71 current
.set_value
(new Pair(id
== firstid
, color
))
83 fun blue
: Int do return 0
84 fun red
: Int do return 1
85 fun yellow
: Int do return 2
86 var numbers
= ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
87 var colors
= ["blue", "red", "yellow"]
88 # Matrix for complementing colors
89 var complements
: Array[Array[Int]] = [[0, 2, 1],
95 fun print_all_colors
do
96 print_colors
(blue
, blue
)
97 print_colors
(blue
, red
)
98 print_colors
(blue
, yellow
)
99 print_colors
(red
, blue
)
100 print_colors
(red
, red
)
101 print_colors
(red
, yellow
)
102 print_colors
(yellow
, blue
)
103 print_colors
(yellow
, red
)
104 print_colors
(yellow
, yellow
)
107 fun print_colors
(c1
, c2
: Int) do
108 print colors
[c1
] + " + " + colors
[c2
] + " -> " + colors
[complements
[c1
][c2
]]
111 fun get_number
(n
: Int): String do
115 str
+= " " + numbers
[c
.to_i
]
120 fun work
(n
, nb_colors
: Int ) do
121 var place
= new MeetingPlace(n
)
122 var creatures
= new Array[Creature]
123 for i
in [0..nb_colors
[ do
124 printn
" " + colors
[i
% 3]
125 creatures
[i
] = new Creature(place
, i
% 3, i
)
129 for c
in creatures
do c
.async
.run
134 for c
in creatures
do
139 print get_number
(total
)
142 for c
in creatures
do
144 c
.async
.wait_termination
148 var n
= if args
.is_empty
then 600 else args
[0].to_i