Generate random numbers without repeat and sequence
✔ Recommended Answer
function generatePin() { $digits = range(0, 9); shuffle($digits); $pin = ''; while (strlen($pin) < 4) { // Get a random digit from the shuffled array $digit = array_pop($digits); // Check if the digit would create a sequence with the last digit in the pin if (strlen($pin) > 0 && ($digit == $pin[strlen($pin) - 1] - 1 || $digit == $pin[strlen($pin) - 1] + 1)) { // Skip this digit and shuffle the array again shuffle($digits); } elseif (strlen($pin) == 0 || !in_array($digit, str_split($pin))) { // Add the digit to the pin if it is not already in the pin $pin .= $digit; } } return $pin;}
Source: stackoverflow.com
Answered By: Mahdi Rashidi
Here's a PHP code snippet that generates an array of n
unique random numbers within a specified range:
php<?php
$start = 1; // starting number of range
$end = 100; // ending number of range
$n = 10; // number of random numbers to generate
$numbers = array();
while (count($numbers) < $n) {
$num = mt_rand($start, $end);
if (!in_array($num, $numbers)) {
$numbers[] = $num;
}
}
print_r($numbers);
This code uses a while
loop to generate random numbers until the array contains n
unique numbers. The mt_rand()
function generates a random integer between start
and end
, inclusive. The in_array()
function checks whether the number already exists in the array. If the number is not in the array, it is added to the end of the array using the []
syntax.
You can adjust the start
, end
, and n
variables to generate random numbers within different ranges and with different lengths of the resulting array.
Comments
Post a Comment