Ruby for daily chores: Extracting most frequent loto numbers

Here’s the quick story: I was hoping to win the Romanian lottery (6 winning numbers out of 49). On the website, they were having the list of the winning numbers from 1998 to now. So I copy-pasted them all into a text file, and wrote a quick and dirty script to count their appearances and sort them – thus getting the lists of the most frequent numbers and the least frequent ones.

First, the input text file – I’ll show you a brief excerpt:

2007-07-01 29 39 15 14 23 9
2007-07-08 8 41 46 12 4 17
2007-07-15 36 41 44 46 48 10
2007-07-22 24 47 46 30 9 23
2007-07-29 43 19 13 46 38 42
2007-08-05 44 4 38 28 37 35
2007-08-12 42 43 18 47 46 44

Now, the code:


# initialize: the data structure to store the results
freqs={}
(1..49).each {|x| freqs[x]=0}

# parse the input text file(shown above)
i=0
res=[]
File.open("loto07.txt").each { |line|
  res[i]=line.split(" ")
  i=i+1
}

#increase the frequency of appearance, for each winning number
res.each{|line|
  line[1..-1].each{|a|
    nb=a.to_i
    freqs[nb]=freqs[nb]+1
  }
}

# sort the datastructure by frequency and display
puts freqs.sort{|a,b| a[1]<=>b[1]}.inspect

Nothing more to explain: a simple ruby script to sort the winning lotto numbers across history by their frequency. Now, if you win the lotto by using this script as well, I won’t mind a small(or bigger) gift. Seriously.


Similar Posts:

Leave a Reply