Re: Array.invert

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

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 :slight_smile:

a.invert works but not a.invert.invert

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

Christer

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 :slight_smile:

Christer

Christer N. 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

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
[email protected]

“Ruby for Rails”, forthcoming from Manning Publications, April 2006!