[erlang-questions] Matrix rotator

Johnny Billquist bqt@REDACTED
Mon Jun 15 02:45:46 CEST 2009


Oh, and if you don't mind not being able to do tail recursion 
optimization, you can do it like this:

rotate2([]) ->
     [];
rotate2(L = [H|_]) ->
     rotate2(length(H),L).

rotate2(0,_) ->
     [];
rotate2(N,L) ->
     [extract2(N,L)|rotate2(N-1,L)].

extract2(_,[]) ->
     [];
extract2(N,[H|T]) ->
     [lists:nth(N,H)|extract2(N,T)].


Which I think is much prettier.

	Johnny

Johnny Billquist wrote:
> Tony Arcieri wrote:
>> On Sun, Jun 14, 2009 at 2:08 PM, Johnny Billquist <bqt@REDACTED 
>> <mailto:bqt@REDACTED>> wrote:
>>
>>     The problem is rather trivial in itself. Are you looking for some
>>     particularly efficient algorithm, or what?
>>
>>
>> Whatever you'd like, but creative or clever solutions are always 
>> interesting.
> 
> Ok. A really trivial solution then:
> 
> -----------------
> rotate([]) ->
>     [];
> rotate(L = [H|_]) ->
>     rotate(length(H),L,[]).
> 
> rotate(0,_,R) ->
>     lists:reverse(R);
> rotate(N,L,R) ->
>     rotate(N-1,L,[extract(N,L,[])|R]).
> 
> extract(_,[],R) ->
>     lists:reverse(R);
> extract(N,[H|T],R) ->
>     extract(N,T,[lists:nth(N,H)|R]).
> ------------------
> 
> 
> And an example run:
> 
> 17> test:rotate([[a,b,c],[d,e,f]]).
> [[c,f],[b,e],[a,d]]
> 18>
> 
>     Johnny
> 
> 


-- 
Johnny Billquist                  || "I'm on a bus
                                   ||  on a psychedelic trip
email: bqt@REDACTED             ||  Reading murder books
pdp is alive!                     ||  tryin' to stay hip" - B. Idol


More information about the erlang-questions mailing list