Home php Create an array with random numbers ascending. PHP

Create an array with random numbers ascending. PHP

Author

Date

Category

Only at the beginning of the study of PHP. You need to create an array of 10 numbers. In the first element, write a number 1. Each next number is generated randomly and is written to an array provided if it is greater than the previous one.
I know that Random can immediately issue the maximum figure, I’ll think about it.

$ arr = [];
$ arr = array_push ($ arr, 1);
While (Count ($ ARR) & LT; = 9) {
  $ num = Rand (0, 100);
  $ Endnum = End ($ ARR);
  if ($ num & gt; $ endnum) {
  $ arr [] = array_push ($ arr, $ num);
}
}
Print_R ($ ARR);

Answer 1, Authority 100%

But it is necessary to generate a random number and check whether it is more previously. And then write to the array.

Generate random numbers with a gradual increase in the maximum:

$ arr [] = 1;
$ Total = 10;
$ STEP = $ Total;
While (Count ($ ARR) & LT; $ Total) {
  $ RAND = RAND (1, $ STEP + $ Total);
  $ max = max ($ ARR);
  If ($ RAND & GT; $ MAX) {
    $ arr [] = $ RAND;
    $ STEP + = $ Total;
  }
}
VAR_DUMP ($ ARR);

Answer 2, Authority 50%

Only probably in the task got excited with the condition “if it is greater than the previous one, it is necessary to further take into account that the random number can be 100, then if the current number 100 and the previous one 100, then it will be an infinite cycle. Therefore, I think this decision can approach, we check that the previous less than the current $ ARR [$ i-1] & lt; $ num , if not, then we repeat the attempt. Well, the extension condition, if the random number turned out to be 100, then we write it $ num == 100

$ arr = [1];
For ($ i = 1; $ i & lt; 10; $ i ++) {
  $ num = Rand (0, 100);
  ($ Arr [$ i-1] & lt; $ num or $ num == 100)? $ arr [] = $ num: $ i--;
}
Print_R ($ ARR);

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions