Question

I am really struggling with this, so maybe some of you have some beautiful hints?

What I want to do I want to create a table with two columns ("name" and "rating"). I've got 5 rows.

  • 2 of these rows should have a random "rating" between 6-10
  • 2 other rows should have a random "rating" between 1-5
  • 1 row (the last one) should have a random rating between 7-10.

Until this point there is no problem: This is my jsFiddle so far: http://jsfiddle.net/HT89v/2/

BUT: I want to shuffle the "ratings" of the first 4 rows, so that the first two rows don't always have a very high "rating" and the 3rd and 4th row don't always have a very low "rating". I want to randomly shuffle them.

The 5th row should not be affected. .

I tried to implement the .shuffle plugin in the jsfiddle but I have no idea what I am doing wrong.

function noNorm(){  
    document.getElementById("rating4").innerHTML = [Math.floor(Math.random()*5) + 6];

    for (var i = 0; i <= 1; i++){
        document.getElementById("rating"+i).innerHTML = [Math.floor(Math.random()*5) + 6];
    };

    for (var i = 2; i <= 3; i++){
        document.getElementById("rating"+i).innerHTML = [Math.floor(Math.random()*5) + 1];
    };
};

noNorm();

jQuery(function($){
    $('#rating0', '#rating1', '#rating2', '#rating3').shuffle();
});


(function($){

    $.fn.shuffle = function() {
        return this.each(function(){
            var items = $(this).children().clone(true);
            return (items.length) ? $(this).html($.shuffle(items)) : this;
        });
    }

    $.shuffle = function(arr) {
         for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
         return arr;
    }

})(jQuery);

Thank you very very much!

Was it helpful?

Solution

There are many solutions to shuffle arrays with javascript. If I understand your problem correcty, this should do the trick: http://jsfiddle.net/HT89v/6/

I shuffle the whole ratings[] array before giving a value to ratings[4] so that the 5th row is not affected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top