【发布时间】:2016-07-22 20:01:14
【问题描述】:
我正在尝试从数据库中提取单词列表,以 $word1.$word2.$word3 的形式创建一个唯一的三词组合,并将其分配给星号。
我想避免重复组合 - 我希望每颗星都有一个唯一的三字标识符。
我当前的方法是创建一个包含所有可能的三字组合的数组,然后在将每个组合分配给星号后从数组中删除它。但是,我打算在我的单词列表中使用几千个单词,这意味着这个数组将包含数百亿个组合,因此这种方法看起来非常低效。
我怎样才能更有效地实现这一目标?我最初的想法是,我应该遍历每颗星,创建并分配一个三字组合,然后将组合添加到数组中,并为每颗星检查新生成的组合是否在数组中。
代码
<?php
// Initiate connection to the database...
$db = mysqli_connect('localhost', 'root', '', 'stellar');
// Query database of words
$words_sql = "SELECT * FROM words";
$words_res = mysqli_query($db, $words_sql)or die(mysqli_error());
// Create array of words
$words = array();
// Loop through each word from the database and add each to an array
while($row = mysqli_fetch_array($words_res)){
$words[] = $row['word'];
}
// Create array of all possible three-word combinations, from which we will randomly select our combinations
$triplets = array();
foreach ($words as $word1){
foreach ($words as $word2){
foreach($words as $word3){
if ($word1 !== $word2 && $word2 !== $word3 && $word1 !== $word3){
$triplets[] = "$word1.$word2.$word3";
}
}
}
}
// Pull all stars from database
$stars_sql = "SELECT * FROM stars";
$stars_res = mysqli_query($db, $stars_sql)or die(mysqli_error());
// Loop through every star in the array
while($row = mysqli_fetch_array($stars_res)){
// Store the star name and star_id in variables
$star = $row['star_name'];
$star_id = $row['star_id'];
// Set $three_words as a random combination from the array of possible combinations...
$ran_num = array_rand($triplets);
$three_words = $triplets[$ran_num];
// ...and remove this particular combination, in order to prevent repating combinations
array_splice($triplets, $ran_num, 1);
// Attach the random 3-word combination to the star
echo $star.' '.$three_words.'<br/><br/>';
}
?>
【问题讨论】:
-
如果您有 1000 个单词,您将有 1000000000 个可能的组合,这与您需要命名的总星数相比如何,例如,它是像 100 个星还是更多像 500000000 个星?
-
我想从大约 250 万颗星开始,所以我想我只需要大约 300 个字。
标签: php random combinations