[Jprogramming] Memoizing (Project Euler problem 14)

Roger Stokes rs at rogerstokes.free-online.co.uk
Thu Aug 7 10:02:52 UTC 2014


Dear All,

I've come across a puzzle
and would be glad if someone could explain it.

In a few words, I have a variation of collatzv which is a one-liner
  (c1 below) and the very same verb spread over several lines (c2 below).
The second is nearly twice as fast as the first.  How come?

The timings I get are

  collatzv T          0.0592513

  c1 T NB. one-liner  0.0582203

  c2 T NB. spread out 0.0352435

where T is  2 + i. 1e6

What follows is transcript of session producing these results.

Starting with Roger Hui's original collatzv:


    collatzv =: 3 : '<. (2|y)} 0 1 + 0.5 3 */y'

    NB. here is my one-liner, an experiment intended to stick to
    NB. integer arithmetic throughout.

    c1 =: 3 : '(_1 & (33 b.)) (2 | y) }  y ,: (2 + 6 * y)'

    NB. here is a spread-out version

    c2 =: 3 : 0
   a =. 2 | y
   b =. 2 + 6 * y
   c =. a } y ,: b
   (_1 & (33 b.)) c
)

    (collatzv -: c1) T =: 2 + i. 1e6
1
    (collatzv -: c2) T
1

    NB. comparing timings:

    compare =: (; (6!:2)) @: > "0
    compare 'collatzv T '; 'c1 T NB. one-liner '; 'c2 T NB. spread out'

  collatzv T          0.0587746

  c1 T NB. one-liner  0.0579726

  c2 T NB. spread out 0.0340378


    NB. Do we get the same effect by spreading collatzv?  No.

    collatzvs =: 3 : 0
   a =. 0 1 + 0.5 3 */y
   b =. 2|y
   c =: b } a
   <. c
)

    (collatzv -: collatzvs) T
1

    compare  'collatzv T '; 'c1 T '; 'c2 T '; 'collatzvs T '

  collatzv T   0.0591852

  c1 T         0.0594112

  c2 T         0.034516

  collatzvs T  0.0597546


    JVERSION
Engine: j701/2011-01-10/11:25
Library: 8.02.10
Qt IDE: 1.1.3/5.3.0
Platform: Win 64
Installer: J802 install
InstallPath: c:/users/homer/j64-802

 


More information about the Programming mailing list