games: Introduce a simple puzzle game
[lcapit-junk-code.git] / mega-sena / python / megasena-stats
blobebfdbcd7bfe98c6ba2ec36a963bfd37733701bf6
1 #!/usr/bin/python
3 # TODO:
4 # 1. Describe this thing as a whole
5 # 2. Check whether randint() is safe
7 # This software is licensed under the GPLv2
9 # Author: Luiz Fernando N. Capitulino <lcapitulino@gmail.com>
12 import sys
13 import signal
14 import hashtable
15 from os import getpid
16 from random import randint
18 nr_runs = nr_found = 0L
20 def sig_handler(signum, frame):
21 """Show current status."""
22 sys.stdout.write('-> Ran %d times with %d matches\n' %
23 (nr_runs, nr_found))
24 sys.stdout.flush()
26 def show_pid():
27 """Print our PID."""
28 sys.stdout.write('-> PID: %d\n\n' % getpid())
29 sys.stdout.flush()
31 def megasena():
32 """Make the lottery.
34 Randomly generate six not equal numbers between 1 and 60, return
35 them as a string formatted likes this: 12 03 21 22 43 25.
37 Note that we must always return two algarisms, because external data
38 also does.
39 """
40 numbers = []
42 for i in range(6):
43 while True:
44 # XXX: Is there something better than randint() to be
45 # used here?
46 val = randint(1, 60)
47 if val in numbers:
48 continue
49 numbers.append("%02d " % val)
50 break
52 return ''.join(numbers).rstrip()
54 def main():
55 global nr_runs, nr_found
57 try:
58 probe = sys.argv[1]
59 fname = sys.argv[2]
60 except:
61 sys.stderr.write('usage: %s < -linear-probe | -double-hashing | -chained > < file-name >\n' % sys.argv[0])
62 sys.exit(1)
64 if probe == '-double-hashing':
65 table = hashtable.OpenAddressedDH(3119)
66 elif probe == '-linear-probe':
67 table = hashtable.OpenAddressedLP(10240)
68 elif probe == '-chained':
69 table = hashtable.Chained(2048)
70 else:
71 sys.stderr.write('Unknown probe method: %s\n' % probe)
72 sys.exit(1)
74 table.load_from_file(fname)
76 print ''
77 table.show_stats()
78 show_pid()
80 # Print status when SIGUSR1 is sent
81 signal.signal(signal.SIGUSR1, sig_handler)
83 while True:
84 name = megasena()
85 ret = table.lookup(name)
86 if ret >= 0:
87 sys.stdout.write('-> HIT in run %d: [%d] %s\n' %
88 (nr_runs, ret, name))
89 sys.stdout.flush()
90 nr_found += 1
92 nr_runs += 1
94 if __name__ == "__main__":
95 main()