Home > front end >  Get random elements from array and show how many times occurs in the array
Get random elements from array and show how many times occurs in the array

Time:08-10

I have long string which I split after each 4th char. After that I want to take 3 random of them and show how many times are in the array.

What I have is

$string = "AAAAAAABAAACAAADAAAEAAAFAAAGAAAHAAAIAAAJAAAKAAALAAAMAAANAAAOAAAPAAAQAAARAAASAAATAAAUAAAVAAAWAAAXAAAYAAAZAAAaAAAbAAAcAAAdAAAeAAAfAAAgAAAhAAAiAAAjAAAkAAAlAAAmAAAnAAAoAAApAAAqAAArAAAsAAAtAAAuAAAvAAAwAAAxAAAyAAAzAABAAABBAABCAABDAABEAABFAABGAABHAABIAABJAABKAABLAABMAABNAA";
$segmentLength = 3;
$totalLength = strlen($string);
for ($i = 0; $i < $totalLength; $i  = $segmentLength) {
    $result[] = substr($string, min($totalLength - $segmentLength, $i), $segmentLength);
}

print_r(array_rand(array_count_values($result), 4));

array_count_values($result) output is

Array
(
    [AAA] => 19
    [ABA] => 1
    [AAC] => 1
    ........
    [AAL] => 1
    [MAA] => 1
    [AAB] => 4
)

I'm trying with print_r(array_rand(array_count_values($result), 4)); to output

Array
    (
        [AAA] => 19
        [ABA] => 1
        [AAC] => 1
        [AAB] => 4
    )

or

Array
    (
        [ABA] => 1
        [AAC] => 1
        [AAL] => 1
        [MAA] => 1
    )

instead I get

Array
(
    [0] => AHA
    [1] => AAa
    [2] => zAA
    [3] => BGA
)
...
Array
(
    [0] => GAA
    [1] => AxA
    [2] => CAA
    [3] => BGA
)
... so on

CodePudding user response:

You could store the result of array_count_values($result); to a variable and then get a random set of keys from that result. Then loop through that random list of keys and generate your desired output. For example:

$string = "AAAAAAABAAACAAADAAAEAAAFAAAGAAAHAAAIAAAJAAAKAAALAAAMAAANAAAOAAAPAAAQAAARAAASAAATAAAUAAAVAAAWAAAXAAAYAAAZAAAaAAAbAAAcAAAdAAAeAAAfAAAgAAAhAAAiAAAjAAAkAAAlAAAmAAAnAAAoAAApAAAqAAArAAAsAAAtAAAuAAAvAAAwAAAxAAAyAAAzAABAAABBAABCAABDAABEAABFAABGAABHAABIAABJAABKAABLAABMAABNAA";
$segmentLength = 3;
$totalLength = strlen($string);
for ($i = 0; $i < $totalLength; $i  = $segmentLength) {
    $result[] = substr($string, min($totalLength - $segmentLength, $i), $segmentLength);
}

$countedValues = array_count_values($result);

$randValues = array_rand($countedValues, 4);

$output = [];
for ($i = 0; $i < count($randValues); $i  ) {
    $key = $randValues[$i];
    $output[$key] = $countedValues[$key];
}

print_r($output);
  • Related