0
votes

If you have a kind of matrix (or list of rows with different sizes) with a random number of random elements in each row how would you rearrange the matrix such that the same elements appear in the same column?

Every row has at least one element/column but different rows can have different numbers of elements/colums. Every element appears at most once per row.

For example:

a|c
a|b|c
c|e
a|d|e
b|d

should afterwards look like this:

a| |c| | 
a|b|c| | 
 | |c| |e
a| | |d|e
 |b| |d|

What would be an efficient algorithm?

EDIT: This was just a simple example, any positive number of colums and positive number of elements per column should be covered.

Elements do not have to keep their original column but should appear in minimal distance to their original column in the resulting matrix. Every element x that appears before element y in the input must also appear before y in the output. Sorry, this is an important constraint I didn't originally add which isn't generally covered by the otherwise good solution provided by user1734710.

1
could you provide a more complex example with corner-cases? or is it really this simple? five different letters, five columns. end of storyKaroly Horvath
do elements have to keep their original column?UmNyobe

1 Answers

1
votes
  1. Copy all the elements in one long vector v
  2. Sort v and remove duplicates
  3. Allocate a matrix m of size n_rows x v.size()
  4. For each element e in each row r, look up the position i of e in v and store e in m[r, i]