Ich versuche, eine Liste von Wörtern aus der Datenbank zu ziehen, eine eindeutige Drei-Wort-Kombination in der Form $ word1. $ Word2. $ Word3 zu erstellen und sie einem Stern zuzuordnen.Wie kann ich doppelte zufällige Drei-Wort-Kombinationen aus einer Tabelle von Wörtern vermeiden?
Ich möchte doppelte Kombinationen vermeiden - ich möchte, dass jeder Stern eine eindeutige Drei-Wort-Kennung hat.
Meine aktuelle Methode besteht darin, ein Array aller möglichen Drei-Wort-Kombinationen zu erstellen und dann jede Kombination aus dem Array zu löschen, sobald sie einem Stern zugewiesen wurde. Ich beabsichtige jedoch, ein paar tausend Wörter in meiner Wortliste zu verwenden, was bedeutet, dass dieses Array Zehntausende von Kombinationen enthält, so dass diese Methode unglaublich ineffizient erscheint.
Wie kann ich dies effektiver erreichen? Meine anfänglichen Gedanken sind, dass ich jeden Stern durchlaufen, eine Drei-Wort-Kombination erstellen und zuweisen, dann die Kombination zu einem Array hinzufügen und für jeden Stern überprüfen soll, ob die neu erzeugte Kombination im Array ist.
-Code
<?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/>';
}
?>
Wenn Sie 1000 Wörter haben, hätten Sie 1000000000 mögliche Kombinationen. Wie ist das mit den Sternen zu vergleichen, die Sie benennen müssen, z. B. 100 Sterne oder mehr wie 500000000 Sterne? – apokryfos
Ich möchte mit ~ 2,5 Millionen Sternen beginnen, also denke ich, dass ich nur ~ 300 Wörter benötige. – Callum