Open Source / Collaboration

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bill Marsden

    #1

    Open Source / Collaboration

    Hi. I am an under-graduate currently studying Open Source (Linux) vs Closed
    Source and Collaboration within the IT Community. I am fairly new to
    Javascript and I have written a "Lottery Program" which essentially picks 6
    numbers at random and puts them in sequence.

    Would anyone would be interested in modifying the code below to

    a). Check for bugs
    b). Make the program more efficient

    My idea is to see the response to this so as to make a comparison to
    developers and the Open Source Movement.

    Thanks

    <HTML>

    <HEAD>

    <TITLE> Program_7.2.1 First Program

    </TITLE>

    <SCRIPT LANGUAGE = "JavaScript ">



    /*************** *************** ***/

    /* */

    /* Lottery Program */

    /* Author: Bill Marsden */

    /* Date: 17/05/2004 */

    /* */

    /*************** *************** ***/



    // Define Variables



    var lott_one;

    var lott_two;

    var lott_three;

    var lott_four;

    var lott_five;

    var lott_six;

    var sort_numbers;

    var another_go;



    another_go = 'YES'





    while (another_go == 'YES')

    {



    // Load the balls! Our adjudicator tonight is Bill Marsden !



    lott_one = Math.floor(Math .random()*50+1) ;

    lott_two = Math.floor(Math .random()*50+1) ;



    // Main body of program testing for unique numbers





    if (lott_two == lott_one)

    {

    lott_two = Math.floor(Math .random()*50+1)

    }

    ;



    lott_three = Math.floor(Math .random()*50+1) ;

    if (lott_three == lott_two || lott_three == lott_one)

    {

    lott_three = Math.floor(Math .random()*50+1)

    }

    ;



    lott_four = Math.floor(Math .random()*50+1) ;

    if (lott_four == lott_three || lott_four == lott_two || lott_four ==
    lott_one)

    {

    lott_four = Math.floor(Math .random()*50+1)

    }

    ;

    lott_five = Math.floor(Math .random()*50+1) ;



    if (lott_five == lott_four || lott_five == lott_three ||

    lott_five == lott_two || lott_five == lott_one)

    {

    lott_five = Math.floor(Math .random()*50+1)

    }

    ;



    lott_six = Math.floor(Math .random()*50+1) ;



    if (lott_six == lott_five || lott_six == lott_four ||

    lott_six == lott_three || lott_six == lott_two || lott_six ==
    lott_one)

    {

    lott_six = Math.floor(Math .random(1)*50+1 )

    }

    ;



    // We have our selection, lets sort them in ascending order



    sort_numbers = [lott_one , lott_two , lott_three , lott_four , lott_five ,
    lott_six]

    function sortNumbers(a, b) { return a - b}



    // Are you a lucky winner? Check the output!





    document.write( 'And this weeks winning numbers are:' + '<BR>'

    + sort_numbers.so rt(sortNumbers) + '<BR>' + '<BR>' ) ;



    another_go = window.prompt(' Another go? Enter YES/NO' , '') ;



    }

    ;



    </SCRIPT>

    </HEAD>

    <BODY>

    </BODY>

    </HTML>





  • Lee

    #2
    Re: Open Source / Collaboration

    Bill Marsden said:[color=blue]
    >
    >Hi. I am an under-graduate currently studying Open Source (Linux) vs Closed
    >Source and Collaboration within the IT Community. I am fairly new to
    >Javascript and I have written a "Lottery Program" which essentially picks 6
    >numbers at random and puts them in sequence.
    >
    >Would anyone would be interested in modifying the code below to
    >
    >a). Check for bugs
    >b). Make the program more efficient
    >
    >My idea is to see the response to this so as to make a comparison to
    >developers and the Open Source Movement.[/color]

    I can't help but suspect that your idea is to get somebody
    else to do your homework assignment.

    1. Your code is hard to read.
    In my newsreader it's double-spaced.
    There are extraneous semi-colons on lines by themselves.

    2. You should use an array, instead of lott_one, lott_two, etc.

    3. Your algorithm allows duplicate numbers.

    if (lott_two == lott_one)
    {
    lott_two = Math.floor(Math .random()*50+1)
    }
    // lott_two can still be the same as lott_one

    4. You don't allow the page to ever finish loading,
    which is the only reason you can get away with
    using document.write( ) more than once. That may
    be ok for a very simple case, but it's questionable.


    There are other things that I would do differently,
    but you probably haven't covered them, yet.
    Reading the newsgroup's FAQ before posting is always
    a good idea. I believe it contains a link to a page
    that has an efficient function for returning random
    numbers without repetition.

    The link to "Dealing and Shuffling".

    Comment

    • Richard Cornford

      #3
      Re: Open Source / Collaboration

      Bill Marsden wrote:[color=blue]
      > Hi. I am an under-graduate currently studying Open Source (Linux)
      > vs Closed Source and Collaboration within the IT Community.[/color]

      Either that or you are a student trying to find a credible excuse for
      getting help with your programming homework (it is that time of year
      again :)
      [color=blue]
      > I am fairly new to Javascript and I have written
      > a "Lottery Program" which essentially picks 6 numbers
      > at random and puts them in sequence.[/color]

      That certainly sounds like a programming exercise. It certainly isn't
      something that you would write for the benefit of humanity.
      [color=blue]
      > Would anyone would be interested in modifying the code below to[/color]

      The best modification is to delete it and start again.
      [color=blue]
      > a). Check for bugs
      > b). Make the program more efficient
      >
      > My idea is to see the response to this so as to make a
      > comparison to developers and the Open Source Movement.[/color]

      If that is your real reason I don't see how you could learn anything
      useful from this exercise.

      <snip>[color=blue]
      > <SCRIPT LANGUAGE = "JavaScript ">[/color]

      The language attribute is deprecated in HTML 4.01 and the type attribute
      is required:-

      <SCRIPT type="text/javascript">

      <snip>[color=blue]
      > // Define Variables
      > var lott_one;
      > var lott_two;
      > var lott_three;
      > var lott_four;
      > var lott_five;
      > var lott_six;[/color]

      Six variables with numeric suffixes makes it look like you probably want
      to be using an Array instead.

      <snip>[color=blue]
      > another_go = 'YES'[/color]

      another_go looks like it should be boolean. Generally, if a variable is
      only going to have two states it should be boolean. In this case the two
      states are "YES" and NOT "YES", they should be true and false.
      [color=blue]
      > while (another_go == 'YES')[/color]

      if - another_go - had been boolean you would not need to be doing a
      relatively heavyweight string comparison in the test expression of
      your - while - loop. Instead you would use:-

      while (another_go)

      - which is considerably simpler and faster.

      <snip>[color=blue]
      > // Load the balls! Our adjudicator tonight is Bill Marsden ![/color]

      ?
      [color=blue]
      > lott_one = Math.floor(Math .random()*50+1) ;
      >
      > lott_two = Math.floor(Math .random()*50+1) ;[/color]

      Random numbers form 1 to 50 (except maybe on the buggy and old Opera 4 &
      5 browsers where they might get to 51). That is 0 to < 50 plus 1 == 1 to
      < 51, rounded down == 1 to 50.
      [color=blue]
      > // Main body of program testing for unique numbers
      > if (lott_two == lott_one)
      > {
      >
      > lott_two = Math.floor(Math .random()*50+1)
      >
      > }[/color]

      You realise that this isn't going to work properly because there is
      always a chance that the replacement - lott_two - number will be the
      same as the first and so still identical to - lott_one -?

      <snip>[color=blue]
      > if (lott_three == lott_two || lott_three == lott_one)[/color]

      A pattern is starting to emerge.

      <snip>[color=blue]
      > if (lott_six == lott_five || lott_six == lott_four ||
      >
      > lott_six == lott_three || lott_six == lott_two || lott_six ==
      > lott_one)[/color]

      Yes, this is a ludicrous thing to be doing.

      I would go into the details of why but in reality the algorithm
      implemented here is just wrong. The algorithm should be:-

      1. Create a re-orderable collection/Array of all of
      the numbers (1 to 50 in your case).
      2. Randomly shuffle that collection/Array.
      3. Pull the first 6 numbers from the front (or end),
      they should be random and they will never coincide
      with each other.

      Google for "javascript shuffle"

      <snip>

      Now the part that tells the student with a desire to have their homework
      done for them from the individual with a genuine desire; an
      implementation that no idle student could ever hope to get away with
      handing it as their own work :)

      In previous discussions of the shuffling problem I have often wondered
      whether a stack could be used instead of an array. With the items
      representing the numbers being dropped onto the stack such that they
      would fall to a randomly determined depth within the stack. I don't know
      if that would be a mathematically good shuffle but I thought it was
      about time I had a go at implementing it:-

      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
      "http://www.w3.org/TR/html4/loose.dtd">
      <html>
      <head>
      <title></title>
      <meta http-equiv="Content-Type"
      content="text/html; charset=iso-8859-1">
      <script type="text/javascript">

      var sixNumbers = (function(){
      function pull(){
      base = this.next;
      return this;
      }
      function toString(){
      return String(this.val ueOf());
      }
      function b(itm){
      itm.next = b;
      itm.index = 1;
      return itm;
      }
      function aSort(a, b){return a - b;}
      b.pull = pull;
      b.index = 0;
      b.next = b;
      b.toString = toString;
      b.valueOf = function(){retu rn '';};
      var base = b;
      var outAr = [];
      function getStackFnc(num ){
      function p(itm, index){
      if(index < p.index){
      p.next = p.next(itm, index);
      ++p.index;
      return p;
      }else{
      itm.next = p;
      itm.index = p.index + 1;
      return itm;
      }
      }
      p.pull = pull;
      p.index = NaN;
      p.next = null;
      p.valueOf = function(){retu rn num;};
      p.toString = toString;
      return p;
      }
      for(var c = 50;--c;){
      base = base(getStackFn c(c), 1);
      }
      return ({
      toString:functi on(){
      var tempBase = b;
      for(var c = outAr.length;c--;){
      base = base(outAr[c],1);
      }
      for(var c = 50;--c;){
      tempBase = tempBase(base.p ull(),
      (((Math.random( )%1)*(tempBase. index+1))|0));
      }
      base = tempBase;
      for(var c = 6;c--;){
      outAr[c] = base.pull();
      }
      return outAr.sort(aSor t).join(' ');
      }
      });
      })();

      </script>
      </head>
      <body>
      <form action="" name="f">
      <input type="button" value="Get Numbers"
      onclick="this.f orm.elements.t. value = sixNumbers;">
      <textarea cols="70" rows="10" name="t"></textarea>
      </form>
      </body>
      </html>

      The output range is 1 to 49, if you do want 1 to 50 you will have to
      change the two occurrences of 50 to 51.

      Richard.


      Comment

      • Lee

        #4
        Re: Open Source / Collaboration

        Richard Cornford said:
        [color=blue]
        >Now the part that tells the student with a desire to have their homework
        >done for them from the individual with a genuine desire; an
        >implementati on that no idle student could ever hope to get away with
        >handing it as their own work :)[/color]

        <html>
        <head>
        <script type="text/javascript">
        function lotto(m,n){
        var selected=new Array();
        var hat=new Array(m+1);
        for(while n--){
        var r=Math.floor(Ma th.random()*m+1 );
        selected.push(h at[r]?hat[r]:r);
        hat[r]=m--;
        }
        return selected.sort(n umerically);
        }
        function numerically(a,b ){return a-b}
        </script>
        </head>
        <body>
        <button onclick="this.i nnerHTML=lotto( 50,5)">go</button>
        </body>
        </html>

        Comment

        • Lee

          #5
          Re: Open Source / Collaboration

          Lee said:[color=blue]
          >
          >Richard Cornford said:
          >[color=green]
          >>Now the part that tells the student with a desire to have their homework
          >>done for them from the individual with a genuine desire; an
          >>implementatio n that no idle student could ever hope to get away with
          >>handing it as their own work :)[/color]
          >
          ><html>
          ><head>
          ><script type="text/javascript">
          > function lotto(m,n){
          > var selected=new Array();
          > var hat=new Array(m+1);
          > for(while n--){
          > var r=Math.floor(Ma th.random()*m+1 );
          > selected.push(h at[r]?hat[r]:r);
          > hat[r]=m--;
          > }
          > return selected.sort(n umerically);
          > }
          > function numerically(a,b ){return a-b}
          ></script>
          ></head>
          ><body>
          ><button onclick="this.i nnerHTML=lotto( 50,5)">go</button>
          ></body>
          ></html>[/color]


          Extra credit: find the bug.

          Comment

          • Dr John Stockton

            #6
            Re: Open Source / Collaboration

            JRS: In article <cbf1oa01hss@dr n.newsguy.com>, seen in
            news:comp.lang. javascript, Lee <REM0VElbspamtr ap@cox.net> posted at Thu,
            24 Jun 2004 10:07:22 :[color=blue]
            >Lee said:[color=green]
            >>
            >>Richard Cornford said:
            >>[color=darkred]
            >>>Now the part that tells the student with a desire to have their homework
            >>>done for them from the individual with a genuine desire; an
            >>>implementati on that no idle student could ever hope to get away with
            >>>handing it as their own work :)[/color][/color][/color]

            [color=blue][color=green]
            >> function lotto(m,n){
            >> var selected=new Array();
            >> var hat=new Array(m+1);
            >> for(while n--){
            >> var r=Math.floor(Ma th.random()*m+1 );
            >> selected.push(h at[r]?hat[r]:r);
            >> hat[r]=m--;
            >> }
            >> return selected.sort(n umerically);
            >> }
            >> function numerically(a,b ){return a-b}[/color][/color]
            [color=blue][color=green]
            >><button onclick="this.i nnerHTML=lotto( 50,5)">go</button>[/color][/color]
            [color=blue]
            >Extra credit: find the bug.[/color]

            That reminds me of a problem published in Scientific American, long ago;
            a diagram showing circles and rectangles of paper dropped on the floor,
            the question being to identify three instances of four points (a point
            being a visible corner or intersection of edges) lying on a circle.
            Four such instances could be found.

            One bug is that the required version of JS is not specified. The OP is
            apparently a UK student; he may have a nice new computer himself, but
            his institution and its staff may be impoverished.

            If I remove both the line with the amazing syntax and its mate ISTM that
            I should have script that executes (but does not satisfy the OP) in
            *your* browser; but I do not have Array.push, so it does not execute for
            me. It should be easy enough to do without Array.push.

            I have a syntax change which, combined with replacing push, seems at
            first to work; but not at second.

            If such a method works, it should work for drawing most or all of the
            balls, and that will find some errors rather quickly.

            It appears to be a method taking time proportional to the number of
            balls drawn, rather than the number available; this is good.

            I'd be pleased to put a compatible working copy on my Web page, with
            attribution.

            ISTM that the OP has one ball more than the customary 49.

            --
            © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
            <URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang. javascript
            <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
            <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

            Comment

            • Mick White

              #7
              Re: Open Source / Collaboration

              Bill Marsden wrote:
              [color=blue]
              > Hi. I am an under-graduate currently studying Open Source (Linux) vs Closed
              > Source and Collaboration within the IT Community. I am fairly new to
              > Javascript and I have written a "Lottery Program" which essentially picks 6
              > numbers at random and puts them in sequence.
              >
              > Would anyone would be interested in modifying the code below to
              >
              > a). Check for bugs
              > b). Make the program more efficient[/color]

              <snip>
              For some ideas look at:



              Good luck

              Comment

              • Lee

                #8
                Re: Open Source / Collaboration

                Dr John Stockton said:
                [color=blue]
                >I have a syntax change which, combined with replacing push, seems at
                >first to work; but not at second.
                >
                >If such a method works, it should work for drawing most or all of the
                >balls, and that will find some errors rather quickly.
                >
                >It appears to be a method taking time proportional to the number of
                >balls drawn, rather than the number available; this is good.
                >
                >I'd be pleased to put a compatible working copy on my Web page, with
                >attribution.[/color]


                The for(while) line was a typo. I changed the loop and apparently
                made the edit in the post, rather than making a fresh copy of
                tested code. I chose push() partly because it was unlikely to be
                familiar to a student and partly for brevity, knowing that it made
                the code less library worthy.

                I'm relieved that the error I caught isn't so obvious as to be
                completely humiliating. The algorithm simply doesn't work.
                I didn't test with large enough n until after I posted it.
                Then I started seeing duplicates.

                Say m=5, n=3

                pass 1:
                r := 4
                selected.push(4 )
                hat[4] := 5
                m := 4

                pass 2:
                r := 3
                selected.push(3 )
                hat[3] := 4 *** 4 re-enters the selection pool!
                m := 3

                pass 3:
                r := 3
                selected.push(h at[3]=4) *** duplicate!
                hat[3] := 3
                m := 2

                result: 4,3,4

                Comment

                • Dr John Stockton

                  #9
                  Re: Open Source / Collaboration

                  JRS: In article <UhWCc.248625$h Y.72235@twister .nyroc.rr.com>, seen in
                  news:comp.lang. javascript, Mick White <mwhite13@BOGUS rochester.rr.co m>
                  posted at Fri, 25 Jun 2004 14:04:36 :[color=blue]
                  >Bill Marsden wrote:
                  > ...
                  >and I have written a "Lottery Program" which essentially picks 6[color=green]
                  >> numbers at random and puts them in sequence.
                  >>
                  >> Would anyone would be interested in modifying the code below to
                  >>
                  >> a). Check for bugs
                  >> b). Make the program more efficient[/color]
                  >
                  ><snip>
                  >For some ideas look at:
                  >
                  >http://www.mickweb.com/javascript/ra...y_lottery.html[/color]


                  I have looked at that page. It was not clear to me how it was supposed
                  to work, so I went to its source code.


                  The code is not indented.

                  While it is entirely appropriate for delivered code that is intended to
                  be read only by browsers to be not indented, code intended to be read or
                  edited by humans should be indented to show its intended logical
                  structure - preferably by two or three spaces per level, and not by a
                  tab. If that is not in the FAQ or the FAQ notes, then it should be.


                  The code uses getElementById. That is nowadays a reasonable choice; but
                  it should be an informed choice on the part of the code editor.
                  Accordingly, for code offered as example code, it would be well to note
                  the presence of a comparatively recent function, and/or to provide code
                  to emulate, if necessary, that function. Such code may be in the FAQ
                  notes; it is in my js-other.htm (taken from a post by Randy).


                  Your method is, basically, to generate an array of numbers (i.e. make
                  the balls), to shuffle it, and to take from the beginning the required
                  number of entries.

                  Your shuffle is done by a large number (300) of swaps of randomly-chosen
                  elements. Random is thus called 600 times, with, for 59 balls, 59
                  possibilities per call. Therefore there are, in principle assuming
                  random to be perfect, 59^600 ways for the code to run. But there are
                  59! possible orders of the balls, and 59^600 is not a multiple of 59!,
                  so the sequences cannot all be equi-probable, as they should be.

                  Granted, 59^600/59! is large : I think that it is about
                  23,398, ...,806.964 ~= 2.3e982, so the deviation will be unimportant.
                  But, more significantly, the method is slower than need be; only 59
                  calls of random are needed to shuffle the array equi-probably. The
                  method is quite well-known, in Knuth, linked from the FAQ, almost
                  obvious, and codes slightly shorter.

                  Starting with the array, one selects a ball at random, and swaps it with
                  the end ball. The last-placed ball is thus randomly chosen. The
                  process is repeated using only those balls not already chosen, until
                  there is one ball left (or no balls).

                  To pick a few balls, just terminate the process early and use the end
                  balls.


                  To obtain a random-order array of sequential numbers, there is no need
                  to pre-fill the array; a slight modification generates them directly.
                  At each step, the array is considered to be expanded by one position;
                  the content of a random location in the expanded array is moved to the
                  new position; the next new number is placed at that random position.


                  In code offered for others to read, it is better not to use l as an
                  identifier; it can look very much like 1 - likewise O and 0.


                  I would not choose to use func as an identifier for something which is
                  not a function. PrintResults is in effect a simple version of FAQ
                  DynWrite (with reversed parameters), and can print any string.


                  My copy of W3's checker TIDY (1st November 2003) reports several errors.


                  Many readers will be unfamiliar with some or all of the various
                  lotteries shown; it would be well to describe them briefly in words.

                  --
                  © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                  <URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang. javascript
                  <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                  <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                  Comment

                  • Dr John Stockton

                    #10
                    Re: Open Source / Collaboration

                    JRS: In article <cbidt302o6l@dr n.newsguy.com>, seen in
                    news:comp.lang. javascript, Lee <REM0VElbspamtr ap@cox.net> posted at Fri,
                    25 Jun 2004 16:53:07 :
                    [color=blue]
                    > The algorithm simply doesn't work.[/color]

                    I thought that it might be a version of that obtained via David Rifkind
                    and c.l.p.d.m, in <URL:http://www.merlyn.demo n.co.uk/pas-rand.htm#Draw>:

                    type RandomSet = set of 1..MaxN ;

                    { Generate M non-repeating random numbers from 1 to N }
                    procedure GenerateRandomS et(M, N : integer ; var aSet : RandomSet) ;
                    var J : integer ;
                    begin
                    if M < 1 then aSet := []
                    else begin
                    GenerateRandomS et(M - 1, N - 1, aSet) ;
                    J := Random(N) + 1 { J is in [1..N] } ;
                    if J in aSet then Include(aSet, N) else Include(aSet, J) ;
                    end ;
                    end {GenerateRandom Set} ;

                    It seems to work, & DR is trustworthy.

                    Throwing it rapidly into javascript, I got a function returning an array
                    of length <= N in which M elements existed at random positions indexed
                    1..N - which corresponds to Pascal/Delphi set notation. A minor change
                    then made the element at position K, if present, be of value K. One
                    needs then only to strip the undefined elements, which ISTM that sort
                    will do. There may be a quicker way than sort, for this special case;
                    and I cannot say whether sort really should do what is wanted.


                    function GenerateRandomS et(M, N) {
                    // Generate M non-repeating random numbers from 1 to N }
                    if (M<1) return []
                    var aSet = GenerateRandomS et(M-1, N-1)
                    var J = Math.floor(Math .random()*N) + 1 // J is in 1..N
                    aSet[J] ? aSet[N]=N : aSet[J]=J
                    return aSet }

                    Ans = GenerateRandomS et(3, 9) // .sort() // to compactify


                    NOTES :
                    1. The translation needs to be checked
                    2. The javascript needs to be tested
                    3. In fact, sort only moves the selected elements together. How best
                    to compactify?
                    4. Recursion may not be quickest

                    BTW, it is easy to see that Random is called M times, with appropriate
                    handling to get the correct number of possibilities.

                    --
                    © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                    <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
                    <URL:http://www.merlyn.demo n.co.uk/clpb-faq.txt> RAH Prins : c.l.p.b mFAQ;
                    <URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zip> Timo Salmi's Turbo Pascal FAQ.

                    Comment

                    • rh

                      #11
                      Re: Open Source / Collaboration

                      Dr John Stockton wrote :
                      <snip>[color=blue]
                      >
                      > Throwing it rapidly into javascript, I got a function returning an array
                      > of length <= N in which M elements existed at random positions indexed
                      > 1..N - which corresponds to Pascal/Delphi set notation. A minor change
                      > then made the element at position K, if present, be of value K. One
                      > needs then only to strip the undefined elements, which ISTM that sort
                      > will do. There may be a quicker way than sort, for this special case;
                      > and I cannot say whether sort really should do what is wanted.
                      >
                      >
                      > function GenerateRandomS et(M, N) {
                      > // Generate M non-repeating random numbers from 1 to N }
                      > if (M<1) return []
                      > var aSet = GenerateRandomS et(M-1, N-1)
                      > var J = Math.floor(Math .random()*N) + 1 // J is in 1..N
                      > aSet[J] ? aSet[N]=N : aSet[J]=J
                      > return aSet }
                      >
                      > Ans = GenerateRandomS et(3, 9) // .sort() // to compactify
                      >[/color]

                      Netscape (and its Gecko friends?) don't do very well on numerically
                      sorting and grouping sparse arrays, unless the compare function is
                      specifically set up to shift the "undefined" values into the high end
                      of the array.

                      An alternative may be:

                      function GenerateRandomS et(M, N) {
                      // Generate M non-repeating random numbers from 1 to N }
                      if ( M < 1 ) return {}; // Use an object instead of array
                      var aSet = GenerateRandomS et(M-1, N-1);
                      var J = Math.floor(Math .random()*N) + 1; // J is in 1..N
                      aSet[J] ? aSet[N]=N : aSet[J]=J;
                      return aSet ;
                      }

                      AnsObj = GenerateRandomS et(M,N);
                      var Ans = [];
                      for (var k in AnsObj) Ans.push( AnsObj[k] );
                      Ans.sort( function (a,b) { return a-b } );

                      ../rh

                      Comment

                      • Richard Cornford

                        #12
                        Re: Open Source / Collaboration

                        Lee wrote:
                        <snip>[color=blue]
                        > The for(while) line was a typo.[/color]
                        <snip>

                        I immediately spotted that.
                        [color=blue]
                        > ... . The algorithm simply doesn't work.[/color]
                        <snip>

                        But I am glad you said that because I couldn't see any way of changing
                        the code so that it would not output duplicates.

                        I was looking at my version and noticed that I could lose the sort
                        operation because I knew the order of the values when they were first
                        created. Storing the relationships at the time of creation allows the
                        results array to be assembled pre-sorted, and simplifies the resulting
                        code.

                        var sixNumbers = (function(){
                        var base,orderBase, outAr = [];
                        function pull(){
                        base = this.next;
                        return this;
                        }
                        function toString(){
                        return String(this.val ueOf());
                        }
                        function b(itm){
                        itm.next = b;
                        itm.index = 1;
                        return itm;
                        }
                        function getFinal(index) {
                        var ar = this.orderPrv.g etFinal(index);
                        if(this.index <= index){
                        ar[ar.length] = this;
                        }
                        return ar;
                        }
                        b.pull = pull;
                        b.index = 0;
                        b.next = b;
                        b.toString = toString;
                        b.valueOf = function(){retu rn '';};
                        b.getFinal = function(){
                        outAr.length = 0
                        return outAr;
                        }
                        base = orderBase = b;
                        function getStackFnc(num ){
                        function p(itm, index){
                        if(index < p.index){
                        p.next = p.next(itm, index);
                        ++p.index;
                        return p;
                        }else{
                        itm.next = p;
                        itm.index = p.index + 1;
                        return itm;
                        }
                        }
                        p.pull = pull;
                        p.index = NaN;
                        p.next = null;
                        p.valueOf = function(){retu rn num;};
                        p.toString = toString;
                        p.orderPrv = orderBase;
                        p.getFinal = getFinal;
                        return (orderBase = p);
                        }
                        for(var c = 1;c < 50;c++){
                        base = base(getStackFn c(c), 1);
                        }
                        return ({
                        toString:functi on(){
                        var tempBase = b;
                        while(base.inde x){
                        tempBase = tempBase(base.p ull(),
                        ((Math.random() *(tempBase.inde x+1))|0));
                        }
                        base = tempBase;
                        return orderBase.getFi nal(6).join(' ');
                        }
                        });
                        })();

                        Richard.


                        Comment

                        • Dr John Stockton

                          #13
                          Re: Open Source / Collaboration

                          JRS: In article <t0S3xuI9Wf3AFw 0n@merlyn.demon .co.uk>, seen in
                          news:comp.lang. javascript, Dr John Stockton <spam@merlyn.de mon.co.uk>
                          posted at Sat, 26 Jun 2004 23:16:29 :
                          [color=blue]
                          >3. In fact, sort only moves the selected elements together. How best
                          > to compactify?[/color]

                          Sort, then assign the length ?
                          If the array is long, replace the sort by a scan that moves elements
                          down to the first vacancy.

                          The method in the cited article looks like a recursive form of my
                          GenerateSubsetU norderedSparse2 (M, N), which has for some while been on
                          the FAQ-cited page.

                          --
                          © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                          <URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang. javascript
                          <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                          <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                          Comment

                          • Mick White

                            #14
                            Re: Open Source / Collaboration

                            Dr John Stockton wrote:
                            [color=blue]
                            > JRS: In article <UhWCc.248625$h Y.72235@twister .nyroc.rr.com>, seen in
                            > news:comp.lang. javascript, Mick White <mwhite13@BOGUS rochester.rr.co m>
                            > posted at Fri, 25 Jun 2004 14:04:36 :
                            >[color=green]
                            >>Bill Marsden wrote:
                            >> I have written a "Lottery Program" which essentially picks 6
                            >>numbers at random and puts them in sequence.
                            >><snip>
                            >>For some ideas look at:
                            >>
                            >>http://www.mickweb.com/javascript/ra...y_lottery.html[/color]
                            >
                            >
                            >
                            > I have looked at that page. It was not clear to me how it was supposed
                            > to work, so I went to its source code.
                            >
                            >
                            > The code is not indented.
                            >
                            > While it is entirely appropriate for delivered code that is intended to
                            > be read only by browsers to be not indented, code intended to be read or
                            > edited by humans should be indented to show its intended logical
                            > structure - preferably by two or three spaces per level, and not by a
                            > tab. If that is not in the FAQ or the FAQ notes, then it should be.
                            >[/color]

                            My concern in this case is that the page function, but your point is
                            well taken
                            [color=blue]
                            >
                            > The code uses getElementById. That is nowadays a reasonable choice; but
                            > it should be an informed choice on the part of the code editor.
                            > Accordingly, for code offered as example code, it would be well to note
                            > the presence of a comparatively recent function, and/or to provide code
                            > to emulate, if necessary, that function. Such code may be in the FAQ
                            > notes; it is in my js-other.htm (taken from a post by Randy).
                            >[/color]

                            Yes, you're correct, there's nothing in the code that couldn't be
                            tweaked to work in very old browsers or to fail unceremoniously in js
                            challenged browsers.

                            [color=blue]
                            >
                            > Your method is, basically, to generate an array of numbers (i.e. make
                            > the balls), to shuffle it, and to take from the beginning the required
                            > number of entries.
                            >
                            > Your shuffle is done by a large number (300) of swaps of randomly-chosen
                            > elements. Random is thus called 600 times, with, for 59 balls, 59
                            > possibilities per call. Therefore there are, in principle assuming
                            > random to be perfect, 59^600 ways for the code to run. But there are
                            > 59! possible orders of the balls, and 59^600 is not a multiple of 59!,
                            > so the sequences cannot all be equi-probable, as they should be.
                            >
                            > Granted, 59^600/59! is large : I think that it is about
                            > 23,398, ...,806.964 ~= 2.3e982, so the deviation will be unimportant.
                            > But, more significantly, the method is slower than need be; only 59
                            > calls of random are needed to shuffle the array equi-probably. The
                            > method is quite well-known, in Knuth, linked from the FAQ, almost
                            > obvious, and codes slightly shorter.[/color]

                            From the start, I was concerned with the shuffle function's efficiency,
                            not so much with its pure randomness.
                            [color=blue]
                            >
                            > Starting with the array, one selects a ball at random, and swaps it with
                            > the end ball. The last-placed ball is thus randomly chosen. The
                            > process is repeated using only those balls not already chosen, until
                            > there is one ball left (or no balls).
                            >
                            > To pick a few balls, just terminate the process early and use the end
                            > balls.
                            > To obtain a random-order array of sequential numbers, there is no need
                            > to pre-fill the array; a slight modification generates them directly.
                            > At each step, the array is considered to be expanded by one position;
                            > the content of a random location in the expanded array is moved to the
                            > new position; the next new number is placed at that random position.
                            >[/color]

                            Certainly looks to be more efficient. Thanks.
                            [color=blue]
                            >
                            > In code offered for others to read, it is better not to use l as an
                            > identifier; it can look very much like 1 - likewise O and 0.
                            >[/color]

                            Good advice, mea culpa.
                            [color=blue]
                            >
                            > I would not choose to use func as an identifier for something which is
                            > not a function. PrintResults is in effect a simple version of FAQ
                            > DynWrite (with reversed parameters), and can print any string.
                            >[/color]

                            What would you suggest? I use "func" to remind me that the parameter to
                            be passed was to be the return statement of a function.
                            [color=blue]
                            >
                            > My copy of W3's checker TIDY (1st November 2003) reports several errors.
                            >[/color]

                            One errror now, according to http://validator.w3.org/check

                            ....boldred=fun ction(){return "<span style='color:re d'
                            "+this.bold()+" </span>"}

                            The element named above was found in a context where it is not allowed.
                            This could mean that you have incorrectly nested elements -- such
                            as a "style" element in the "body" section instead of inside
                            "head" -- or two elements that overlap (which is not allowed).

                            I know what is being pointed out, but how would you create a "legal"
                            bold red String prototype ?
                            [color=blue]
                            >
                            > Many readers will be unfamiliar with some or all of the various
                            > lotteries shown; it would be well to describe them briefly in words.
                            >[/color]

                            The intended audience knows more about the lotteries than Spasky does
                            about gambits...

                            Thanks for your critique, a rel eye opener.

                            Mick

                            Comment

                            • Richard Cornford

                              #15
                              Re: Open Source / Collaboration

                              Mick White wrote:
                              <snip>[color=blue]
                              > One errror now, according to http://validator.w3.org/check
                              >
                              > ...boldred=func tion(){return "<span style='color:re d'"
                              > +this.bold()+"</span>"}[/color]
                              ^^[color=blue]
                              >
                              > The element named above was found in a context where it is not
                              > allowed. This could mean that you have incorrectly nested
                              > elements -- such
                              > as a "style" element in the "body" section instead of inside
                              > "head" -- or two elements that overlap (which is not allowed).
                              >
                              > I know what is being pointed out, but how would you create a "legal"
                              > bold red String prototype ?[/color]
                              <snip>

                              It is likely that the validator is having trouble with the - </ -
                              character sequence and escaping that to - <\/ - would pacify it. But if
                              you want bold why not use a - font-weight:bold; - clause in the STYLE
                              attribute of the containing SPAN?

                              Richard.


                              Comment

                              Working...