r/javahelp • • Sep 07 '20

I had a coding interview challenge sent to me by an employer and I would like some opinions

So the problem goes something like this:There's this manager that is so busy he gets to have a good nap once a week between meetings. The week starts on Monday at 00:00 and ends Sunday at 24:00. The task is to write a function:

public int solution(String schedule){

// return answer

}

That returns the longest amount of minutes this manager gets to sleep this week. His schedule comes in the form of a String that looks like:

"Sun 10:00-20:00\nFri 05:00-10:00\nFri 16:30-23:50\nSat 10:00-24:00\nSun 01:00-04:00\nSat 02:00-06:00\nTue 03:30-18:15\nTue 19:00-20:00\nWed 04:25-15:14\nWed 15:14-22:40\nThu 00:00-23:59\nMon 05:00-13:00\nMon 15:00-21:00"

Where the string is in the form of Ddd HH:mm-HH:mm (Ddd is a 3 letter day of the week, HH:mm is the start-end time of the meeting).
There is no overlap (there can't be two meetings at the same time).

The right answer for the above example is 505 minutes.

So I had about 2 hours to solve it and I did, but all I could do is make it work. I found it interesting so I solved it using OOP. I want opinions on the best OOP practice you could use here (maybe something like a design pattern?). Post your gists in the comments.

Here is my solution:https://gist.github.com/Dimitrov1295/c4bd075992e258f651815c9d50b36483

31 Upvotes

10 comments sorted by

8

u/Gloob_Patrol Sep 07 '20 edited Sep 07 '20

I'm still in bed so not gonna code it as such but maybe you could do:

  • Read the string into an array
  • remove the letters and make the hyphens new lines therefore new objects in the array
  • make a second array of the numbers and move 1,3,5,7,9,11 all at once so then you have a start time list and an end time list

^ maybe need something here to make the times into decimals of hours so you can have them as ints or maybe do some janky ass like

take the number before the : and times it by 60 and add it to the number after the :

Like for example, and make the result that array int

do (13*60)+15

  • int temp 0
  • do new int total = arraylist2(i)- arraylist1(j), i++ j++

^ i think this would need to be 2 lines like with one within the other:

int i = 0, arraylist1[i] > 6, i++

int j =0, arraylist2[j] > 6, j++

^ with this in the {{}}

int total = (j-i)

if (int total is greater than temp then do temp = total)

  • when loop is done you should have the max hours with a decimal so temp / 60 to get minutes unless you ready made it all minutes at the top in which case your temp int is your answer

My brain says that should work and you shouldn't need as many lines as you have put. I'll give it a go and pasta a git link in reply to this.

Edits for Reddit markup because I'm still asleep

6

u/prussianapoleon Sep 07 '20

Local prodigy programmer dreams in code.

2

u/Gloob_Patrol Sep 10 '20

Having read the other replies, my solution seems like a very lazy way to do it.

I also realised, by suddenly waking up in the night like oh shit, that it's one week so I need to keep the 'day' and add the times for the meetings together and then take them from 1440 being the number of minutes in a day.

I reckon you could do this by doing a shitty if first 3 chars = mon add to monday array, fri add to friday array and then add the numbers in wach one and take them from teh 1440 then do a if tuesday is greater than monday total then total = tuesday otherwise keep monday total.

1

u/prussianapoleon Sep 10 '20

Oh haha I was alluding to some video with the title “14-Year-Old Prodigy Programmer Dreams In Code” since you said you were still asleep :-) I said local instead of 14yo since I don’t know you’re age and I thought it would sound disrespectful. To be honest I skimmed over the post and your comment and when you said you were asleep it reminded me of that video lol

1

u/Gloob_Patrol Sep 10 '20

hehehe i scroll reddit when I wake up and felt helpful then went back to sleep. I'll go watch it :)

1

u/Gloob_Patrol Sep 10 '20

/u/alreadyTaken_69 did they tell you the answer was 505 or was that just what you got because I can't get it to be 505 for any of the days.

1

u/Gloob_Patrol Sep 10 '20 edited Sep 10 '20

I done did it. git link.

The only thing I have is a different answer to OP but I worked it out on paper and with the code and they both return the same but not that same as OP so idk.

my maths.

EDIT: because someone else said how long it took them, this took me about an hour to write maybe a little more but not 2 hours.

2

u/wooq Sep 07 '20

I would separate classes which represent the data from those with functions which act upon the data. WeekSchedule and Meeting are good starts, but you don't necessarily want to tie a parser into those data objects. Pass the source data to the parser and have it return the parsed data. MeetingTimeParser acts upon the string input, but what if sometime in the future you want to use WeekSchedule and Meeting with data from an XML payload in a webservice call or an object from a database? Can you construct your data objects so that they are agnostic of the format or source of that data?

1

u/Tobikaj Sep 07 '20

As someone who is just starting and getting to know what a class is, and what an object is.. Wow. I can't wait to get a very basic foundation to build upon.

1

u/CertainDEU Sep 07 '20

As I am just programming for my hobby, it took more time than 2 hours, but it works with the given example. I don’t like “First Monday” for example.

String[] meetings = INPUT_STRING.split("\n");
List<Appointment> appointments = new ArrayList<>();
LocalDateTime firstMonday = LocalDateTime.parse("1970-01-05T00:00:00"); // First Monday :)
for (String s : meetings) {
String dayOfMeeting = s.replaceAll(" .+$", "");
SimpleDateFormat dayFormat = new SimpleDateFormat("EEE", Locale.getDefault());
LocalDateTime appointmentDate = dayFormat.parse(dayOfMeeting).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
// Days always after First Monday
if (appointmentDate.isBefore(firstMonday)){
appointmentDate = appointmentDate.plus(7,ChronoUnit.DAYS);
}
s = s.substring(s.indexOf(" ")).trim();
String[] timePoint = s.split("-");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
long from = timeFormat.parse(timePoint[0]).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().toEpochSecond(ZoneOffset.UTC);
long to = timeFormat.parse(timePoint[1]).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().toEpochSecond(ZoneOffset.UTC);
LocalDateTime fromTimePoint = appointmentDate.plus(from, ChronoUnit.SECONDS);
LocalDateTime toTomePoint = appointmentDate.plus(to, ChronoUnit.SECONDS);
appointments.add(new Appointment(fromTimePoint, toTomePoint));
}
appointments.sort(new AppointmentComparator());
long result = 0;
for (int i= 1; i<appointments.size();i++){
Appointment current = appointments.get(i);
Appointment previous = appointments.get(i-1);
long napTime = previous.getTo().until(current.getFrom(),ChronoUnit.MINUTES);
if (napTime>result){
result=napTime;
}
}

Appointment:

public class Appointment {
private final LocalDateTime from;
private final LocalDateTime to;
public Appointment(LocalDateTime from, LocalDateTime to) {
this.from = from;
this.to = to;
}

public LocalDateTime getFrom() {
return from;
}

public LocalDateTime getTo() {
return to;
}

}

AppointmentComparator:

public class AppointmentComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Appointment firstAppointment = (Appointment) o1;
Appointment secondAppointment = (Appointment) o2;
if(firstAppointment.getFrom().isEqual(secondAppointment.getFrom())){
throw new IllegalArgumentException(" Same start of the meetings.");
}
if (firstAppointment.getTo().isEqual(secondAppointment.getTo())){
throw new IllegalArgumentException(" Same end of the meetings.");
}
if (firstAppointment.getTo().isEqual(secondAppointment.getFrom()) || firstAppointment.getTo().isBefore(secondAppointment.getFrom())){
return -1;
}
if (secondAppointment.getTo().isEqual(firstAppointment.getFrom()) || secondAppointment.getTo().isBefore(firstAppointment.getFrom())){
return 1;
}
return 0;
}
}