Amazon Interview Question
SDE-2sCountry: United States
Interview Type: Phone Interview
You could just use regex to do this:
Pattern pattern = Pattern.compile("(from:-?\\d+.\\d+,-?\\d+.\\d+)|(to:-?\\d+.\\d+,-?\\d+.\\d+)");
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
if(matcher.group(1) != null) System.out.println(matcher.group(1));
if(matcher.group(2) != null) System.out.println(matcher.group(2));
}
Focus was to write a shell command/ script. I gave simple one:
$ IFS=$'\n'; for i in `cat log`; do from=`echo "$i" | grep -o 'from:[^ ]*'`; to=`echo "$i" | grep -o 'to:[^ ]*' $i`; echo "$from $to"; done
He said it might work but it doesn't any corrections here?
perl -wnl -e '
m#from:\K[0-9]+(\.[0-9]+)?,[0-9]+(\.[0-9]+)?# and $from=$&;
m#to:\K[0-9]+(\.[0-9]+)?,[0-9]+(\.[0-9]+)?# and $to=$&;
print "( $from , $to )" ' test
overhere test is the name of the log file
\K is a special regex meta character that matches but does not output its preceding group
Output:
( 123.54,78.21 , 56.82,124.54 )
( 11.54,45.84 , 115.87,98.65 )
use Boyer–Moore (BM) search algorithm.
- zr.roman December 16, 2015O(n/m).
In loop in each iteration use BM twice:
1) find nearest "from:" entry,
2) find nearest "to:" entry. (Start from position found in search from step #1).
Collect a pair and go to next iteration, which starts at the position found in search #2 from previous iteration.