📜 ⬆️ ⬇️

Divide the number by the specified number of cubes

I came across a problem here, some interesting solutions became different from mine, and, preferably, in a different language.

The condition is quite simple. There is a random number and a specified number of game blocks. The value of each cube can be from 1 to 6. You need to split the number so that the output is an array of values ​​for each cube. And with each call, the values ​​of these cubes must be random.
For example:
The number 18 and 4 dice. Answer: [6,3,5,4];

My solution is under the cut and spoiler ...

Hidden text
public function splitDices($number, $dicesCount) { $dices = []; if ($number > $dicesCount * 6 || $number < $dicesCount) throw new \Exception('Wrong number for split'); $j = 0; for ($i = $dicesCount - 1 ; $i > 0; $i--) { $diff = $number - $i * 6; if ($diff > 0) $dices[$j] = rand($diff, 6); else { if ($number - $i * 1 > 6) $max = 6; elseif ($number - $i * 1 <= 0) $max = $number; else $max = $number - $i * 1; $dices[$j] = rand(1, $max); } if ($i > 1) $number -= $dices[$j]; $j++; } $dices[$j] = $number - $dices[$j-1]; return $dices; } 


')

Source: https://habr.com/ru/post/226171/


All Articles