J
J
Jony13372016-11-21 12:39:41
PHP
Jony1337, 2016-11-21 12:39:41

Is there a possibility of repeating one digit in this code?

There was a task to get 4 random numbers and that would not be repeated, I found a bunch of working examples on the Internet but decided to make my own

for ($i=0; $i <= 3 ; $i++ ) {
  $randNumber[$i] = rand (1,100);
  if ($randNumber[$i] == $randNumber[$i+1]) {
    $randNumber [$i+1] = rand (1,100);
  }
  echo $randNumber [$i];
  echo "<br>";
}

like 20 times checked, do not repeat, is there a chance that they will repeat at least once?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Kuzmina Maria, 2016-11-21
@Jony1337

Of course, there is a possibility. As already mentioned, you cannot compare with the next empty value.
I think it's better to do this:

// Необходимое количество случайных чисел
$limit = 4;
// Максимальное значение случайного числа
$max = 100;
// Массив, в который складываются случайные числа
$numbers = [];

// Запускаем цикл
while(1) {
  // Генерируем случайное число
  $random = rand(1, $max);
  
  // Проверяем, есть ли уже такое число в массиве-результате
  if(!in_array($random, $numbers)) {
    // Если такого числа нет, добавляем его в массив
    $numbers[] = $random;
  }
  
  // Если уже набрали нужное количество чисел - выходим из цикла
  if(count($numbers) == $limit) { 
    break; 
  }
}

var_dump($numbers);

E
Edward, 2016-11-21
@edb

there is. But as a matter of fact at you also it is not checked for uniqueness.
what does the if ($randNumber[$i] == $randNumber[$i+1]) { ??? compares to an empty value? To ensure uniqueness, you need to make a double loop: the main one for generating and the inner one for checking uniqueness.

U
ukoHka, 2016-11-21
@ukoHka

for ($i=0; $i <= 3 ; $i++ ) { //$i=0;
  $randNumber[$i] = rand (1,100); //Допустим 50
  if ($randNumber[$i] == $randNumber[$i+1]) { //$randNumber[$i+1] == null для i=0
    $randNumber [$i+1] = rand (1,100); //Допустим 50
  }
  echo $randNumber [$i]; //50
  echo "<br>"; //<br>
}

For now, assuming that the array initially has all null values, the condition will never be met.
It would be necessary to compare with the previous one, and not with the next one.

M
Maxim Timofeev, 2016-11-21
@webinar

There is. At least your validation won't work at all:
???? You don't have $randNumber[$i+1]. You've created $randNumber[$i] and you're checking with $randNumber[$i+1] that doesn't exist yet.
Suppose this is a typo and $randNumber[$i-1] was meant, but what about the previous element?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question