From: Johan Holmberg Date: 2002-09-19T17:20:03+09:00 Subject: Re: How to Efficiently Calculate the Pattern of Zeros and Ones? William Djaja Tjokroaminata writes: > > 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 > I don't know if the following is efficient in terms of CPU-cylces but it is at least rather short and easy to read (once you know the cool enum-package). /Johan Holmberg #---------------------------------------------------------------------- require "enum/cluster" lists = [ [1, 0, 0, 1, 0, 0, 5, 1], [0, 0, 1, 0, 0, 1, 0, 2], [1, 0, 1, 0, 1, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0], ] facit = [0, 0, 1, 0, 0] m = 2 for list in lists count = 0 list.each_with_neighbors(m, 0) do |part| count += 1 if part == facit end puts "# in #{list.inspect} = #{count}" end #----------------------------------------------------------------------