From: dblack@... Date: 2002-09-19T10:19:58+09:00 Subject: Re: How to Efficiently Calculate the Pattern of Zeros and Ones? Hi -- On Thu, 19 Sep 2002, Chris Reay wrote: > William Djaja Tjokroaminata wrote in message news:... > > Hi, > > > > I am dealing with this algorithmic problem. I have an array of arbitrary > > integers. I have to count the occurences of 1's with the pattern > > > > "0 0 ... 0 1 0 .. 0 0" > > > > in the array. The minimum number of zeros on each side of the 1 is a > > parameter, say m = 2. Also at the beginning and at the end of the array, > > the boundary condition does not require the minimum number of zeros, as > > long as they are zeros (or non-existent). > > > > For example, with m = 2: > > > > [1 0 0 1 0 0 5 1] --> 2 > > [0 0 1 0 0 1 0 2] --> 1 > > [1 0 1 0 1 0 1 0] --> 0 > > [1 0 0 0 0 0 1 0] --> 2 > > > > Typical array length will be around 24. The problem is I will have > > thousands, if not hundreds of thousands, of such arrays. What is a good > > way to do it in Ruby? (Even coverting the array first to, for example, > > string and then use regexp, is also fine as long as it is efficient.) > > > > Regards, > > > > Bill > > Is this too slow? > > arr.select { |i| i ==1 }.size That counts all the 1's, without regard for whether or not they're surrounded by the requisite number of 0's. David -- David Alan Black | Register for RubyConf 2002! home: dblack@candle.superlink.net | November 1-3 work: blackdav@shu.edu | Seattle, WA, USA Web: http://pirate.shu.edu/~blackdav | http://www.rubyconf.com