In search of elegant indices searching


#1

Dear all,

I have a Hash, with equal-length Arrays as values, something like

my_hash={‘x’,[1,1,3,1,5,6],‘w’,[1,2,3,1,4,5],‘y’,[1,1,1,4,4,6],‘z’,[0,1,1,2,3,
4]} .

Some of the values in the Arrays occur several times.
Now, I am looking for an elegant way to extract, for all the values
of specified keys, all the indices
where one or more variables do not change their values, i.e., something
like

class Hash
def fixed_vars(which_vars)

     # some elegant code
    return result
end

end

res=my_hash.fixed_vars([‘x’,‘w’])

giving

res={{‘x’=>1,‘w’=>1}=>[0,3],{‘x’=>3,‘w’=>3}=>[2],{‘x’=>5,‘w’=>4}=>[4],{‘x’=>6,
‘w’=>5}=>[5]}.

How could that be done?

Thank you!

Best regards,

Axel


#2

2006/5/16, removed_email_address@domain.invalid removed_email_address@domain.invalid:

where one or more variables do not change their values, i.e., something
res=my_hash.fixed_vars([‘x’,‘w’])

giving

res={{‘x’=>1,‘w’=>1}=>[0,3],{‘x’=>3,‘w’=>3}=>[2],{‘x’=>5,‘w’=>4}=>[4],{‘x’=>6,
‘w’=>5}=>[5]}.

That’s a really wired output. Can you explain what that means? I have
a hard time detecting the pattern here.

robert


#3

removed_email_address@domain.invalid å??é?ï¼?

Dear all,

I have a Hash, with equal-length Arrays as values, something like

my_hash={‘x’,[1,1,3,1,5,6],‘w’,[1,2,3,1,4,5],‘y’,[1,1,1,4,4,6],‘z’,[0,1,1,2,3,
4]} .

Some of the values in the Arrays occur several times.
Now, I am looking for an elegant way to extract, for all the values
of specified keys, all the indices
where one or more variables do not change their values, i.e., something
like

class Hash
def fixed_vars(which_vars)

     # some elegant code
    return result
end

end

res=my_hash.fixed_vars([‘x’,‘w’])

giving

res={{‘x’=>1,‘w’=>1}=>[0,3],{‘x’=>3,‘w’=>3}=>[2],{‘x’=>5,‘w’=>4}=>[4],{‘x’=>6,
‘w’=>5}=>[5]}.

Indeed, I really don’t fully understand what you want , and the code
below is hacked out and is definitively not elegant. But it works, and
gives what you want .

module MyHash
def fixed_vars(key1, key2)
res = {}
def res.
self.each do |akey, aval|
if akey == key
return aval
end
end
nil
end
a1 = self[key1]
a2 = self[key2]
len = a1.length
recorded = []
len.times do |i|
if a1[i] == a2[i]
h = {key1=>a1[i],key2=>a2[i]}
res[h]=[] if res[h] == nil
res[h] << i
recorded << a1[i]
end
end
len.times do |i|
if a1[i] != a2[i] and
(not recorded.include?(a1[i])) and
(not recorded.include?(a2[i]))
res[{key1=>a1[i],key2=>a2[i]}] = [] if
res[{key1=>a1[i],key2=>a2[i]}] == nil
res[{key1=>a1[i], key2=>a2[i]}] << i
end
end
return res
end
end

def testmy_hash
my_hash={‘x’,[1,1,3,1,5,6],‘w’,[1,2,3,1,4,5],
‘y’,[1,1,1,4,4,6],‘z’,[0,1,1,2,3,4]}
my_hash.extend MyHash
res = my_hash.fixed_vars(‘x’,‘w’)
puts res.inspect
end

testmy_hash

Best regards.