From: Robert Feldt Date: 2006-04-02T18:23:49+09:00 Subject: Re: Gathering ngrams with the highest probability On 4/2/06, Minkoo Seo wrote: > Hi group. > > I'm writing some scientific applications with Ruby, and found a > frequent problem that I want to solve with Ruby. > > I got tons of instances of NGram whose definition is as follows: > > NGram = Struct.new :seq, :prob > > I have a list of instances of NGram like: > > .... > # > # > # > # > # > # > # > # > # > # > # > # > # > # > # > .... > > What I want to derive from this data is the list of NGram instances > each of which is unique with regard to seq. At the same time, the prob > of each ngram in the list must be that of the highest prob. > > For example, from the ngram list I've shown above, I want to derive a > list like the folloing: > > .... > # > # > # > # > # > # > # > .... > > What I've written so far is > > # Sort by prob in descending order > ngrams.sort_by { |ngram| > > # Compare seq > > # Then, compare prob > } > > result = [] > > # Collect unique ngrams with the highest prob. > ngrams.inject(nil) { |prev, cur| > if prev.nil? > result << cur > prev = cur > elsif prev.seq != cur.seq > result << cur > prev = cur > end > } > > return result > ngrams.inject({}) do |highest, ngram| seq = ngram.seq best_now = highest[seq] highest[seq] = ngram unless (best_now && best_now.prob > ngram.prob) highest end.values /RF