NumberOfDiscIntersections   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 0
cbo 0
dl 0
loc 34
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C solution() 0 31 7
1
<?php
2
3
namespace Lesson04;
4
5
class NumberOfDiscIntersections
6
{
7
    public function solution($A)
8
    {
9
        $N = count($A);
10
        $numberOfIntersectingDiscs = 0;
11
        $numberOfDiscsStartedAt = array_fill(0, $N, 0);
12
        $numberOfDiscsEndedAt = array_fill(0, $N, 0);
13
14
        for ($i = 0; $i < $N; $i++) {
15
            $startingIndex = $i - $A[$i] > 0 ? $i - $A[$i] : 0;
16
            $endingIndex = $i + $A[$i] < $N - 1 ? $i + $A[$i] : $N - 1;
17
            $numberOfDiscsStartedAt[$startingIndex]++;
18
            $numberOfDiscsEndedAt[$endingIndex]++;
19
        }
20
21
        $discsAtCurrentPosition = 0;
22
23
        for ($i = 0; $i < $N; $i++) {
24
            if ($numberOfDiscsStartedAt[$i] > 0) {
25
                $numberOfIntersectingDiscs += $discsAtCurrentPosition * $numberOfDiscsStartedAt[$i];
26
                $numberOfIntersectingDiscs +=
27
                    $numberOfDiscsStartedAt[$i] * ($numberOfDiscsStartedAt[$i] - 1) / 2;
28
                if ($numberOfIntersectingDiscs > 10000000) {
29
                    return -1;
30
                }
31
                $discsAtCurrentPosition += $numberOfDiscsStartedAt[$i];
32
            }
33
            $discsAtCurrentPosition -= $numberOfDiscsEndedAt[$i];
34
        }
35
36
        return $numberOfIntersectingDiscs;
37
    }
38
}
39