views:

53

answers:

3

I have 2 lists that have dates and data. Each list is in the proper order as noted by the sequence number. Now I need to merge the 2 lists together and keep everything in the correct order.

For example:

List A
20101001 A data 1 seq1
20101001 A data 2 seq2
20101005 A data 3 seq3

List B
20101001 B data 1 seq1
20101003 B data 2 seq2

etc...

I need the new list to look like this:
20101001 A data 1 seq1
20101001 A data 2 seq2
20101001 B data 1 seq3
20101003 B data 2 seq4
20101005 A data 3 seq5

2 things that I thought of is merging the lists together and applying the sequence number prior to inserting them into a db or I can insert them into the db with the current sequence and pull them back out again to merge them together, but that seems like an extra step and kludgy.

Any ideas on the best way to go about this?

Thanks!!!!!

+1  A: 

Assuming your lists are in Ruby Arrays, and the objects in the lists have attributes defined (such as obj.sequence_number), one way to merge and sort the lists would be:

First merge the lists as a union:

@merged_list = @list_a | @list_b

Then sort the merged_list with the appropriate sorting rule:

@merged_list.sort! {|a, b| a.date <=> b.date # or whatever your sorting rule is... }

Edit:

Once the merged array is sorted, you can re-define the sequence_number:

@merged_list.each_with_index {|obj, index| obj.sequence_number = "seq#{index+1}"}

Edit:

Same thing applies if your objects in the lists are themselves just simple arrays:

@merged_list.sort! {|a, b| a[0] <=> b[0] # or whatever your sorting rule is... }
@merged_list.each_with_index {|obj, index| obj[2] = "seq#{index+1}"}
Dave Sims
A: 

To sort array by several fields, you can apply .sort{|a,b| after merging in such way:

> m = Array.new(10){ [rand(10),rand(10),rand(10)] }
=> [[1, 8, 3], [9, 5, 8], [6, 9, 2], [6, 3, 3], [4, 6, 4], [2, 6, 4], [6, 1, 5], [3, 6, 4], [8, 0, 9], [0, 4, 3]]

> m.sort{ |a,b| (0!=e0=a[0]<=>b[0]) ? e0 : (0!=e1=a[1]<=>b[1]) ? e1 : (a[2]<=>b[2]) }
=> [[0, 4, 3], [1, 8, 3], [2, 6, 4], [3, 6, 4], [4, 6, 4], [6, 1, 5], [6, 3, 3], [6, 9, 2], [8, 0, 9], [9, 5, 8]]

It means: if a[0]==b[0], then check a[1] and b[1]; if they are equal, check a[2] and b[2];........

Nakilon
A: 

Try this:

(listA + listB).sort!{|a, b| a.sequence_no <=> b.sequence_no}
KandadaBoggu