You are not logged in.

#1 2007-06-07 19:14:49

hypermegachi
Member
Registered: 2004-07-25
Posts: 311

algorithm to group sequential numbers

i'm stuck....brain is in mush state sad
i'm starting to brute force it, and i thought maybe some of you guys might have an elegant solution.

given a list of numbers; 1,2,3,4,5,6,7,8,9
this will return a single array of [1,2,3,4,5,6,7,8,9]

given this list; 1,2,5,6,7
will return [1,2],[5,6,7]

likewise, this list; 1,2,4,6,8,9
should return [1,2],[4],[6],[8,9]

get the pattern?  basically group sequential numbers together.  i just started and the only way i can think of doing it is very ugly involving lots of forward and backward comparisons with a lot of collections to keep track of stuff sad

Offline

#2 2007-06-07 19:35:42

Ramses de Norre
Member
From: Leuven - Belgium
Registered: 2007-03-27
Posts: 1,289

Re: algorithm to group sequential numbers

Will they always be sorted ascending like your examples?

Offline

#3 2007-06-07 20:40:38

hypermegachi
Member
Registered: 2004-07-25
Posts: 311

Re: algorithm to group sequential numbers

yes.  i figured it out.

here's the basic pseudo code:

List[List[int]] sections = new;
List[int] current = new;

foreach (number in list) {
  current.Add(number)
  if not adjacent(number, next number) {
    sections.Add(current)
    current = new
  }
}
current.Add(list number in list)
sections.Add(current)

Offline

Board footer

Powered by FluxBB