Saturday, March 26, 2011

Consecutive Groups of Integers


Divide a list of numbers into group of consecutive numbers but their original order should be preserved?
e.g.
8,2,4,7,1,0,3,6
2,4,1,0,3 and 8,7,6

Approach:

we can use a technique called "index sorting", C#, Java, etc. all have overloads of the sort call which can tandem sort two arrays. So essentially you have two arrays

int[] numbers = {2, 9, 0, 7, 3, 8, 1, 6} or whatever
int[] indices = {0, 1, 2, 3, 4, 5, 6, 7}

sort indices and numbers by the elements in numbers.

numbers = {0, 1, 2, 3, 6, 7, 8, 9}
indices = {2, 6, 0, 4, 7, 3, 5, 1}

Then divide numbers/indices into consecutive groups.

Re-Sort numbers/indices but sort by indices. Then just walk through numbers printing out the values.



Sample Input:
8 6 4 2 0 4 1 3

Sample output:
Printing Map::
2 -> 4
3 -> 2
4 -> 0
5 -> 4
6 -> 1
7 -> 3

Printing Map::
1 -> 6

Printing Map::
0 -> 8

No comments:

Post a Comment