在 Javascript/PHP 中无重复地随机排列随机数 [英] Shuffles Random Numbers with no repetition in Javascript/PHP

查看:31
本文介绍了在 Javascript/PHP 中无重复地随机排列随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里搜索了一些答案,但它似乎不是我需要的东西,或者我只是不知道如何应用它.

I've searched through some of the answers here but it doesn't seem the thing that I needed or I just don't know how to apply it though.

我还没有开始任何代码,我只是在考虑如何去做,我不知道如何去做.我需要你们的帮助.

I haven't started any codes and I'm only thinking on how to do it and I have no idea how to do it. I need your help guys.

假设我有一个数组,其中包含以下这些值

Let's assume that I have an array which consists of these values below

[1,2,3,4,5,6,7,8,9]

而且我需要在不重复最后结果的每个数字的位置的情况下对其进行洗牌.所以它可能会喜欢

And I need to shuffle it without repeating the position of each numbers of the last result. so it would probably like

[5,3,9,6,2,8,1,4,7]

如果我再次洗牌它会像

[4,7,2,1,8,3,6,9,5]

等等.

好吧,我不知道它是否有任何相关性,但是我宁愿不使用 rand().这个东西有什么解决方案吗?

Well I don't know if there' any relevance to it but, would rather not to use rand() though. Any solution for this stuff?

推荐答案

试试这个,

$count = 15;
$values = range(1, $count);
shuffle($values);
$values = array_slice($values, 0, 15);

$numbers = array();
do {
   $possible = rand(1,15);
   if (!isset($numbers[$possible])) {
      $numbers[$possible] = true;
   }
} while (count($numbers) < 15);
print_r(array_keys($numbers));

希望对你有帮助.

这篇关于在 Javascript/PHP 中无重复地随机排列随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆