Created
January 17, 2019 04:41
-
-
Save azizasm/1fba096e22f9ecca54dddd4591842ef6 to your computer and use it in GitHub Desktop.
Phone Bill Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.DateFormat; | |
import java.text.SimpleDateFormat; | |
import java.util.Arrays; | |
import java.util.Date; | |
import java.util.HashMap; | |
class Solution { | |
/** | |
* Solutions | |
* @param S | |
* @return | |
*/ | |
public int solution(String S) { | |
int total = 0, max = 0; | |
int sec; | |
String[] lines = S.split("\n"); | |
HashMap<String, Integer> phonesTime = new HashMap<>(); | |
Arrays.stream(lines).map(s -> s.split(",")).forEach(line -> { | |
String phone = line[1]; | |
int time = timeToSecs(line[0]); | |
//Sum up same phone number into one | |
if (phonesTime.containsKey(phone)) { | |
int oldTime = phonesTime.get(phone); | |
phonesTime.put(phone, oldTime + time); | |
} else { | |
phonesTime.put(phone, time); | |
} | |
}); | |
for (String key : phonesTime.keySet()) { | |
sec = phonesTime.get(key); | |
if (sec >= max) { | |
max = sec; | |
} | |
total += secsToCents(sec); | |
} | |
//remove promotion rebate | |
total -= secsToCents(max); | |
return total; | |
} | |
/** | |
* Business logic | |
* @param sec | |
* @return | |
*/ | |
private static int secsToCents(int sec) { | |
if (sec < 300) return sec * 3; | |
else if (sec % 60 == 0) return (sec / 60) * 150; | |
else return ((sec / 60) + 1) * 150; | |
} | |
/** | |
* timeToSecs | |
* @param time | |
* @return | |
*/ | |
private static int timeToSecs(String time) { | |
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); | |
Date date = null; | |
Date reference = null; | |
try { | |
reference = dateFormat.parse("00:00:00"); | |
date = dateFormat.parse(time); | |
}catch ( Exception ex){ | |
} | |
long seconds = (date.getTime() - reference.getTime()) / 1000L; | |
return Math.toIntExact(seconds); | |
} | |
public static void main(String[] args) { | |
String S = "00:01:07,400-234-090\n" + | |
"00:05:01,701-080-080\n" + | |
"00:05:00,400-234-090"; | |
Solution s = new Solution(); | |
int solution = s.solution(S); | |
System.out.println(solution); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment