选择条件值为

时间:2016-07-05 05:06:49

标签: php arrays random conditional-statements

我有一个布尔数组,我想从中选择一个值为true的随机索引并将其设置为false。

当然,我可以通过选择索引来执行此操作,直到我找到一个值为真的值:

$arr = array(true, false, false, true, false, true);

var_dump($arr);

$i = array_rand($arr);
while(!$arr[$i])
{
    $i = array_rand($arr);
}
$arr[$i] = false;

var_dump($arr);

这会创建类似这样的内容,其中第四个条目已更改。

array(6) {
  [0]=>
  bool(true)
  [1]=>
  bool(false)
  [2]=>
  bool(false)
  [3]=>
  bool(true)
  [4]=>
  bool(false)
  [5]=>
  bool(true)
}

array(6) {
  [0]=>
  bool(true)
  [1]=>
  bool(false)
  [2]=>
  bool(false)
  [3]=>
  bool(false)
  [4]=>
  bool(false)
  [5]=>
  bool(true)
}

但是,我必须使用明显更大的阵列多次执行此操作。在某些时候,阵列几乎完全是假的,在这种情况下,强力方法效率很低。

有没有更优雅的方法来解决这个问题?任何类型的array_rand()函数,我可以给出前提条件吗?

3 个答案:

答案 0 :(得分:2)

library(rvest)
library(purrr) # for `map`

url <- "https://play.google.com/music/preview/Ttyni4p5vi3ohx52e7ye7m37hlm?lyrics=1&utm_source=google&utm_medium=search&utm_campaign=lyrics&pcampaignid=kp-lyrics&sa=X&ved=0ahUKEwiV7oXtqtvNAhVB5GMKHTnHDZEQr6QBCBsoADAB"

url %>% read_html() %>% 
    html_nodes("p") %>% 
    # For each node, return all content nodes, both text and tags, separated. From xml2.
    map(xml_contents) %>%    # or lapply(xml_contents)
    # For each nexted node, get the text. Here, this just reduces "<br />" tags to "".
    map(html_text) %>%       # or lapply(html_text)
    # For each list element, subset to non-empty strings.
    map(~.x[.x != ''])       # or lapply(function(x){x[x != '']})

## [[1]]
## [1] "People all over the world (everybody)"         
## [2] "Join hands (join)"                             
## [3] "Start a love train, love train"                
## [4] "People all over the world (all the world, now)"
## [5] "Join hands (love ride)"                        
## [6] "Start a love train (love ride), love train"    
## 
## [[2]]
## [1] "The next stop that we make will be soon"             
## [2] "Tell all the folks in Russia, and China, too"        
## [3] "Don't you know that it's time to get on board"       
## [4] "And let this train keep on riding, riding on through"
## [5] "Well, well" 
## 
## ...

上面的代码返回$ res中$ arr的真值的索引。

https://3v4l.org/CG1v2

编辑。然后将$ arr索引之一设置为false,您应该:

$arr = array(true,true,false,false,true,false);

$res = array_keys($arr, true);

var_dump($res);  // returns 0,1,4

echo $res[array_rand($res)]; //echo one of the indexes that is true

循环这两行最终会将所有索引设置为false:

$arr[$res[array_rand($res)]] = false; // will set one as false.

答案 1 :(得分:1)

您可以使用以下代码:

B

答案 2 :(得分:0)

在不浪费任何工作的情况下执行此操作的最简单方法是创建数组索引的随机排列。 Knuth shuffle(也称为Fisher-Yates shuffle)应该是令人钦佩的。

某些应用程序的另一个选项是选择一个生成器,该生成器在不重复的情况下创建所需范围内的值,或者仅使用相对较少数量的异常值(超出目标范围的值)。例如,所有linear-congruential generators都具有任何低n位循环且具有周期2 ^ n的属性。选择不小于数组大小的2的第一个幂,并且平均每个好的数据都会产生少于一个的浪费数字。