Function Random File .Txt texts

0

I've been trying to create a project. When the user clicks <a href> to do download the function should read the file txt and show a line in random mode (with probability of leaving line 1, 2, 3 , 19, etc.).

If you leave line 1 of the file txt , the user "won", if other lines appear without being 1, echo "perdeu" .

It is a genre of random text . You can either.

How do I do something like this?

    
asked by anonymous 17.05.2017 / 20:49

2 answers

0

To get all the lines of the file (file), use the file function:

$lines = file("arquivo.txt");

To randomly sort a line, use the array_rand function:

$randomLine = array_rand($lines);

To check if this is the first line, just compare with the first line in $lines :

if ($randomLine == $lines[0]) {
    echo $randomLine;
} else {
    echo "Perdeu!";
}
    
17.05.2017 / 21:05
0

First open the file, in an array:

$texto = file('arquivo.txt');

To adjust the probability, just say what they are.

$probabilidade = [ 
   0 => 10,
   1 => 50,
   2 => 35,
   3 => 5 
];

In this case the index is the line and in sequence its probability.

Then it generates a random number (in this case using CSPRNG):

$aleatorio = random_int(1, array_sum($probabilidade));

So now based on% set% we will know what minimum and maximum numbers for each, if it is the message will be shown.

$ultimo = 0;

foreach ($probabilidade as $key => $porcento) {

    if ($aleatorio >= $ultimo + 1
        && $aleatorio <= $ultimo + $porcento
    ) {
        echo $texto[$key];
    }

    $ultimo = $ultimo + $porcento;

}

Try This Here

This will cause if $probabilidade is ...

  • From $aleatorio to 1 will be the 10 line.
  • From 0 to 11 will be the 60 line.
  • From 1 to 61 will be the 95 line.
  • From 2 to 96 will be the 100 line.

Obviously the chance of being between 3 to 11 is higher, so the 95 message and 1 message are shown more frequently, than 2 and 0 messages.

    
17.05.2017 / 21:42