Forum: Ruby Re: Array.invert

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
87e9a89c53ccf984db792113471c2171?d=identicon&s=25 Kroeger, Simon (ext) (Guest)
on 2005-12-13 17:14
(Received via mailing list)
Hi Christer,

don't take this to serious:

a = [[1,3],[1,4,5]]
p (0...a.size).zip(a).inject([]){|s, b| b[1].each{|i| (s[i] ||= []) <<
b[0]}; s}

=> [nil, [0, 1], nil, [0], [1], [1]]

cheers

Simon
Af95bdaf87958c40150b813e94381bfd?d=identicon&s=25 Christer Nilsson (christer)
on 2005-12-13 18:10
Kroeger, Simon (ext) wrote:
> Hi Christer,
>
> don't take this to serious:
>
> a = [[1,3],[1,4,5]]
> p (0...a.size).zip(a).inject([]){|s, b| b[1].each{|i| (s[i] ||= []) <<
> b[0]}; s}
>
> => [nil, [0, 1], nil, [0], [1], [1]]
>
> cheers
>
> Simon

Ruby is so fun, it's impossible to be serious :-)

a.invert works but not a.invert.invert

Can you fix that in your amazing oneliner ?
Clue: nil.each is the bummer.

Christer
A9c4658e9e475e13d790ae419acf01b6?d=identicon&s=25 =?UTF-8?B?U2ltb24gS3LDtmdlcg==?= (Guest)
on 2005-12-13 21:04
(Received via mailing list)
Christer Nilsson wrote:
>>=> [nil, [0, 1], nil, [0], [1], [1]]
> Can you fix that in your amazing oneliner ?
> Clue: nil.each is the bummer.
>
> Christer

rofl!

i will give you two:

class Array
   def invert
     zip([*(0...size)]).inject([]){|s, b| (b.first || []).each{|i| (s[i]
||= []) << b.last}; s}
   end
end

or (even worse):

class Array
   def invert
     Array.new(flatten.compact.max.succ){|i|
zip([*(0...size)]).find_all{|b, j| b && b.include?(i)}.transpose[1]}
   end
end


cheers

Simon
Af95bdaf87958c40150b813e94381bfd?d=identicon&s=25 Christer Nilsson (christer)
on 2005-12-14 00:34
Simon wrote:
>
> i will give you two:
>
> class Array
>    def invert
>      zip([*(0...size)]).inject([]){|s, b| (b.first || []).each{|i| (s[i]
> ||= []) << b.last}; s}
>    end
> end
>
> or (even worse):
>
> class Array
>    def invert
>      Array.new(flatten.compact.max.succ){|i|
> zip([*(0...size)]).find_all{|b, j| b && b.include?(i)}.transpose[1]}
>    end
> end

I didn't know invert was so complex that ten keywords were needed!
The more keywords, the more cycles.
My original old fashioned fortran style polyliner is still quickest :-)

Christer
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2006-01-01 21:33
(Received via mailing list)
Hi --

On Wed, 14 Dec 2005, Simon Kröger wrote:

>>>
>>
>  def invert
>    zip([*(0...size)]).inject([]){|s, b| (b.first || []).each{|i| (s[i] ||=
> []) << b.last}; s}
>  end
> end

You could also do: b.first.to_a, which will be [] for nil and self if
b.first is an array.


David

--
David A. Black
dblack@wobblini.net

"Ruby for Rails", forthcoming from Manning Publications, April 2006!
This topic is locked and can not be replied to.