Codility Passing Car Problem in Java
codemania
Asked: May 27, 20232023-05-27T09:40:41+00:00
2023-05-27T09:40:41+00:00In: Education
Codility Passing Car Problem in Java
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is the Java Program to Solve the passing Car Codility Problem.
Given a boolean array of 0’s and 1’s, where 0’s represent cars going to east and 1’s represent cars going to the west.
Find out the pairs of the cars that will cross each other, that is, the pairs of cars going in another direction.
Example:
ArrayOne = [1, 0, 1, 1, 0, 0, 1, 0]
Output
5
Explanation:
The last 0 has no 1 following it, so their will be no car pairs crossing each other.
The 0’s at positions 5 and 6, have a 1 following them, so there will be two car pairs crossing each other.
The 0 at position 2, have three 1’s following it, so there will be 3 car pairs crossing each other.
So, total 5 car pairs are crossing each other.
Traverse from the right end of the array and count the number of 1’s encountered, whenever a 0 is encountered, add the number of 1’s obtained till that point to the number of pairs and continue traversing.
Here is the source code of the Java Program to Solve the passing Car Codility Problem. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java Program to Solve the passing Car Codility Problem
// Function to count the number of pairs
{
count++;
}
}
}
}
// Function to read input and display the output
}
}
}
}
}
1. In function passingPairs(), the variable pairs and count are initialized to zero.
2. The loop for(i = array.length-1; i>=0; i–) traverses the array from right to left.
3. The condition if(array[i] == 1) counts the number of 1’s encountered till present.
4. The else part, indicating the value zero, adds the number of 1’s encountered to the pairs, since these car pairs are travelling in the opposite direction.
5. The pairs variable is returned.
Time Complexity: O(n) where n is the number of elements in the array.