http://rosettacode.org/wiki/Perfect_shuffle#J

Update of my direct implementation: This tacit version runs in 15 minutes, depending. It maintains a boxed vector of the count and shuffling state. Furthermore, the Change adverb together with a named index makes the program feel like modern code rather than 1950 FORTRAN code having all variables as indexes into a single array; "a(17) is the loop counter". Next incantation of Change would be a ``parallel'' version accepting a gerund to work with an array of indexes. The explicit version is still a great deal faster.

Until=: 2 :'u^:(0-:v)^:_'

shuffle=: [: , [: |: ([\~ (0 _0.5 p. #))

Change=: (&.>)(@:{)(`[)(`])}  NB. INDEX verb Change BOXED_DATA
'example'assert 0 1 2 3 8 5 6 7 (-: ;) 4+:Change;/i.8
'serial changes'assert'0 1 _2 3 ABC5 6 7 '-:,":&>(2&(-Change))@:(4&('ABC'"_ Change));/i.8

COUNT=:0
SHUFFLE_STATE=:1

so=: 1&((([: shuffle f. {)`[`])}) NB. shuffle once: advance the shuffled state
inc=: >:

css=: SHUFFLE_STATE&(so f. Change)       NB. change the shuffled state
count=: COUNT&(inc f. Change)            NB. well....count

shuffles=: COUNT {:: [: count@:css f.Until([:-:/SHUFFLE_STATE&{::) 1 ; (,:shuffle)

NB. Use:

   timespacex'COUNTS =: (,:shuffles@i.&>) >:@:i.&.-: 10000'
782.185 4.49293e6
   >./"1 COUNTS
10000 9948



>From: Raul Miller <[email protected]>
>To: Programming forum <[email protected]>
>Subject: Re: [Jprogramming] perfect shuffle rosetta code
>Message-ID:
> <cad2jou-em_hdvf1dnf_qy33yc-_emwnewifr7+abibqxv32...@mail.gmail.com>
>Content-Type: text/plain; charset=UTF-8
>
>This "perfect shuffle" algorithm can be implemented as:
>   shuf=: /: $ /:@$ 0 1"_
>
>The number of iterations needed to cycle back to the start for a
>permutation of length n is:
>   *./#@>C.shuf i.n
>
>I'll update the rosettacode page with these details after it comes back up.
>
>Thanks,
>

*./#@>C.shuf i.n is non-obvious to me, especially since I haven't spent much time with C. Quite nice.

>Date: Mon, 15 Jun 2015 12:44:49 -0400
>From: Raul Miller <[email protected]>
>To: Programming forum <[email protected]>
>Subject: Re: [Jprogramming] perfect shuffle rosetta code
>Message-ID:
> <CAD2jOU_sgBS=hn6w8h3vnh2+kuwknpfn363cmgg9fyknbfv...@mail.gmail.com>
>Content-Type: text/plain; charset=UTF-8
>
>Actually, it looks like the only problem with the site was that
>posting a 21k long line of text fails.
>
>That said, when I compare my result with the result you displayed,
>I've decided I don't understand what you are posting for cycle
>lengths.
>
>Can you clarify?

The page is now hidden in the RC historical archives. The output shape was probably 2 by n to consume horizontal space. I might have mistakenly displayed transposed stitch. One row showed the deck size, and in the corresponding column the perfect shuffle count to restore the deck.
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to