An elegant way

On Tue, Sep 21, 2010 at 1:10 AM, F. Senault [email protected] wrote:

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…

[email protected]:~/ruby
$ irb

a=[ ‘1’, ‘2’, ‘3’, ‘4’, ‘6’, ‘7’, ‘9’, ‘S1’, ‘S2’]
=> [“1”, “2”, “3”, “4”, “6”, “7”, “9”, “S1”, “S2”]

?> c=[ [prev=a[0]] ]
=> [[“1”]]

?> a[1…-1].each do |e|
?> if (prev.class == e.class) && (prev.succ == e)

c.last << e

else
?> c << [e]

end

?> prev=e

end
=> [“2”, “3”, “4”, “6”, “7”, “9”, “S1”, “S2”]

?> p c
[[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]
=> [[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]

?>

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

?>
?> c =
?> a[1…-1].inject([[prev=a[0]]]) do |b,e|
?> if (prev.class == e.class) && (prev.succ == e)

b.last << e

else
?> b << [e]

end
prev=e
b
end
=> [[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]

?> p c
[[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]
=> [[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]

hth.

best regards -botp

Le 20 septembre à 19:09, F. Senault a écrit :

Hello everybody.

Right. I’ve written a sligthly better version in my project.

All answers given were very interesting and fun…

Tanks a lot everyone !

Fred

unsubscribe

(\ /)
(O.o)
(> <)

This is Bunny. Copy Bunny into your signature to help him on his way to
world domination.


From: botp [email protected]
To: ruby-talk ML [email protected]
Sent: Tue, September 21, 2010 6:47:37 PM
Subject: Re: An elegant way…

On Tue, Sep 21, 2010 at 1:10 AM, F. Senault [email protected] wrote:

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…

[email protected]:~/ruby
$ irb

a=[ ‘1’, ‘2’, ‘3’, ‘4’, ‘6’, ‘7’, ‘9’, ‘S1’, ‘S2’]
=> [“1”, “2”, “3”, “4”, “6”, “7”, “9”, “S1”, “S2”]

?> c=[ [prev=a[0]] ]
=> [[“1”]]

?> a[1…-1].each do |e|
?> if (prev.class == e.class) && (prev.succ == e)

c.last << e

else
?> c << [e]

end

?> prev=e

end
=> [“2”, “3”, “4”, “6”, “7”, “9”, “S1”, “S2”]

?> p c
[[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]
=> [[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]

?>

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

?>
?> c =
?> a[1…-1].inject([[prev=a[0]]]) do |b,e|
?> if (prev.class == e.class) && (prev.succ == e)

b.last << e

else
?> b << [e]

end
prev=e
b
end
=> [[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]

?> p c
[[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]
=> [[“1”, “2”, “3”, “4”], [“6”, “7”], [“9”], [“S1”, “S2”]]

hth.

best regards -botp

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs