Ok, after understanding the question, the algorithm I can think of is the next.
- Open the file
- Read a line from that file
- If you're in the first row ->
3.1 Create a file for the column being read
- Read a number from the current line
- Store it in its corresponding file
- Continue until you finish the dump, this would leave your with
N
files, each one representing a column
- Now, from all the files you have created:
- Read each file
- Write the content of that file as a regular row in the output file.
Something like the following:
file = File.open(myFile)
columns = File[] // columns is a file array, each one will contain a column from the original file
for each line in file
numbersInThatLine : Integer[]
numbersInThatLine = parseArrayFrom( line ) // created an array of int's from the given line
writeArraryToFiles( array=numbersInThatLine, files=columns ) // write each number in a separate file
end
close( file )
output = File.new()
for each file in columns
output.write( file )
end
close( output )
So, if your file has
1 2 3 4
5 6 7 8
9 10 11 12
You will open 4 files and in the first pass you'll have
file0 = 1
file1 = 2
file2 = 3
file3 = 4
In the second pass you will have:
file0 = 1 5
file1 = 2 6
file2 = 3 7
file3 = 4 8
And finally:
file0 = 1 5 9
file1 = 2 6 10
file2 = 3 7 11
file3 = 4 8 12
Finally by writing each file to the output file you'll have
1 5 9 // from file0
2 6 10 // from file1
3 7 11 // from file2
4 8 12 // from file3
Which is ( if I understood correctly this time ) what you need.
Good luck!
So the file containing:
1 2 3 4
5 6 7 8
9 10 11 12
Would represent the matrix:
[[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]]
??
Do the following:
- Open the file
- Read each line
- Parse the elements
- Store them in the array.
Something like the following:
List<Integer[]> matrix = new ArrayList<Integer[]>();
List<Integer> currentRow;
BufferedReader reader = new BufferedReader( yourFile );
String line = null;
while((line = reader.readLine()) != null ) {
Scanner scanner = new Scanner( line );
currentRow = new ArrayList<Integer>();
while( scanner.hasNextInt()){
currentRow.add( scanner.nextInt() );
}
matrix.add( convertListToArray( currentRow )); // See: http://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java
}
Note: I didn't even compile the above code, so it may not work