Multi Dimensional Array in Random Order

multi dimensional array in random order

shuffle() is the way to go here. It prints 1 because shuffle changes the array in-place and returns a boolean, as it is written in the documentation:

Returns TRUE on success or FALSE on failure.

I suggest to also read the documentation of array_rand():

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.


Always read documentation if you use built-in functions. Don't just assume how the work. I bet it took more time to write the question than looking this up.

Sorting multi-dimensional array by random key

You need to sort the array by key value. So if you had an array

$year = ["7" => [], "9" => [], "3" => []];

you would go by

ksort($year); // ["3" => [], "7" => [], "9" => []]

See:
https://www.php.net/manual/en/function.ksort.php

And a running example:
http://sandbox.onlinephpfunctions.com/code/216a48077d871dbd871445013fc838ddb1130bd4

If you need to apply for multidimensional arrays, I suggest you use a recursive function like from this answer:
https://stackoverflow.com/a/4501406/5042856

// Note this method returns a boolean and not the array
function recur_ksort(&$array) {
foreach ($array as &$value) {
if (is_array($value)) recur_ksort($value);
}
return ksort($array);
}

php Shuffle multi-dimensional array whilst maintaining column order

$lee[] = array("question" => "3", "appeared" => "0");
$lee[] = array("question" => "4", "appeared" => "1");
$lee[] = array("question" => "5", "appeared" => "0");
$lee[] = array("question" => "6", "appeared" => "0");
$lee[] = array("question" => "7", "appeared" => "1");
$lee[] = array("question" => "8", "appeared" => "1");
$lee[] = array("question" => "9", "appeared" => "2");
$lee[] = array("question" => "10", "appeared" => "0");
$lee[] = array("question" => "12", "appeared" => "3");
$lee[] = array("question" => "15", "appeared" => "3");
$lee[] = array("question" => "19", "appeared" => "3");

$parts = [];
// Group items by `appeared` value
foreach ($lee as $item) {
$parts[$item['appeared']][] = $item;
}

// shuffle each group
foreach ($parts as &$part) {
shuffle($part);
}

// sort array by keys in ascending order
ksort($parts);
// merge groups to one array
print_r(call_user_func_array('array_merge', $parts));

Numpy shuffle multidimensional array by row only, keep column order unchanged

You can use numpy.random.shuffle().

This function only shuffles the array along the first axis of a
multi-dimensional array. The order of sub-arrays is changed but their
contents remains the same.

In [2]: import numpy as np                                                                                                                                                                                  

In [3]:

In [3]: X = np.random.random((6, 2))

In [4]: X
Out[4]:
array([[0.71935047, 0.25796155],
[0.4621708 , 0.55140423],
[0.22605866, 0.61581771],
[0.47264172, 0.79307633],
[0.22701656, 0.11927993],
[0.20117207, 0.2754544 ]])

In [5]: np.random.shuffle(X)

In [6]: X
Out[6]:
array([[0.71935047, 0.25796155],
[0.47264172, 0.79307633],
[0.4621708 , 0.55140423],
[0.22701656, 0.11927993],
[0.20117207, 0.2754544 ],
[0.22605866, 0.61581771]])

For other functionalities you can also check out the following functions:

  • random.Generator.shuffle

  • random.Generator.permutation

  • random.Generator.permuted

The function random.Generator.permuted is introduced in Numpy's 1.20.0 Release.

The new function differs from shuffle and permutation in that the
subarrays indexed by an axis are permuted rather than the axis being
treated as a separate 1-D array for every combination of the other
indexes. For example, it is now possible to permute the rows or
columns of a 2-D array.

jquery multidimensional array shuffle random

If you simply want to run an operation over all the elements in an array, then you should use map or forEach. I'm sure jquery provides shims for these methods in older browsers. So if we assume you're using your original fisherYates function unaltered, we might have something like this:

var multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
multArr.forEach(fisherYates);

On accessing the elements, you're almost right, but you have one set too many of brackets :

multArr[1]; // == [6, 7, 8, 9, 10]
multArr[1][3]; // == 9

I wouldn't speculate about the performance, if you're really worried you should put together a jsperf test case.

Sort and shuffle multidimensional array

Based on idea @Hugo's answer about using random weight:

$array = array(
array('id' => 101, 'bid' => 0.5, 'priority' => 5),
array('id' => 102, 'bid' => 0.4, 'priority' => 4),
array('id' => 103, 'bid' => 0.4, 'priority' => 4),
array('id' => 104, 'bid' => 0.4, 'priority' => 4),
array('id' => 105, 'bid' => 0.3, 'priority' => 5),
array('id' => 106, 'bid' => 0.3, 'priority' => 5),
array('id' => 107, 'bid' => 0.2, 'priority' => 5),
array('id' => 108, 'bid' => 0.7, 'priority' => 5),
array('id' => 108, 'bid' => 0.1, 'priority' => 4)
);
function cmp(&$a, &$b) { # notice the use of & in function signature
if ($a['bid'] - $b['bid']) {
return $a['bid'] - $b['bid'] > 0 ? 1 : -1; # bid is different, sort using bid
} else if ($a['priority'] - $b['priority']) {
return $a['priority'] - $b['priority'] > 0 ? 1 : -1; # priority is different, sort using priority
} else {
if (isset($a['rw']) == false) {
$a['rw'] = rand(1, 100); # assign random tie breaker
}
if (isset($b['rw']) == false) {
$b['rw'] = rand(1, 100); # assign random tie breaker
}
if ($a['rw'] - $b['rw']) {
return $a['rw'] - $b['rw'] > 0 ? 1 : -1; # sort using random weight
} else {
return 0;
}
}
}
usort($array, 'cmp');
var_dump($array);

Output

array(9) {
[0]=>array(3) {["id"]=>int(108) ["bid"]=>float(0.1) ["priority"]=>int(4)}
[1]=>array(3) {["id"]=>int(107) ["bid"]=>float(0.2) ["priority"]=>int(5)}
[2]=>array(4) {["id"]=>int(106) ["bid"]=>float(0.3) ["priority"]=>int(5) ["rw"]=>int(70)}
[3]=>array(4) {["id"]=>int(105) ["bid"]=>float(0.3) ["priority"]=>int(5) ["rw"]=>int(73)}
[4]=>array(4) {["id"]=>int(103) ["bid"]=>float(0.4) ["priority"]=>int(4) ["rw"]=>int(29)}
[5]=>array(4) {["id"]=>int(104) ["bid"]=>float(0.4) ["priority"]=>int(4) ["rw"]=>int(67)}
[6]=>array(4) {["id"]=>int(102) ["bid"]=>float(0.4) ["priority"]=>int(4) ["rw"]=>int(80)}
[7]=>array(3) {["id"]=>int(101) ["bid"]=>float(0.5) ["priority"]=>int(5)}
[8]=>array(3) {["id"]=>int(108) ["bid"]=>float(0.7) ["priority"]=>int(5)}
}

Shuffle multidimensional array by columns and update list of indexes accordingly

Get the random permutations for the column indices with np.random.permutation -

col_idx = np.random.permutation(a.shape[1])

Get shuffled input array -

shuffled_a = a[:,col_idx]

Then, simply index into the sorted indices for col_idx with idxs for the traced back version -

shuffled_idxs = col_idx.argsort()[idxs]

Sample run -

In [236]: a # input array
Out[236]:
array([[ 0.1534, 0.2118, 0.1985, 0.5246, 0.2445],
[ 0.1746, 0.4573, 0.2691, 0.8162, 0.8899],
[ 0.501 , 0.2246, 0.2404, 0.0952, 0.959 ]])

In [237]: col_idx = np.random.permutation(a.shape[1])

# Let's use the sample permuted column indices to verify desired o/p
In [238]: col_idx = np.array([4,2,3,1,0])

In [239]: shuffled_a = a[:,col_idx]

In [240]: shuffled_a
Out[240]:
array([[ 0.2445, 0.1985, 0.5246, 0.2118, 0.1534],
[ 0.8899, 0.2691, 0.8162, 0.4573, 0.1746],
[ 0.959 , 0.2404, 0.0952, 0.2246, 0.501 ]])

In [241]: col_idx.argsort()[idxs]
Out[241]: array([4, 2, 0])


Related Topics



Leave a reply



Submit