简体   繁体   中英

Sort Tuples Row-Wise and Column-Wise

I've got a bunch of tuples that I want to insert into a 2D matrix according to the following rules:

  1. A tuple can go to the right of of another tuple (in the same row) if the first element of the tuple is greater than or equal to the first element in the previous tuple.
  2. A tuple can go under a tuple (in the same column) if the second element in the tuple is greater than or equal to the second element in the previous tuple.

This is an example of an acceptable solution:

(1,2) (2,1) (4,5)  
(8,6) (9,2) (9,8)

In other words, column-wise the tuples are sorted by the second element in the tuple and the row-wise by the first element. I realise that these rules can't always be 100% satisfied but I need to think of an algorithm that minimises the number of violations of the rules.

Thanks in advance.

We can definitely avoid either row or column violations completely, but simultaneously avoiding both depends on courtesy of data and not algorithm .

Here is what I came up with.

Let us assume a 2-d array of dimensions nX2n.

Step 1 :Sort all the tuples based on first element,lets call it TUP_1.

Step 2 :Sort all the tuples based on second element,lets call it TUP_2.

Step 3 :

i=0
while(i<n)
{
 Pick first n tuples(unmarked) from TUP_2 which are at Positions a,b,c......
 in TUP_1 such that a < b < c and so on.

 Mark the picked tuples.     

 fill the ith row with:
 first element from tuples in even positions.
 second element from tuples in odd positions.
 increment i.
}

Note :The above algorithm due to the condition

 a < b < c would always avoid any violation in row.

However, it would completely avoid the column violation if

 the elements from TUP_2 are always picked in order without any skipping.

If they are not, then there are chances that column violations can occur.

Example :Let us assume 3X4 matrix

Let the input contain following tuples.

(12,6) (12,1) (2,1) (11,1) (8,6) and (4,5).

Sorting, the tuples based on first element will give TUP_1

(2,1) (4,5) (8,6) (11,1) (12,1) and (12,6).

Sorting the tuples based on second element will give TUP_2

(2,1) (11,1) (12,1) (4,5) (8,6) (12,6).

Now performing step 3

(2,1) and (11,1) get picked up from TUP_2 because the tuples are at position
1 and 4 in TUP_1 and 1 < 4 and first row is filled as.

(2,1),(11,1)

(12,1) and (12,6) get picked up from TUP_2 because the tuples are at position
5 and 6 in TUP_1 and 5 < 6 and second row is filled as.

(12,1),(12,6)

(4,5) and (8,6) get picked up from TUP_2 because the tuples are at position
2 and 3 in TUP_1 and 2 < 3 and third row is filled as.

(4,5),(8,6)

Hence, the 3X4 matrix is:

(2,1),(11,1)
(12,1),(12,6)
(4,5),(8,6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM