Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #6907

Re: Making a count of unique elements in an array

From Robert Klemme <shortcutter@googlemail.com>
Newsgroups comp.lang.ruby
Subject Re: Making a count of unique elements in an array
Date 2013-12-28 12:02 +0100
Message-ID <bi7peiF3p8jU1@mid.individual.net> (permalink)
References <1136789236.482098.144200@o13g2000cwo.googlegroups.com> <5327790f-e3da-4cb6-a94c-b198de7139da@googlegroups.com> <bh3etcFg4fbU1@mid.individual.net> <9d904cf9-f46c-4ec9-8564-45614ff97501@googlegroups.com>

Show all headers | View raw


On 26.12.2013 22:44, lukeabergen@gmail.com wrote:
> Another way is the super-useful group_by and map
>
> arr = ["a", "b", "b", "c", "c", "d", "e", "e", "e"]
> grouped = arr.group_by {|x| x}  #=> produces something like {"a" => ["a"], "b" => ["b", "b"], etc...
> result = grouped.map {|el, arr| [el, arr.count]}

Downside of that approach is that it does unnecessary work and uses more 
memory than necessary.  And the result is not a Hash which may make 
retrieval of the counts of an element quite expensive if there are many 
different values.

Btw, the OP spoke of a "2D array".  So the input likely looks different 
than in your example.  We also do not know what he actually wants to 
count.  Is it individual elements?  Or does "distinct elements" refer to 
a single array?

Kind regards

	robert

Back to comp.lang.ruby | Previous | NextPrevious in thread | Find similar


Thread

Re: Making a count of unique elements in an array vsingla160@gmail.com - 2013-12-12 09:56 -0800
  Re: Making a count of unique elements in an array Norbert Melzer <norbert.melzer@gmx.net> - 2013-12-12 19:44 +0100
  Re: Making a count of unique elements in an array Robert Klemme <shortcutter@googlemail.com> - 2013-12-14 17:22 +0100
    Re: Making a count of unique elements in an array lukeabergen@gmail.com - 2013-12-26 13:44 -0800
      Re: Making a count of unique elements in an array Robert Klemme <shortcutter@googlemail.com> - 2013-12-28 12:02 +0100

csiph-web