Passed
Push — master ( 857f8e...183174 )
by Alexey
03:16
created

Demo::randomWalk()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 15
rs 9.6111
cc 5
nc 7
nop 2
1
<?php
2
3
namespace backend\widgets\chart\flot\data;
4
5
/**
6
 * Class Demo
7
 *
8
 * @package modules\main\models\backend
9
 */
10
class Demo
11
{
12
    /**
13
     * Demo Random Data
14
     *
15
     * @param array $data
16
     * @param int $totalPoints
17
     * @return array
18
     */
19
    public static function getRandomData($data = [], $totalPoints = 100)
20
    {
21
        if (is_null($data)) {
0 ignored issues
show
introduced by
The condition is_null($data) is always false.
Loading history...
22
            $data = [];
23
        }
24
        if (count($data) > 0) {
25
            $data = array_slice($data, 1);
26
        }
27
        $randomWalk = self::randomWalk($totalPoints, $data);
28
        // Zip the generated y values with the x values
29
        $res = [];
30
        foreach ($randomWalk as $key => $items) {
31
            $items[0] = $key;
32
            $res[] = $items;
33
        }
34
        return $res;
35
    }
36
37
    /**
38
     * Do a random walk
39
     *
40
     * @param array $data
41
     * @param int $totalPoints
42
     * @return array
43
     */
44
    public static function randomWalk($totalPoints = 100, $data = [])
45
    {
46
        $count = count($data);
47
        while ($count < $totalPoints) {
48
            $prev = $count > 0 ? (int)$data[$count - 1] : $totalPoints / 2;
49
            $val = $prev + self::randomFloat(0, $totalPoints);
50
            if ($val < 0) {
51
                $val = 0;
52
            } elseif ($val > $totalPoints) {
53
                $val = $totalPoints;
54
            }
55
            $data[] = [$count, $val];
56
            $count++;
57
        }
58
        return $data;
59
    }
60
61
    /**
62
     * Calculating a random floating point number
63
     *
64
     * @param int $min
65
     * @param int $max
66
     * @return float|int|mixed
67
     */
68
    public static function randomFloat($min = 0, $max = 1)
69
    {
70
        return $min + mt_rand() / mt_getrandmax() * ($max - $min);
71
    }
72
}
73