如何选择数组中的随机元素

如何选择数组中的随机元素

本文介绍了如何选择数组中的随机元素,避免(如果是的话)某个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,当用户连接到此应用程序时,会给他们一个userid var,然后将其插入到数组中.所以,我正在使用

For example, when users are connecting to this application they are given a userid var, then it's inserted into the array. So, i'm using

chosenUser = usersOnlineArray[Math.round((Math.random()*usersOnlineArray.length))];

选择另一个随机用户.但是我需要确保它不会选择他们个人分配的用户ID,这样他们才不会最终得到自己.

to pick another random user. But i need to make sure it doesn't pick the userID they personally were assigned so they don't end up getting themselves.

我将如何使用该代码,但告诉它记住,请确保您不选择用户名"

how would i use that code but tell it to "remember, make sure you don't pick userid"

也许我可以做类似的事情

maybe I could do something like

chosenUser = usersOnlineArray[Math.round((Math.random()*usersOnlineArray.length))];

    if (chosenUser = userid)
    {
        chosenUser = usersOnlineArray[Math.round((Math.random()*usersOnlineArray.length))];
    } else
    {
    //next part of mycode
    }

也许应该是while (chosenUser = userid),以防它两次出现...

Maybe that should be a while (chosenUser = userid) incase it gets it twice...

但是,我想,如果有一种有效的方法只是为了确保它不会首先被选中,我可以跳过所有这些事情.

But, i'm thinking i could skip all that if there is a efficent way just to make sure it doesn't pick it in the first place.

对不起,我不太确定我该如何表达这个问题,或者我是否有一个术语我不知道要提及的内容.

Sorry, i'm not quite sure how I should have phrased the question or if there is a term i'm unaware of to refer to what i'm trying to do.

推荐答案

您的方法很好,例如再次调用您的方法

You are on good way, just call again your method for example

public void Something(){ string user = GetUser(); }
public string GetUser(){
   chosenUser = usersOnlineArray[Math.round((Math.random()*usersOnlineArray.length))];

  if (chosenUser == userid)
  {
    return GetUser();
  }
return chosenUser;
}

这篇关于如何选择数组中的随机元素,避免(如果是的话)某个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 11:00