Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #4571
| From | Robert Klemme <shortcutter@googlemail.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: Counting how many times the same elements occurs in an array? |
| Date | 2011-05-15 15:37 +0200 |
| Message-ID | <93a392Fkp8U1@mid.individual.net> (permalink) |
| References | <6a81112b3af069fa30e1c843c72f8be9@ruby-forum.com> <d6cf848516ea814ff3552bba56a5c4ba@ruby-forum.com> |
On 15.05.2011 15:06, Thomas Greenwood wrote:
> I'm sure your solutions are better than mine, what I ended up doing;
>
> xml_events = Array.new
> temp_array = Array.new
>
> [...]
> #extract xml data and assign it to the events array.
> [...]
>
> xml_events.each{|x|
> if temp_array.include?(x) == false
This is dangerous: in Ruby false and nil are treated as boolean false.
It's better to not compare with boolean constants but rather to use
boolean operators and logic. In your case you could do
if !temp_array.include?(x)
unless temp_array.include?(x)
> temp_array<< x
> puts "#{x} occurs #{xml_events.count(x)} times"
> end
> }
>
> A kludge but it does the job.
Your code has effort O(n*n) if I am not mistaken while the approach with
the Hash storage of counters only has O(n). That might not really make
a difference in your case but from the fact that you are iterating
xml_events over and over again (same for temp_array btw.) you might see
that it is "ugly" in a way.
> Thanks for your help.
You're welcome.
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
Back to comp.lang.ruby | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Counting how many times the same elements occurs in an array? Thomas Greenwood <nedpointsman@gmail.com> - 2011-05-15 05:01 -0500
Re: Counting how many times the same elements occurs in an array? John Feminella <johnf@bitsbuilder.com> - 2011-05-15 06:49 -0500
Re: Counting how many times the same elements occurs in an array? Robert Klemme <shortcutter@googlemail.com> - 2011-05-15 13:52 +0200
Re: Counting how many times the same elements occurs in an array? Thomas Greenwood <nedpointsman@gmail.com> - 2011-05-15 08:06 -0500
Re: Counting how many times the same elements occurs in an array? Robert Klemme <shortcutter@googlemail.com> - 2011-05-15 15:37 +0200
Re: Counting how many times the same elements occurs in an array? 7stud -- <bbxx789_05ss@yahoo.com> - 2011-05-15 15:01 -0500
Re: Counting how many times the same elements occurs in an array? Adam Prescott <adam@aprescott.com> - 2011-05-15 15:21 -0500
Re: Counting how many times the same elements occurs in an array? David Jacobs <developer@wit.io> - 2011-05-15 15:33 -0500
csiph-web