首页 > 其他分享 >用set做一轮无重复纯随机

用set做一轮无重复纯随机

时间:2023-02-19 22:58:35浏览次数:30  
标签:set int 一轮 播放 随机 100 include

前端时间面腾讯的时候,一位老师问了一个相当有趣的问题:假设存在一个音乐播放器,里面有一个100首歌的歌单。现在需要做一个随机播放功能,要求不重复的随机播放完一百首歌。当时脑子短路了没想出来,几天突然意识到了问题的解法。

定义一个集合,将歌曲按照编号1-100存进集合,根据集合中剩余的元素数量做rand,每一次播放后删除即可。

简单写了点代码:

#include <iostream>
#include <set>
#include <time.h>
using namespace std;

int main() {
    srand(time(0));
    set <int> st;
    for (int i = 1; i <= 10; i++) {
        st.insert(i);
    }
    while (!st.empty()) {
        int pos = rand() % st.size();
        auto iter = st.begin();
        for (int i = 0; i < pos; i++) {
            iter++;
        }
        cout << *iter << " ";
        st.erase(iter);
    }
    return 0;
}

 

标签:set,int,一轮,播放,随机,100,include
From: https://www.cnblogs.com/kazusarua/p/17135849.html

相关文章

  • Set Next-Hop IP Address
    TheinfrastructureprovidedbyCEForprocessswitchingperformstherecursiontothenext-hopIPaddress.Theconfigurationsequence,whichaffectsrouting,i......
  • 输出不重复的随机数
    packagecom.fqs.demo1;importjava.util.Random;publicclassOnly3{publicstaticvoidmain(String[]args){//输出不重复的随机数范围0,1,2,3,......
  • 传参的方式 输出不重复的 随机数
    packagecom.fqs.demo1;importjava.util.Random;publicclassOnly2{publicstaticvoidmain(String[]args){//用传参方式输出不重复的随机数......
  • The Number of Good Subsets
    TheNumberofGoodSubsetsYouaregivenanintegerarray nums .Wecallasubsetof nums good ifitsproductcanberepresentedasaproductofoneormo......
  • Count the Number of Square-Free Subsets
    CounttheNumberofSquare-FreeSubsetsYouaregivenapositiveinteger0-indexed array nums .Asubsetofthearray nums issquare-free iftheproduct......
  • Golang基础-随机数
    import"math/rand"n:=rand.Intn(100)//nisarandomint,0<=n<100f:=rand.Float64()//fisarandomfloat64,0.0<=f<1.0x:=[]string{"a","b",......
  • Hibernate 随机获取100条记录
    Hibernate执行的话效率太低,我数据库才3000条左右,就用了5秒时间。建议用jdbc执行finder=newFinder("").append("FROMEvent21ORDERBYRA......
  • An attempt to set a process's DebugPort or ExceptionPort was made
    Howtoresolve"Cannotdebugpid,NTSTATUS0xC0000048"-"Anattempttosetaprocess'sDebugPortorExceptionPortwasmade..."2011/10/21 OnceIfou......
  • WEB版双色球号码随机生成代码(chatgpt)
    <!doctypehtml><html><head><title>双色球号码随机生成</title><scripttype="text/javascript">functiongenerateBall(){......
  • Collection子接口之二: Set接口
    Set接口是Collection的子接口,set接口没有提供额外的方法Set集合不允许包含相同的元素,如果试把两个相同的元素加入同一个Set集合中,则添加操作失败。Set判断两个对象......