Detecting Valid Latitude and Longitude Pairs

  • + 0 comments

    Java 15:

    import java.io.*;
    import java.util.*;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class Solution {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt(); scanner.nextLine();
            String x = "([+-]?((90(\\.0+)?)|([1-8]?[0-9](\\.[0-9]+)?)))";
            String y = "([+-]?((180(\\.0+)?)|((1[0-7][0-9]|[1-9]?[0-9])(\\.[0-9]+)?)))";
            String regex = "^\\(" +x+ ",\s" +y+ "\\)$";
            Pattern pattern = Pattern.compile(regex);
            for(int i=0;i<n;i++)
            {   Matcher matcher = pattern.matcher(scanner.nextLine());
                if (matcher.find()) System.out.println("Valid");
                else System.out.println("Invalid");
            }
        }
    }
    
    /*
    ------------------Regex for x------------------------
    x = "(
            [+-]?
            (
                ( 90              (\\.0+)?     )       |
                ( [1-8]? [0-9]    (\\.[0-9]+)? )
            )
         )"
        
    x is a floating number between (-90,+90)
    [+-]? means there may or may not be sign
    
    First think of integer number between (-90,+90). Ignoring sign, 
        One digit combination: [0-9]
        Two digit combination for 10 to 89 : [1-8][0-9]
        Ninty: 90
    That is, ( 90 | [1-8]?[0-9] ) 
    
    Now think about floating points. \\. denotes original dot.
        If the number is 90, floating point should never cross 0. Only 90.00000 is allowed.
        (\\.0+)? means ".0" or ".00" or ".000" or ...
    
        For any number other than 90, Floating point can be made up of any digit. 
        So (\\.[0-9]+) means any decimal point
    
    Whole thing should be covered by () to avoid ambiguity while concatenating this x to the regex for (x,y).
    
    
    ------------Regex for y------------------
    y = "(
            [+-]?
            (   (180                                (\\.0+)?)       |
                ( ( 1[0-7][0-9] | [1-9]?[0-9] )     (\\.[0-9]+)?)
            )
        )"
    y is a floating number between (-180,+180)
    
    Integer (-180,+180) ignoring the sign:
        180
        1[0-7][0-9]
        [1-9][0-9]
        [0-9]
        So combining 180 or 1[0-7][0-9] or [1-9]?[0-9]
    
    Floating point for 180 is .0000. So (\\.0+)?)
    Floating point for others is (\\.[0-9]+)?)
    */