Programming Technique: How to create a simple card game

前端 未结 6 1182
自闭症患者
自闭症患者 2020-12-24 00:10

as I am learning the Ruby language, I am getting closer to actual programming. I was thinking of creating a simple card game. My question isn\'t Ruby oriented, but I do kno

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-24 00:31

    Rather than cramming this all in a comment, I'm adding this as a note for people that might find it useful. Ruby 1.9's native Array#shuffle! and Array#shuffle does in fact use the Knuth-Fisher-Yates shuffle algorithm.

    ruby-1.9.1-p376/array.c

    /*
     *  call-seq:
     *     array.shuffle!        -> array
     *  
     *  Shuffles elements in _self_ in place.
     */
    
    static VALUE
    rb_ary_shuffle_bang(VALUE ary)
    {
        long i = RARRAY_LEN(ary);
    
        rb_ary_modify(ary);
        while (i) {
        long j = rb_genrand_real()*i;
        VALUE tmp = RARRAY_PTR(ary)[--i];
        RARRAY_PTR(ary)[i] = RARRAY_PTR(ary)[j];
        RARRAY_PTR(ary)[j] = tmp;
        }
        return ary;
    }
    
    
    /*
     *  call-seq:
     *     array.shuffle -> an_array
     *  
     *  Returns a new array with elements of this array shuffled.
     *     
     *     a = [ 1, 2, 3 ]           #=> [1, 2, 3]
     *     a.shuffle                 #=> [2, 3, 1]
     */
    
    static VALUE
    rb_ary_shuffle(VALUE ary)
    {
        ary = rb_ary_dup(ary);
        rb_ary_shuffle_bang(ary);
        return ary;
    }
    

提交回复
热议问题