dimanche 17 juillet 2016

How to prevent repeating combinations of two random numbers?

<?php

include "db_connect.php";

// Query database of words
$words_sql    = "SELECT * FROM words";
$words_res    = mysqli_query($db, $words_sql)or die(mysqli_error());

// Create array of words
$array  = array();

// Loop through each word and add each to the array
while($row = mysqli_fetch_array($words_res)){
     $array[] = $row['word'];
}

// Set $word1 as random word from $array
$ran_num = array_rand($array);
$word1   = $array[$ran_num];

// Remove the chosen word from the array
array_splice($array, $ran_num, 1);

// Reset the array
$array2 = $array;

// Set $word2 as random word from $array
$ran_num2 = array_rand($array2);
$word2    = $array2[$ran_num2];

// Set variables 
$word        = 'star';
$three_words = "$word.$word1.$word2";

echo $three_words;

?>

I'm trying to create a three-word combination in the form star.word1.word2, where word1 is a random word from the database, and word2 is a different random word from the database (word1 != word2).

How do I avoid repeating combinations? By repeating combinations I mean the following:

Combination 1: star.lamp.chair; Combination 2: star.dog.ball; Combination 3: star.ball.dog; Combination 4: star.lamp.chair

Here, combination 1 and combination 4 are the same - this repetition is what I want to avoid. The order is not important, so combination 2 and combination 3 are fine.

Above is my code, which works, but is susceptible to repeating combinations.




Aucun commentaire:

Enregistrer un commentaire