Reputation: 222
I need to sort columns based on first row. Can anyone help me in achieve this for example. Basically I have a csv.
I have a matrix like:-
B, C, D, E, A
1, 11, 12, 23, 67
111, 112, 114, 118, 200
I want this matrix to be sorted using row 1, so A should come at first and so the same columns in other rows.
A, B, C, D, E
67, 1, 11, 12, 23
200, 111, 112, 114, 118
CSV Input:- B,C,D,E,A\n1,11,12,23,67\n,111,112,114,118,200
CSV Output:- A,B,C,D,E\n67,1,11,12,23\n,200,111,112,114,118
Can someone help me or guide me how to achieve the same.
Upvotes: 1
Views: 119
Reputation: 29680
Because you haven't provided us with any of your code, I won't be able to do more than explain one solution. Assume you have the following matrix, which can potentially be stored in an Object[][]
where Object
is the type of whatever you're concerned with:
Object[][] = [
[B, C, D, E, A ],
[1, 11, 12, 23, 67 ],
[111, 112, 114, 118, 200]
]
You can now take the transpose of the matrix, which results in the following:
Object[][] = [
[B, 1, 111],
[C, 11, 112],
[D, 12, 114],
[E, 23, 118],
[A, 67, 200]
]
Now, simply sort this matrix by the first element of each row to produce the following:
Object[][] = [
[A, 67, 200],
[B, 1, 111],
[C, 11, 112],
[D, 12, 114],
[E, 23, 118]
]
Finally, if you would like it back in its original form, take the transpose once again:
Object[][] = [
[A, B, C, D, E ],
[67, 1, 11, 12, 23 ],
[200, 111, 112, 114, 118]
]
If you provide us with some of your code showing us how you store the data contained in the CSV, then I can help you write the code.
Upvotes: 2