HackerRank Detecting Valid Latitude and Longitude Pairs Solution

Hello Programmers, In this post, you will know how to solve the HackerRank Detecting Valid Latitude and Longitude Pairs Solution. This problem is a part of the Regex HackerRank Series.

Ezoicreport this adHackerRank Detecting Valid Latitude and Longitude Pairs Solution
HackerRank Detecting Valid Latitude and Longitude Pairs Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Detecting Valid Latitude and Longitude Pairs Solution

Problem

Given a line of text which possibly contains the latitude and longitude of a point, can you use regular expressions to identify the latitude and longitude referred to (if any)?

Input Format
The first line contains an integer N, which is the number of tests to follow.
This is followed by N lines of text. Each line contains a pair of co-ordinates which possibly indicate the latitude and longitude of a place.

Constraints
1 <= N <= 100
The latitude and longitude, if present will always appear in the form of (X, Y) where X and Y are decimal numbers.
For a valid (latitude, longitude) pair:
-90<=X<=+90 and 180<=Y<=180.
They will not contain any symbols for degrees or radians or N/S/E/W. There may or may not be a +/ sign preceding X or Y.
There will be a space between Y and the comma before it.
There will be no space between X and the preceding left-bracket, or between Y and the following right-bracket.
There will be no unnecessary zeros (0) before X or Y.

Output Format
“Valid” where X and Y are the latitude and longitude which you found to be a valid (latitude,longitude) pair.
If the given pair of numbers are not a valid (latitude,longitude) pair, output “Invalid”.

Sample Input

12
(75, 180)
(+90.0, -147.45)
(77.11112223331, 149.99999999)
(+90, +180)
(90, 180)
(-90.00000, -180.0000)
(75, 280)
(+190.0, -147.45)
(77.11112223331, 249.99999999)
(+90, +180.2)
(90., 180.)
(-090.00000, -180.0000)

Sample Output

Valid
Valid
Valid
Valid
Valid
Valid
Invalid
Invalid
Invalid
Invalid
Invalid
Invalid

Explanation
The first six pairs are valid because X, Y satisfy the criteria related to formatting issues, and they satisfy the conditions restricting the numerical range(s) of X and Y. The next six pairs are all invalid because: The first four (among this invalid group) do not satisfy the conditions restricting the numerical range(s) of X and Y. (90., 180.) is invalid because of an extra dot (.) after 90 and 180.
(-090.0000, -180.0000) is invalid because of the redundant zero (0) before 90.

HackerRank Detecting Valid Latitude and Longitude Pairs Solutions in Cpp

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
using namespace std;
bool isNonZero(string str)
{
   if(str.size()==0)
      return false;
   int i=0;
   for(i=0;i<str.length();++i)
      if(str[i]!='0')
         return true;
   return false;   
}
int toNum(string str)
{
   int ans=0,factor=1;
   for(int i=str.length()-1;i>=0;--i)
   {
      int temp=str[i]-'0';
      ans+=temp*factor;
      factor*=10;      
   }
   return ans;
}
bool check(string str,int flag)
{
   int pos=str.find('.'),len=str.length();
   string full,dec;
   if(pos==str.length()-1 || str[0]=='0')
      return false;
   if(pos!=string::npos)
   {
      full=str.substr(0,pos);
      dec=str.substr(pos+1,len-pos-1);
   }
   else
   {
      full=str;
      dec="";
   }
   //cout<<str<<" "<<full<<" "<<dec<<" "<<isNonZero(dec)<<" "<<toNum(full)<<endl;
   if(flag==1 && (full.length()>2 || toNum(full)>90 || (full=="90" && isNonZero(dec))))
      return false; 
   if(flag==2 && (full.length()>3 || toNum(full)>180 || (full=="180" && isNonZero(dec))))
      return false;
   return true;
}
int main() {
   
   string inp,x,y;
   int n,pos;
   cin>>n;
   cin>>ws;
   while(n--)
   {
      getline(cin,inp);
      pos=inp.find(',');
      x=inp.substr(1,pos-1);
      y=inp.substr(pos+2,inp.length()-pos-3);
      if(x[0]=='+' || x[0]=='-')
         x=x.substr(1,x.length()-1);
      if(y[0]=='+' || y[0]=='-')
         y=y.substr(1,y.length()-1);
      if(check(x,1) && check(y,2))
         cout<<"Valid\n";
      else
         cout<<"Invalid\n";
      
   }
   return 0;
}

HackerRank Detecting Valid Latitude and Longitude Pairs Solutions in Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Arrays;
import java.util.regex.Pattern;
public class Solution {
	static BufferedReader br;
	static PrintWriter out;
	static String INPUT = "";
	
	static void solve() throws Exception
	{
		Pattern p = Pattern.compile("\\([-+]?([1-8]?[0-9](\\.[0-9]+)?|90(\\.0+)?), [-+]?(1?([0-7][0-9](\\.[0-9]+)?|80(\\.0+)?)|[1-9]?[0-9](\\.[0-9]+)?)\\)");
		int n = Integer.parseInt(br.readLine());
		for(int i = 0;i < n;i++){
			String line = br.readLine();
			if(p.matcher(line).matches()){
				out.println("Valid");
			}else{
				out.println("Invalid");
			}
		}
	}
	
	public static void main(String[] args) throws Exception
	{
		long S = System.currentTimeMillis();
		br = new BufferedReader(INPUT.isEmpty() ? new InputStreamReader(System.in) : new StringReader(INPUT));
		out = new PrintWriter(System.out);
		
		solve();
		out.flush();
		long G = System.currentTimeMillis();
		tr(G-S+"ms");
	}
	
	static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}

HackerRank Detecting Valid Latitude and Longitude Pairs Solutions in Python

import sys
import re
digit = "[+-]?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?"
prog = re.compile("\((" + digit + "), (" + digit + ")\)\Z")
n = int(sys.stdin.readline())
for s in sys.stdin:
    s = s.rstrip('\n')
    result = prog.match(s)
    if result:
        x = float(result.group(1))
        y = float(result.group(2))
        if (-90 <= x and x<=90
             and -180 <= y and y <= 180):
            print "Valid"
            continue
    print "Invalid"
Ezoicreport this ad

HackerRank Detecting Valid Latitude and Longitude Pairs Solutions in JavaScript

function processData(input) {
    var lines = input.trim().split("\n"),
        n = lines.shift(),
        line, lat, long, ok;
    for (var i = 0; i < n; i++) {
        line = lines[i].replace(/^\(|\)$/g, '').split(", ");
        ok = line[0].match(/^[+-]?(0|[1-9][0-9]*)(\.[0-9]+)?$/);
        ok = ok && line[1].match(/^[+-]?(0|[1-9][0-9]*)(\.[0-9]+)?$/);
        lat = - -line[0];
        long = - -line[1];
        console.log(ok && Math.abs(lat) <= 90 && Math.abs(long) <= 180 ? 'Valid' : 'Invalid');
    }
} 
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});
process.stdin.on("end", function () {
   processData(_input);
});

HackerRank Detecting Valid Latitude and Longitude Pairs Solutions in PHP

<?php
$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$n = fgets($_fp);
$remove = array("+","-","(",")");
for($i=0;$i<$n;$i++){
    $num = split(',',str_replace($remove,'',fgets($_fp)));
    if(!valid($num[0]) || !valid($num[1]))
            print "Invalid \n";
    else print ($num[0] <= 90 && $num[1] <= 180) ? "Valid \n" : "Invalid \n"; 
}
function valid($s){
    $s = str_split($s);
    return ($s[(sizeof($s)-1)] == '.' || $s[0] == '0') ? false : true;
}
?>

Disclaimer: This problem (Detecting Valid Latitude and Longitude Pairs) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Build a Stack Exchange Scraper Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad