P
P
pathpod2018-04-09 13:08:02
PHP
pathpod, 2018-04-09 13:08:02

Smart sorting of an array with the output of 5 elements without repetition. Is it so?

So I used this feature.

// Сортируем по весу
  static function get_sort($names, $n, $ret = array()) {
    if ($n == 0) {
      return $ret;
    } else {
      $totalchance = 0;
      $partialsums = [];
      foreach ($names as $name) {
        $totalchance += $name[1];
        array_push($partialsums, $totalchance);
      }
      $chance = rand(0, $totalchance);
      
      $nameindex = 0;
      foreach ($partialsums as $ps) {
        if ($ps >= $chance) {
          break;
        }
        $nameindex++;
      }
      $name = $names[$nameindex];
      array_push($ret, $name);
      unset($names[$nameindex]);
      $names = array_values($names);
      return self::get_sort($names, $n-1, $ret);
    }
  }

Calling/getting an array: $user_id_list contains an array like this:
$ids = class::get_sort($user_id_list, 5);
Array
(
    [0] => Array
        (
            [0] => 273904544
            [1] => 0.4
        )

    [1] => Array
        (
            [0] => 376650423
            [1] => 0.78
        )

    [2] => Array
        (
            [0] => 396253653
            [1] => 0
        )
......

The array can be large up to 1000+
Description of the function:
From the entire array of ids, 5 random ones are displayed, but the numbers associated with ids are learned, the higher this number, the more likely it is to get into the list than others who have a smaller number.
Is that how it works? I checked, everything seems to be fine, but there are drawbacks, one of them is that when I get a list, whichever of these 5 had a larger number does not necessarily come first in the array, it can be in any other. It turns out that the function selects after each element of the next one starting all over again but excludes repetitions?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question