How not to repeat random numbers?

2

I'm creating a rotating banner, and for this I use the random javascript that draws a position in the array and displays, this already works well, the problem is that sometimes it draws the same number at random and repeats what is being displayed , I want to make sure that the lottery is not repeated. I'm trying to do a routine for this but after a while the banners stop being displayed and the result is not legal.

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();

});
    
asked by anonymous 16.12.2015 / 16:11

2 answers

2

If it's for display only you can use the unique filter.

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

This will not display two users with the same login.

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

    
16.12.2015 / 16:23
0

I'm not sure how timeout works in angular, if it would be the setinterval of pure js, but I'll give you a solution that does not allow the repetition of 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 at: jsfiddle

    
16.12.2015 / 17:37