HI everyone,
I am wondering how would you make a program to find a list of things
from a file as efficiently as possible. So I have this file that gives
the rank of the following pairs:
pair – rank
4,2 – 1
4,5 – 2
6,8 – 3
8,2 – 4
and I have another file that lists how it predicted the order of this
pairs.
pair
8,2
6,8
4,5
4,2
I need to add to this file the corresponding ranks, preferably without
scanning the file more than once.
So I grab the file of pairs and make it an array like this:
array = []
File.foreach(“pairs.txt”) do |line|
array << line
end
but then I’m not sure how to best proceed to search that file for the
respective ranks and return them, without scanning the file more than
once
Any help appreciated,
Ted.
I need to add to this file the corresponding ranks
Sorry, you don’t add anything to a file–you can only read a file and
then write new output to another file.
In your case, just make a hash out of the first file. split() would
be helpful in that regard. Then read the second file and use each read
line(properly stripped of the \n) as the key in the hash to look up the
value(the rank), and then write the read line plus the rank to a third
file.
Ted F. [email protected] wrote:
[ merging two files ]
I need to add to this file the corresponding ranks, preferably without
scanning the file more than once.
So I grab the file of pairs and make it an array like this:
[…]
first file
pair – rank
4,2 – 1
4,5 – 2
6,8 – 3
8,2 – 4
Use a hash:
pairranks = {}
File.foreach(“pairs.txt”) do |line|
k, v = line.split(/ *-- */)
pairranks[k] = v
end
second file:
pair
8,2
6,8
4,5
4,2
File.open(“result.txt”, ‘w’) do |f|
File.foreach(“sorted.txt”) do |line|
line.chomp!
f << line << pairranks[line]
end
end
I leave error handling (missing values etc) to the reader.
Klaus
PS: this is untested code! may contain syntax and other errors.
The Answer is 42. And I am the Answer. Now I am looking for the
Question.