zaterdag 28 februari 2015

Why I like Python better than PHP: Bingo!

From the real world: How do you create a 6x6 array where every row contains six random numbers  in  the range 1-19, 20-29, etc.

In Python you pretty much do what the problem description says:
for each set of ten numbers pick a sorted set of 6 random numbers:

import random
for t in range(10, 70, 10):
data.append(sorted(random.sample(range(t, 9+t), 6)))

In PHP things are much more complicated because the endless list of inconsistent behaviour.
range() creates an array of values, that's ok.
array_rand() picks random values from the array? No, it picks random KEYS from the array, which means you have to loop through the keys to get the values, which is bull. You can flip the array, but wtf?
So you shuffle the array, but shuffle modifies an array, it does not return a new array, so the rnge() must be materialized into a variable.
Ditto for the sorting.

Put it all together and you get this:

$data = [];
foreach (range(10, 70, 10) as $t) {
$tmp = range($t, $t+9);
$tmp = array_slice($tmp, 0, 6);
$data[] = $tmp;