more playing with inet processing
[xorg/xkeyboard-config] / tests / ruby / utils.rb
1 #
2 # $Id$
3 #
4 # Commont classes
5 #
6
7 #
8 # The hash containing non-unique mappings
9 # It can have a->b and a->c together
10 # Also, for every mapping it counts the number of times this mapping was set
11 #
12 class NonuniqueCountingHash < Hash
13
14   alias get_original []
15   alias put_original []=
16
17   def []=(key, value)
18     own = self.get_original(key)
19     hash = get_original(key)
20     if hash.nil?
21       put_original(key, hash = Hash.new)
22     end
23     if hash.has_key?(value)
24       hash[value] += 1
25     else
26       hash[value] = 1
27     end
28   end
29   
30   #
31   # Number of all mappings (a->b and a->c counted as 2 mappings)
32   #
33   def full_length()
34     values.inject(0) do | rv, hash |
35       rv + hash.length
36     end
37   end
38
39   def cardinality(key1, key2)
40     if has_key?(key1) 
41       hash = get_original(key1)
42       if hash.has_key?(key2)
43         hash[key2]
44       else
45         0
46       end
47     else
48       0
49     end
50   end
51
52   def filter(limit)
53     find_all do | key, hash |
54       hash.find_all do | key1, counter |
55         if (counter <= limit)
56           hash.delete(key1)
57         end
58       end
59       if hash.empty? 
60         delete(key)
61       end
62     end
63   end
64 end