首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在稳定的条件场景中,有什么替代while循环的方法吗?

在稳定的条件场景中,有什么替代while循环的方法吗?
EN

Ethereum用户
提问于 2022-03-29 11:02:58
回答 1查看 25关注 0票数 0

我正在开发一个NFT市场与Dropsite模块,其中免费的NFT将被随机分配。有三种固定数量的NFT:白金: 150,金: 350,银: 500

现在我想建立一个逻辑,如果150来自白金,350来自黄金或500来自银类别,随机数应该再次产生。这可以很容易地使用while循环,但我想避免这一点,因为这将是太昂贵的煤气费。

我怎么能省略这个?我现在有以下逻辑:

代码语言:javascript
复制
function randomMint() contractIsNotPaused public returns (uint) {
    uint nftId = random();
while((Platinum<=150 && nftId==0) || (Gold<=350 && nftId==1) || (Silver<=500 && nftId==2))
    {
        nftId = random();
        if(nftId==0)
        {
            data="Platinum";
            Platinum++;
        }
        else if(nftId==1)
        {
            data="Gold";
            Gold++;
        }
        else if(nftId==2)
        {
            data="Silver";
            Silver++;
        }
    }
_mint(_msgSender(), nftId, numOfCopies, data);
TotalNFTsMinted++;
dropsite_NFT_Owner[_msgSender()]=nftId;
return nftId;
}
EN

回答 1

Ethereum用户

回答已采纳

发布于 2022-03-29 12:19:59

我添加了一些注释,这里不需要循环,它会增加大量的计算,您将在每个循环上调用随机()。

代码语言:javascript
复制
function randomMint() contractIsNotPaused public returns (uint) {
    // no need to call random() multiple times
    uint nftId = random(); // we're assuming that random() returns only 0,1,2
    // if nftID is 0, and less than 151 so 150 MAX
    if(nftId == 0 && platinum < 151) {
        data = "Platinum";
        Platinum++; 
    // if nftID is 0 or 1 and platinum is more than 150, it will go there
    } else if(nftId <= 1 && gold < 351) {
        data = "Gold";
        Gold++;
    // if any of the above conditions are filled it will mint silver if enough silver available
    } else if(nftId == 2 && silver < 501) {
        data="Silver";
        Silver++;
    } else {
        if(gold < 351) {
            data = "Gold";
            Gold++; 
        } else {
            data = "Platinum";
            Platinum++;
        }
    }
}

如果可能的话,我建议避免使用string

票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/124971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档