Create file file1 with the following values 3 4 35 20 43 17
Solution
Please follow the code and comments for description :
CODE :
// required imports for the code to run
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
// class to run the code
public class Transpose
{
// driver method
public static void main(String[] args)
{
// required readers and writers
BufferedReader br = null;
FileReader fr = null;
BufferedWriter bw = null;
FileWriter fw = null;
try
{
// code to read the data
System.out.println(\"Reading the Data...\");
fr = new FileReader(\"file1.txt\");
br = new BufferedReader(fr);
// local variables
int lineCount = 0, r = 0, c = 0, i = 0;
int arr[][] = null;
int arr1[][] = null;
String sCurrentLine;
// read the data till the EOF
while ((sCurrentLine = br.readLine()) != null)
{
lineCount++;
String tokens[] = sCurrentLine.split(\" \");
// based on the rows and columns create and assign the data
if (lineCount == 1)
{
int[] array = Arrays.stream(tokens).mapToInt(Integer::parseInt).toArray();
r = array[0];
c = array[1];
arr = new int[r][c];
} else
{
for (int j = 0; j < c; j++)
{
arr[i][j] = Integer.parseInt(tokens[j]); // parse the data
}
i++; // increment the count
}
}
// method call to get the data transposed
arr1 = rcConvert(arr, r, c);
// file write objects
System.out.println(\"Writing the data...\");
fw = new FileWriter(\"file2.txt\");
bw = new BufferedWriter(fw);
for (int x = 0; x < c; x++)
{
for (int y = 0; y < r; y++)
{
bw.write(arr1[x][y] + \"\\t\"); // write the data
}
bw.write(\"\ \");
}
// end data message
System.out.println(\"Done\");
} catch (IOException e) // catch the exceptions if any
{
e.printStackTrace();
} finally
{
try
{
// close all the instances
if (br != null)
{
br.close();
}
if (fr != null)
{
fr.close();
}
if (bw != null)
{
bw.close();
}
if (fw != null)
{
fw.close();
}
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
// method that transposes the matrix and returns the data
private static int[][] rcConvert(int array[][], int rows, int columns)
{
int trArr[][] = new int[columns][rows];
for (int c = 0; c < rows; c++)
{
for (int d = 0; d < columns; d++)
{
trArr[d][c] = array[c][d];
}
}
return trArr;
}
}
OUTPUT :
Reading the Data...
Writing the data...
Done
file1.txt :
3 4
35 20 -43 17
-10 6 7 -2
13 1 2 3
file2.txt :
35 -10 13
20 6 1
-43 7 2
17 -2 3
Hope this is helpful.


