开发者

Do not allow more than 4 same values in a JS stack

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!


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜