Hey there. How do I get a random Player out of a List? I'm saving Players into a YAML Config when doing a command. If there are 3 or more players in the list, one of them will be picked randomly and the player will get a sword. I already done the List and the command, the only thing I need is the random pick.
PHP: /** @var string[] $list */$selected = [];for($i = 0; $i < 3; $i++){ while(in_array($k = mt_rand(0, count($list) - 1))); // using a while to avoid selecting duplications. $selected[] = $k;}$selections = array_map(function($k) use($list){ return $list[$k];}, $selected);
which sometimes return the same variable in different interval. its not that great. hoping to test @PEMapModder's method.
That's not one of OP's requirements but fair enough Also, I would strongly advise against using in_array (O(n)) - use array keys and isset(O(1)) instead
Hey, thanks for your Post but I still don't know how to do it :/ So, what I wanna do is: PHP: public function startGame(){ $this->AStarted = true; // Sets the Game on true/started // Pick a random player out of $this->inA and teleport him to 0 0 0, teleport the other players to 1 1 1(Example) }
PHP: public function startGame(){$this->AStarted = true; // Sets the Game on true/started $list = $this->inA->getAll(); $selected = [];for($i = 0; $i < 3; $i++){ while(in_array($k = mt_rand(0, count($list) - 1))); // using a while to avoid selecting duplications.$selected[] = $k;}$selections = array_map(function($k) use($list){ return $list[$k];}, $selected);foreach($selected as $select){$list[$select]->teleport(...);}} Is that correct? Sorry but I don't code for that long and don't know much so yea.. But well thanks for your help!