<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users1544</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1544" rel="self"/>
  <title>spoonerism.myopenid.com</title>
  <updated>Wed Jun 10 11:00:18 -0700 2009</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code907</id>
    <published>2009-06-10T11:00:18-07:00</published>
    <updated>2009-06-25T22:45:27-07:00</updated>
    <title>[Ruby] Ruby: array intersperse, efficiency</title>
    <content type="html">&lt;p&gt;Intersperse is a method of the array class&lt;/p&gt;

&lt;p&gt;Intersperse takes an object o, and returns the array ( self ), with o inserted between each element of self.&lt;/p&gt;

&lt;pre&gt;class Array

   # insert i between each element in the array

   # this is O( 2n ) ( I think! Is it? ) as the length of the list is not needed, but we need to initially make a copy of the list
     def intersperse( v )
      tail = [ ].replace self # we need a shallow copy
      first_elem = tail.first
      second_elem = tail[ 1 ]
      arr = [ ]
      while first_elem
         arr.push first_elem
         if second_elem
            arr.push v
            tail = tail.drop 1
            first_elem = tail.first
            second_elem = tail[ 1 ]
         else
            break
         end
      end
      arr
   end

  # this is faster, but I worry that for large arrays, storing i in memory will makes this slower
  # Bearing that in mind, since the speed at which this goes is determined by the length of the list as well as the length of the list stored in memory ( i ) is O( n^2 ) ( again, please correct me )
  def intersperse( v )
     arr = [ ]
     i = 0
     j = 0
     inc_jay = lambda { j = j + 1 }
     while i &amp;lt; length
        arr[ j ] = self[ i ]
        inc_jay.call
        if self[ i + 1 ]
           arr[ j ] = v
           inc_jay.call
        end
        i = i + 1
     end
     arr
  end
end&lt;/pre&gt;</content>
    <author>
      <name>spoonerism.myopenid.com</name>
      <email>spoon@killersmurf.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/907-can-this-code-be-made-more-efficient" rel="alternate"/>
  </entry>
</feed>

