lib/core/stream: LineIterator use CachedIterator
[nit.git] / examples / rosettacode / arithmetic_mode.nit
1 #!/usr/bin/env nit
2 #
3 # This file is part of NIT ( http://www.nitlanguage.org ).
4 # This program is public domain
5
6 # Task: Arithmetic mode
7 # SEE: <http://rosettacode.org/wiki/Averages/Mode>
8 module arithmetic_mode
9
10 # Computes the mode or the `array` values.
11 #
12 # FIXME: Only the first mode will be returned, should we return an array of modes?
13 fun mode(array: Array[Int]): nullable Int do
14 var seen = new HashMap[Int, Int]
15 for i in array do
16 if not seen.has_key(i) then seen[i] = 0
17 seen[i] += 1
18 end
19 var max_key = null
20 var max_val = 0
21 for k, v in seen do
22 if v > max_val then
23 max_key = k
24 max_val = v
25 end
26 end
27 return max_key
28 end
29
30 print mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) or else "null"
31 print mode([1, 1, 2, 4, 4]) or else "null"
32 print mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) or else "null"
33 print mode([1, 1, 2, 4, 4]) or else "null"