0

I'm trying to find a way to replace any duplicated value but the only solution I have found so far is array_unique which doesn't really work for me as I need the duplicate to be replaced by another number which itself is not a duplicate.

 function generate_random_numbers($rows, $delimiter)
 {
     $numbers = array();

     for($i = 0; $i < $delimiter; $i++)
     {
         $numbers[$i] = rand(1, $rows);

         if(in_array($i, $numbers))
         {
            $numbers[$i] = rand(1, $row);
         }
     }
     return $numbers;
 }

 $numbers = generate_random_numbers(20, 10);

 print_r($numbers);

would anyone help me out on this one please?

2
  • you want $delimiter random but different numbers? Commented Aug 14, 2015 at 17:11
  • I actually want all the numbers inside $numbers array to be different but within the $row range. array_unique will remove the numbers that repeat and I want to have the numbers in $delimiter. Commented Aug 14, 2015 at 17:14

3 Answers 3

4

You can do this way easier and faster.

Just create an array for all possible numbers with range(). Then shuffle() the array and take an array_slice() as big as you want.

<?php

    function generate_random_numbers($max, $amount) {
        if($amount > $max)
            return [];

        $numbers = range(1, $max);
        shuffle($numbers);
        return array_slice($numbers, 0, $amount);
    }

    $numbers = generate_random_numbers(20, 10);
    print_r($numbers);

?>

And if you want to get 490 unique elements from a range from 1 - 500, 10'000 times:

  • My version: ~ 0.7 secs
  • Your version: Order 2 birthday cakes, you will need them.
Sign up to request clarification or add additional context in comments.

Comments

1

You are inserting a random number and then, if it is already in the array (which it MUST be because you just inserted it), you use a new random number, which might be a duplicate. So, you have to get a number that is not a duplicate:

do {
    $num = rand(1,$rows);
} while(!in_array($num, $numbers));

Now, you know that $num is not in $numbers, so you can insert it:

$numbers[] = $num;

Comments

1

You were pretty close. The if-clause needs to be a loop, to get new random number.
(Also your in_array was slightly wrong)

function generate_random_numbers($rows, $delimiter) {
    $numbers = array();

    for($i = 0; $i < $delimiter; $i++) {
        do {
            $number = rand(1, $rows);
        }
        while(in_array($number, $numbers));

        $numbers[] = $number;
    }

    return $numbers;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.