Need to find list of things in a file

T

Ted Flethuseo

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

7stud --

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, you 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 kes in the hash to look up the
value(the rank), and then write whatever you want to a third file.
 
K

Klaus Stein

Ted Flethuseo said:
[ 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top