0

So I have here a JavaScript stack built after this function:

function Stack()    //Creating Stack Object
    {
    // Create an empty array of cards.
    this.cards = new Array();  //cards array inside stack object
    this.push  = pushdata;      //Call pushdata function on push operation
    this.pop   = popdata;        //Call popdata function on pop operation
    this.printStack = showStackData; //Call showStackData function on printstack operation

    this.populate = function populate() {

            this.push(rand());
            this.push(rand());
            this.push(rand());
            this.push(rand());
        }
    }

(Where rand() is just a function generating a random number between 0 and 10 - I hope the syntax is alright because I had to delete a lot of commented out functions to make it suitable for this post).

So what I am wanting to achieve is to not allow than 4 same values in this Stack/Array.

I figured out I could check each number generated by rand() before it is pushed onto the Stack and add 1 to a counter variable and add a condition to not add this number when its counter already is on four. But this would mean a new variable for every possible number that may be pushed onto the stack what seems to be a really unnecessary overkill to me and I think you can understand that this is not the most elegant solution.

So how would you approach this?

Thanks a lot in advance!

ngmir
  • 450
  • 6
  • 26
  • Check this question for generating unique random numbers: http://stackoverflow.com/questions/4353830/how-do-you-randomly-generate-x-amount-of-numbers-between-the-range-of-y-and-z-in – Jan Apr 14 '11 at 20:30
  • Is there a reason you are repeating `this.push(rand());` four times instead of putting it in a for loop? – Peter Olson Apr 14 '11 at 20:38
  • yes, was repeating it because of being too lazy to write a loop ^^ – ngmir Apr 14 '11 at 20:45

1 Answers1

1

Instead of

this.push(rand()); 

Check if the value has already been in the array four times

var randNum = rand();
var count = 0;
for(var i = 0; i < this.length; i++){
  if(this[i] === randNum) count++;
}
if(count <= 4) this.push(randNum);
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • @benny Depending on how long the array is, you might want to also add `if(count > 4) break;` so it doesn't always search to the end of the array. – Peter Olson Apr 14 '11 at 20:52
  • the array actually wont be longer than approx. 10 values but I think I might add it anyways. Thanks a lot! – ngmir Apr 16 '11 at 21:13