On Tue, Sep 21, 2010 at 1:10 AM, F. Senault <fred / lacave.net> wrote:
> The method takes one argument, an array containing a sorted list of
> strings representing episodes numbers. =A0The episodes numbers are either
> a number ('1', '12') or prefixed with a letter ('S1' for special 1). =A0M=
y
> goal is to find sequences in the numbers and join them with dashes :
>
>>> RAniDBTools.format_episodes_list([ '1', '2', '3', '4', '6', '7', '9', '=
S1', 'S2' ])
> =3D> "1-4, 6-7, 9, S1-S2"
>>> RAniDBTools.format_episodes_list([ '1', '2', 'S3', 'S4', 'S5', 'O6' ])
> =3D> "1-2, S3-S5, O6"
>
> Here's the code ; what can I do to improve this ?

as always, we start as simple as possible,..  walking one element at a time=
...


botp@bg-mis-u10:~/ruby
$ irb
>> a=3D[ '1', '2', '3', '4', '6', '7', '9', 'S1', 'S2']
=3D> ["1", "2", "3", "4", "6", "7", "9", "S1", "S2"]
>>
?> c=3D[ [prev=3Da[0]] ]
=3D> [["1"]]
>>
?> a[1..-1].each do |e|
?>   if (prev.class =3D=3D e.class) && (prev.succ =3D=3D e)
>>     c.last << e
>>   else
?>     c << [e]
>>   end
>>
?>   prev=3De
>> end
=3D> ["2", "3", "4", "6", "7", "9", "S1", "S2"]
>>
?> p c
[["1", "2", "3", "4"], ["6", "7"], ["9"], ["S1", "S2"]]
=3D> [["1", "2", "3", "4"], ["6", "7"], ["9"], ["S1", "S2"]]
>>
?>

but  _that algo  is clamoring for inject/reduce (and robertk is
watching :) ...  so,

?>
?> c =3D
?> a[1..-1].inject([[prev=3Da[0]]]) do |b,e|
?>   if (prev.class =3D=3D e.class) && (prev.succ =3D=3D e)
>>     b.last << e
>>   else
?>     b << [e]
>>   end
>>   prev=3De
>>   b
>> end
=3D> [["1", "2", "3", "4"], ["6", "7"], ["9"], ["S1", "S2"]]
>>
?> p c
[["1", "2", "3", "4"], ["6", "7"], ["9"], ["S1", "S2"]]
=3D> [["1", "2", "3", "4"], ["6", "7"], ["9"], ["S1", "S2"]]
>>

hth.

best regards -botp