# Re: Preferable Pairs (#165)

**URL:** <https://www.ruby-forum.com/t/re-preferable-pairs-165/140006>\
**Category:** Ruby\
**Created:** [June 10, 2008, 12:44am UTC](https://www.ruby-forum.com/t/re-preferable-pairs-165/140006 "2008-06-10T00:44:52Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Steven\_Hahn](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/5f8ce5/32.png) [@Steven\_Hahn](https://www.ruby-forum.com/u/Steven_Hahn)\
**Post date:** [June 10, 2008, 12:44am UTC](https://www.ruby-forum.com/t/re-preferable-pairs-165/140006/1 "2008-06-10T00:44:52Z")

</div>

I made a couple of minor optimizations to my solution. It still will  
not handle large inputs, but it is a little better. Thanks to Eric  
Ivancich, I removed some of the duplicate checks of potential solutions.  
I hope I got them all. Also, I added some memoization for values of  
solution sets, which has the downside of requiring more memory but seems  
to improve overall performance.

* * *

require ‘yaml’

#execute program by providing a file name with the data in YAML format  
#Example YAML file contents:  
#David: Helen Vicki Joseph  
#Helen: David Vicki Joseph  
#Joseph: Vicki Helen David  
#Vicki: David Helen Joseph

class PairCalculator  
def initialize(filename)  
#read data into hash from YAML file  
@pairs\_hash = YAML::load\_file(filename)  
@num\_people = @pairs\_hash.length  
@num\_choices = @num\_people - 1  
@pair\_set\_value\_hash = Hash.new  
@pair\_value\_hash = Hash.new

```
#build array of all possible pairs
@all_pairs = get_all_pairs

```

end

#finds the nth choice of a person for some value n, 0 would be  
#the first choice, 1 second, etc.  
def get\_nth\_choice(person, n)  
@pairs\_hash[person].scan(/\w+/)[n]  
end

#this method returns 0 if the pair is only one name  
#otherwise it looks up the pair value in a hash  
#preference indexes, 0=best, 1=next best, etc.  
def get\_pair\_value(pair)  
pair\_array = pair.split(" ")  
return 0 if(pair\_array.length==1)

```
#get the value from the pair value hash
return @pair_value_hash[pair] + @pair_value_hash[pair_array[1] + " " 

```

- pair\_array[0]]  
end

- p1))

if(ARGV.length == 0)  
puts “Usage: provide YAML file name as the argument.”  
exit 0  
end

t1 = Time.now  
pc = PairCalculator.new(“list.yaml”)  
pair\_set = pc.get\_preferred\_pairs  
pair\_set.each {|pair| puts pair}  
t2 = Time.now  
puts “Pair set value: #{pc.get\_pair\_set\_val(pair\_set)} \nTime: #{t2 -  
t1}”
