Piyush Ranjan
3/28/2008 10:19:00 PM
[Note: parts of this message were removed to make it a legal post.]
A faster(running time) way is this
def freq2(a)
a_sorted=a.sort;temp=0;h=Hash.new(0);
a_sorted.uniq.each{|x|
h[x]=a_sorted.rindex(x)+1-temp;
temp+=h[x]
}
end
I did a small test and this method seems to running 5 times faster than the
inject one!
>> start=Time.now; 1000.times{|x| freq1(a*x)}; stop=Time.now; puts
stop-start
16.413787
>> start=Time.now; 1000.times{|x| freq2(a*x)}; stop=Time.now; puts
stop-start
3.17855
This seemed counter intuitive as freq2 is doing a lot more than freq1.
Is inject that slow (or have I done something wrong)???
Piyush
On Fri, Mar 28, 2008 at 11:55 PM, jzakiya <jzakiya@mail.com> wrote:
> On Mar 28, 11:39 am, jzakiya <jzak...@mail.com> wrote:
> > On Mar 27, 10:51 am, Paul Danese <pdan...@Rib-x.com> wrote:
> >
> >
> >
> > > If you install the facets gem you can use "frequency"
> >
> > > e.g.
> >
> > > >irb
> >
> > > irb:> require 'rubygems'
> > > => false
> > > irb:> require 'facets'
> > > => true
> > > irb:> x = %w[a b d e e rkeke ele e ee e e el d]
> > > => ["a", "b", "d", "e", "e", "rkeke", "ele", "e", "ee", "e", "e",
> "el",
> > > "d"]
> > > irb:> x.frequency
> > > => {"ee"=>1, "a"=>1, "b"=>1, "d"=>2, "e"=>5, "el"=>1, "ele"=>1,
> > > "rkeke"=>1}
> >
> > I installed facets 2.4.0 (the current latest) and tried to use the
> > 'frequency' method shown in this example, but in doesn't exist in this
> > version of facets.
> >
> > I did 'ri facets' and it only returned 'Enumerable#frequency'
> > This is using Linux (PCLOS) and Ruby 1.8.6-p114.
> >
> > What version of facets does the 'frequency' method exist in, because
> > it isn't in version 2.4.0?
>
> Correction:
> I did 'ri frequency' NOT 'ri facets'
>
>