How to read different lines from a text file simultaneously - scala

I need to read a file line by line such that it reads the first line, does something with it, then takes the second line, does something with it and so on.
I know how to read a text file line by line:
for(line <- Source.fromFile("file.txt").getLines())
{
insert(line) **Use the first line of the file in this function
reverse(line) **Use the second line of the file in this function
}
in the insert function, first I want to use the first line of the file, and in the reverse function I want to use the second line, then in the second iteration of the loop, I want to use the 3rd line in the insert function and the 4th line in the reverse function and so on. How to do that?
EDIT: This is just an example. I want a general thing, like suppose if I want to use the first line, second line, third line and then iterate the for loop, how to do that?

Lots of clever solutions. Here's a simple one using zipWithIndex that handles even cases with an uneven number of lines.
for((line,index) <- Source.fromFile("file.txt").getLines().zipWithIndex)
{
if (index % 2 == 0) insert(line)
else reverse(line)
}

One more approach, using grouped, which takes into account a (possibly) uneven number of lines,
Source.fromFile("file.txt")
.getLines
.grouped(2)
.map { xs => (xs.head, xs.last.reverse) }
Note that getLines gives an iterator for fetching one line at a time, sequentially, then grouped gives yet another iterator with paired lines for simultaneous processing. This is in contrast with reading multiple lines of a file at the same time.

Using sliding to group your lines into pairs of two.
for(pairs <- Source.fromFile("file.txt").getLines().sliding(2, 2)) {
insert(pairs.head)
reverse(pairs.last)
}
Obviously you'll need to handle the condition where you don't have a list of even length.

Related

How do I add only one value per line?

I am trying to take a user input and write it to a separate .txt file with only one input per line.
vote = input()
fh = open('votedata.txt', 'a')
fh.write(vote)
fh.close
When I run my code it saves the input and places it in the txt file, however instead of placing each value on a new line it bunches them together on one. So if I have 5 inputs like 1,2,3,4,5 instead of placing each number on a separate line it bunches them together like 12345. How do I change this?
Try it like this :
vote = input('Enter your vote')
fh = open('votedata.txt', 'a')
fh.write(vote + '\n')
fh.close

Matlab: Printing a data on a specific line

I have below function:
function [] = Write(iteration)
status=close('all');
nomrep=num2str(iteration);
fid=fopen('ID.dat','a');
frewind(fid);
for l=1:iteration
line=fgetl(fid);
end
fprintf(fid,[nomrep,' \n']);
status=fclose(fid);
end
I expect that Write(15) creates ID.dat and prints 2 and 15 in consecutive lines at begining of line 15th.
But is prints those values always on the beginning of the file.
Even I tried fgetl(fid) alone, and also replaced for loop with while loop still did not work.
Is it due to the fact that I should fill in the lines before that with some dummy space? along side this, I executed
for i=1:5
Write(i);
end
Which should print 1 to 5 in each line but even this does not work.
This line is the problem:
fid=fopen('ID.dat','w');
Everytime you open the file, you are overwriting the previous contents (that is what the 'w' argument does). Change 'w' to 'a' (for append), and your file will retain the contents from one write to the next.

Hackerrank stdin only gives me the first line from multiple lines

I am trying to solve this challenge on HackerRank:
https://www.hackerrank.com/challenges/30-operators?h_r=next-challenge&h_v=zen
the way I tried to read the stdin is this:
let input = readline()!
However, the input consists of three lines, e.g.
12.00
20
8
How do I get all three lines, ideally in some separated way so that I can cast them to their respective types?
If you need the 3 lines, call it 3 times :)
The documentation is explicit
Returns Characters read from standard input through the end of the
current line or until EOF is reached, or nil if EOF has already been
reached.
But it seems they forgot to indicate that reading a line will change the current line
Generally what I would do is use input() to assign the stdin values to a variable and then pass the variables for functions.
example:
a = input() #gives the first line
b = input() #gives the second line
c = input() #gives the third line
if you would like to read all the lines then use a for loop:
example:
import sys
for line in sys.stdin:
print(line)

Does eof() look at lines or data? C++

Let's say I am trying to read in data line by line from a file called input.txt. There's about 20 lines and each line consists of 3 different data types. If I use this code:
while(!file.eof){ ..... }
Does this function look at only one data type from each line per iteration, or does it look at the all the data types at once for each line per iteration--so the next iteration would look at the next line instead of the next data type?
Many thanks.
.eof() looks at the end of file flag. The flag is set after you run over the end of the file. This is not desirable.
A great blog post on how this works and best practice can be found here.
Basically, use
std::string line;
while(getline(file, line)) { ... }
or
while (file >> some_data) { ... }
as it will notice errors and the end of the file at the correct time and act accordingly.

How to get the number of columns of a csv file?

I have a huge csv file that I want to load with matlab. However, I'm only interested in specific columns that I know the name.
As a first step, I would like to just check how many columns the csv file has. How can I do that with matlab?
As Jonesy and erelender suggest, I would think this will do it:
fid=fopen(filename);
tline = fgetl(fid);
fclose(fid);
length(find(tline==','))+1
Since you don't seem to know what kind of carriage return character (or character encoding?) is being used then I would suggest progressively sampling your file until you encounter a recognizable CR character. One way to do this is to loop over something like
A = fscanf(fileID, ['%' num2str(N) 'c'], sizeA);
where N is the number of characters to read. At each iteration test A for presence of carriage return characters, stop if one is encountered. Once you know where the carriage return is just repeat with the right N and perform the length(find...) operation, or alternately accumulate the number of commas at each iteration. You may want to check that your file is being read along rows (is it always?), check a few samples to make sure it is.
1-) Read the first line of file
2-) Count the number of commas, or seperator characters if it is not comma
3-) Add 1 to the count and the result is the number of columns in the file.
If the csv has only numeric value you can use:
M=csvread('file_name.csv');
[row,col]=size(M);