From: Kendall Gifford Date: 2011-08-13T04:05:24+09:00 Subject: Re: noob question - pattern matching --001485f85fe861f59e04aa539809 Content-Type: text/plain; charset=UTF-8 On Fri, Aug 12, 2011 at 12:31 PM, Jesper Brandt wrote: > I have a list of 22000 8 digit numbers. Im looking for a number which is > the "best" from a defined set of patterns. > > a pattern could be "abababab" givng a score of 10, and another would be > "abab" giving a score of 5. Patterns could also be specific digits, so > another pattern defining "a0b0" - giving 7 points would mean that it > would only match if there is zeroes in the number such as 10203040 (with > all the above rules it would give 21 points). > > This way the number 52525252 would give a score of 25 and the number > 52526262 would give the score of 10. > > do anybody have a good idea on how to make such a scoring in ruby? > > I'm sorry - but im a bit of a noob regarding ruby, but thought it would > be a good project to get a better virew on the language:-) > Regards > > JB > > #!/usr/bin/env ruby PATTERNS = { /(\d)(\d)\1\2\1\2\1\2/ => 10, # abababab (aaaaaaaa too though) /(\d)(\d)\1\2/ => 5, # abab (aaaa too though) /\d0\d0/ => 7 # a0b0 (a0a0 too though) } NUMBERS = %w{ 12345678 00000000 12121212 01020102 23240102 } def score(number) PATTERNS.reduce(0) do |score, entry| entry.first =~ number ? score + entry.last : score end end puts NUMBERS.map { |n| "#{n} => #{score(n)}" }.join("\n") -- There are several things you didn't specify fully (such as whether the shorter 4-digit patterns can match anywhere in a number or whether they should be anchored to the beginning/end of the number, etc.) but you could easily adjust the patterns and/or logic to suit. Additionally, if a pattern was too complex to be specified using a regular expression, you could let the PATTERNS hash have Regexp _or_ lambda instances and update the #score method to detect which each pattern entry is and do the right thing. -- Kendall Gifford zettabyte@gmail.com --001485f85fe861f59e04aa539809--