How not to repeat random numbers?

Asked

Viewed 835 times

2

I am creating a rotary banner, and for this I use the javascript rule that draws a position in the array and displays, this already works well, the problem is that sometimes draws the same number in the array and repeats what is being displayed, I want to make it not repeat the draw. I’m trying to make a routine for it but after a while the banners stop being displayed and the result is not cool.

I’m trying like this.

var app = angular.module('starter');

app.controller('BannerAnuncios', function($scope, $timeout){

    var banners = ["Fernando", "Paiva", "Campos", "Luis", "Gomes"];
    var count = banners.length;
    var lastBanner = 0;

    function rotationBanner(){  
        var i = Math.floor(Math.random() * count);
        if(i != lastBanner){
            $scope.banner = banners[i];
        }else{
            rotationBanner();
        }       

        console.log(lastBanner);
        console.log(i);
        lastBanner = i;
        $timeout(rotationBanner, 5000);
    }

    rotationBanner();

});
  • 1

    With so few banner options, 1 to 5 would not advise using single randomization. until there will come a time when there will be no more numbers, I advise you to save the current value and generate a new randomic number, ai Voce compares it, if it is equal to the current generates again, until you have a different.

  • @Highlander yes, but I already do it look at the else he invokes the same function again.

  • Randomize only the array distribution and not item by item. using .sort().

2 answers

2

If it’s just for display you can use the filter unique.

Example: ng-repeat="user in users | unique:'login'"

This way it will not display two users with the same login.

If you want to make a filter in the code recommend that answer:

0

I’m not sure how $timeout works at the angle, if it would be the pure js setinterval, but I’ll give you a solution that does not allow repeating the number of banners:

var banners = ["Fernando", "Paiva", "Campos", "Luis", "Gomes"];
var count = banners.length;
var lastBanner = 0;

setInterval(function() {
  var i = Math.floor(Math.random() * count);
  if (i !== lastBanner) {
    document.body.innerHTML = i; // Aqui seus números não serão repetidos.
  }
  lastBanner = i;
}, 1000);

Example working on: jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.