Efficient list rotation

5 messages
Open this post in threaded view
|

Efficient list rotation

 Folks, Is there a more efficient version of this code? I understand that it's better to append to the head of the list and reverse afterwards but appending to the tail works with the logic of the task. I'm trying to rotate the list so that a particular item is at the tail of the list, that is if I rotate the list once more it will be at the head. As a bit of background info, I need this for my poker logic as when a player makes a bet I rotate the list and place them at the tail. I might delete them right after or I might not. -module(bar). -compile([export_all]). rotate(_Target, []) ->     []; rotate(Target, [H|T]) ->     rotate(Target, [H|T], none). rotate(Target, [H|T], none) when Target =:= H ->     rotate(Target, T, H); rotate(Target, [H|T], none) ->     rotate(Target, T ++ [H], none); rotate(_Target, [], X) ->     [X]; rotate(_Target, [H|T], X) ->     [H|T] ++ [X].     Thanks, Joel -- http://wagerlabs.com/tech
Open this post in threaded view
|

Efficient list rotation

 Hi Joel, The problem is to move the first element of the list to the end? Here's a simple way:   move_first_to_last([H|T]) -> T++[H]. The list would be representing a queue. There is also a queue data structure in OTP ('queue' module) which is quite a cute, I remember stepping through the algorithm with billiard balls when I was learning Erlang :-). For your purposes a plain ol' list sounds fine. Or do you really need to move the Nth element to the tail instead?
Open this post in threaded view
|

Efficient list rotation

 In reply to this post by Joel Reymont-2 Have a look at the module 'queue'. It implements a FIFO queue, which can be used as a rotatable list. joelr1 (Joel Reymont) writes: > Folks, > > Is there a more efficient version of this code? I understand that it's > better to append to the head of the list and reverse afterwards but > appending to the tail works with the logic of the task. > > I'm trying to rotate the list so that a particular item is at the tail of > the list, that is if I rotate the list once more it will be at the head. > > As a bit of background info, I need this for my poker logic as when a > player makes a bet I rotate the list and place them at the tail. I might > delete them right after or I might not. > > -module(bar). > -compile([export_all]). > > rotate(_Target, []) -> >     []; > > rotate(Target, [H|T]) -> >     rotate(Target, [H|T], none). > > rotate(Target, [H|T], none) when Target =:= H -> >     rotate(Target, T, H); > > rotate(Target, [H|T], none) -> >     rotate(Target, T ++ [H], none); > > rotate(_Target, [], X) -> >     [X]; > > rotate(_Target, [H|T], X) -> >     [H|T] ++ [X]. > >     Thanks, Joel > > -- > http://wagerlabs.com/tech> > -- / Raimo Niskanen, Erlang/OTP, Ericsson AB