Count pairs of coordinates connected by a line with slope in the range [-K, K]
Given an integer K, and two arrays X[] and Y[] both consisting of N integers, where (X[i], Y[i]) is a coordinate in a plane, the task is to find the total number of pairs of points such that the line passing through them has a slope in the range [-K, K].
Examples:
Input: X[] = {2, 1, 0}, Y[] = {1, 2, 0}, K = 1
Output: 2
Explanation:
The set of pairs satisfying the given condition are [(0, 0), (2, 1)] and [(1, 2), (2, 1)].
Input: X[] = {2, 4}, Y[][] = {5, 6}, K = 1
Output: 1
Approach: The idea is to traverse through all pairs of points and check whether their slope lies in the range [-K, K] or not. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findPairs(vector< int > x, vector< int > y,
int K)
{
int n = x.size();
int ans = 0;
for ( int i = 0; i < n; ++i) {
for ( int j = i + 1; j < n; ++j) {
if (K * abs (x[i] - x[j])
>= abs (y[i] - y[j])) {
++ans;
}
}
}
cout << ans;
}
int main()
{
vector< int > X = { 2, 1, 0 },
Y = { 1, 2, 0 };
int K = 1;
findPairs(X, Y, K);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void findPairs( int [] x, int [] y,
int K)
{
int n = x.length;
int ans = 0 ;
for ( int i = 0 ; i < n; ++i) {
for ( int j = i + 1 ; j < n; ++j) {
if (K * Math.abs(x[i] - x[j])
>= Math.abs(y[i] - y[j])) {
++ans;
}
}
}
System.out.print(ans);
}
public static void main(String[] args)
{
int [] X = { 2 , 1 , 0 };
int [] Y = { 1 , 2 , 0 };
int K = 1 ;
findPairs(X, Y, K);
}
}
|
Python3
def findPairs(x, y, K):
n = len (x)
ans = 0
for i in range (n):
for j in range (i + 1 , n):
if (K * abs (x[i] - x[j]) > = abs (y[i] - y[j])):
ans + = 1
print (ans)
if __name__ = = '__main__' :
X = [ 2 , 1 , 0 ]
Y = [ 1 , 2 , 0 ]
K = 1
findPairs(X, Y, K)
|
C#
using System;
class GFG{
static void findPairs( int [] x, int [] y,
int K)
{
int n = x.Length;
int ans = 0;
for ( int i = 0; i < n; ++i)
{
for ( int j = i + 1; j < n; ++j)
{
if (K * Math.Abs(x[i] - x[j]) >=
Math.Abs(y[i] - y[j]))
{
++ans;
}
}
}
Console.WriteLine(ans);
}
public static void Main(String []args)
{
int [] X = { 2, 1, 0 };
int [] Y = { 1, 2, 0 };
int K = 1;
findPairs(X, Y, K);
}
}
|
Javascript
<script>
function findPairs(x, y, K)
{
let n = x.length;
let ans = 0;
for (let i = 0; i < n; ++i) {
for (let j = i + 1; j < n; ++j) {
if (K * Math.abs(x[i] - x[j])
>= Math.abs(y[i] - y[j])) {
++ans;
}
}
}
document.write(ans);
}
let X = [ 2, 1, 0 ], Y = [ 1, 2, 0 ];
let K = 1;
findPairs(X, Y, K);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Last Updated :
24 Mar, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...