# PassingCars – Codility – Solution

Java solution to Codility PassingCars problem (Lesson 5 – Prefix Sums) which scored 100%. The problem is to calculate the number of passing cars on the road. The strategy is to keep a running count of eastbound cars and then for each westbound car encountered, the number of car passes will be the running count of eastbound cars, added to the running count of total passes.

```12345678910111213141516package com.codility.lesson05.prefixsums;

public class PassingCars {
public int solution(int[] A) {
int zeros = 0;
int carPasses = 0;

for(int i=0; i<A.length; i++) { if(A[i] == 0) { zeros++; } else if(A[i] == 1) { //for every 1 - there will be an extra car pass for ALL the 0's that came before it carPasses += zeros; if(carPasses > 1000000000) {
return -1;
}
}
else throw new RuntimeException("shouldn't reach here");
}
return carPasses;
}
}

```

TestNG test cases for this problem which all passed:

```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748package test.com.codility.lesson05.prefixsums;

import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.codility.lesson05.prefixsums.PassingCars;

public class PassingCarsTests {
private PassingCars solution;

@BeforeTest
public void setUp() {
solution = new PassingCars();
}

@DataProvider(name = "test1")
public Object [][] createData1() {
return new Object [][] {
new Object [] {  new int [] {    0, 1, 0, 1, 1 }, 5 },
new Object [] {  new int [] { 1, 0, 0, 1, 0, 1 }, 5 },
new Object [] {  new int [] { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }, 15 },
new Object [] {  new int [] { 1, 1, 0, 1 }, 1 },
new Object [] {  new int [] { 0, 1, 1, 1 }, 3 },
new Object [] {  new int [] { 0, 1, 1, 1, 0 }, 3 },
new Object [] {  new int [] { 0, 1, 1, 1, 0, 1 }, 5 },
new Object [] {  new int [] { 0, 1, 1, 1, 0, 1, 1 }, 7 },
new Object [] {  new int [] { 0, 1, 1, 1, 0, 1, 1, 1 }, 9 },
new Object [] {  new int [] { 0, 1, 1, 1, 0, 1, 1, 1, 0 }, 9 },
new Object [] {  new int [] { 0, 1, 1, 1, 0, 1, 1, 1, 0, 0 }, 9 },
new Object [] {  new int [] { 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1 }, 13 },

//no passing cars
new Object [] {  new int [] {       1 }, 0 },
new Object [] {  new int [] {       0 }, 0 },
new Object [] {  new int [] {    0, 0 }, 0 },
new Object [] {  new int [] {    1, 1 }, 0 },
new Object [] {  new int [] { 1, 1, 0 }, 0 },

};
}

@Test(dataProvider = "test1")
public void verifySolution(int [] pA, int pExpected) {
Assert.assertEquals(solution.solution(pA), pExpected);
}
}

```