Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Disheartened

Options
13

Comments

  • Closed Accounts Posts: 22,651 ✭✭✭✭beauf


    Is there no library that has a isDate/isTime function to check valid time formats.
    Modify the string so its this format and pass it into such a function.
    I assume you can't do this as you don't have access to such libraries.


  • Registered Users Posts: 6,016 ✭✭✭Talisman


    smacl wrote: »
    Person who told you that was easy might need to define easy.
    Your working assumptions are possibly complicating the problem - you could make two assumptions that simplify the task:
    1. In the U.S. the city block sizes are the same within a city - for argument sake you could give the city block a length of 250m and a width of 150m so your graph edges have two possible lengths.
    2. You can discount traffic levels as an influencing factor because the emergency services sirens generally signal for the traffic to get the hell out of the way.

    Now the question becomes how many of the graph edges could an emergency services vehicle traverse in 10 minutes. After that calculation you know what size grid area a fire station can cover so all you need to do is work out how many of those grids are needed to fit in the map.


  • Registered Users Posts: 7,157 ✭✭✭srsly78


    Yeah it says estimate, so you might get away with using the 'manhattan distance': https://en.wikipedia.org/wiki/Taxicab_geometry


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    beauf wrote: »
    Could you not average journey times, and create a circle that defines this range from station for each station.
    Then work out how many circles are need to overlay the area of the city map. Could be square either.

    Don't think so. To compute the average journey time from any one potential location, you need to compute the journey time between than location and every other location and then divide by the number of locations minus 1. Given every location is a potential station location this still amounts a high computational complexity, though there are plenty of strong optimisations. Even then, the spec says within 10 minutes which implies maximum allowable response time rather than average.

    You can't use radius either as this doesn't correlate with travel time by road. If you could you could use something like a Voronoi diagram to get areas serviced by a specific station.

    If the question came from Google, could be that it was devised by an American who lived in a city laid out in blocks which is the case with many American cities, and you could just divide into equal areas. Not going to work for many of the major European cities ;)


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    Talisman wrote: »
    Your working assumptions are possibly complicating the problem - you could make two assumptions that simplify the task:
    1. In the U.S. the city block sizes are the same within a city - for argument sake you could give the city block a length of 250m and a width of 150m so your graph edges have two possible lengths.
    2. You can discount traffic levels as an influencing factor because the emergency services sirens generally signal for the traffic to get the hell out of the way.

    Now the question becomes how many of the graph edges could an emergency services vehicle traverse in 10 minutes. After that calculation you know what size grid area a fire station can cover so all you need to do is work out how many of those grids are needed to fit in the map.

    Was thinking the same thing, as per my last post. Try applying that logic or Manhattan distances to Dublin, Paris or Rome :p


  • Advertisement
  • Registered Users Posts: 6,016 ✭✭✭Talisman


    smacl wrote: »
    Was thinking the same thing, as per my last post. Try applying that logic or Manhattan distances to Dublin, Paris or Rome :p
    For old European cities the same principle applies but rather than using the length and width of a block you would need a dataset with the length of each road - the emergency services use the main roads so you focus on them.

    You don't need to get a perfect answer - the primary motivation for such questions is to see how the candidate approaches the problem. They want to see how you think when presented with a problem you haven't seen before. Do you make an attempt to think things through or do you just dive in? In an interview situation your instinct might be to dive straight into writing code but that's a trap. Once you get in to the code there is no turning back, you should tease the problem out first and ask any questions that come to mind no matter how stupid they might seem. By asking questions you are giving the interviewer an insight into your line of thinking and it also gives them an opportunity to lead you to the correct path for solving the problem.

    Sometimes the person who asks the question doesn't have the answer and it's just an exercise to see if they can work a problem through with the candidate, after all you are supposed to work as part of a team.


  • Registered Users Posts: 14,715 ✭✭✭✭Earthhorse


    You've skipped a lot of the complications. You can't just sort the array.

    Am I the only one who has actually finished this? I was expecting more solutions.

    Hey, some of us have day jobs! ;)
    rw999 wrote: »
    ...

    TDD is great for these. Try to think of the edge cases, and add a test. The test can be simple, just print to stdout and validate it in your head, particularly if pressed for time. When you write a little code, run the solution to see if it has worked as you intended.

    Get something working. Think about how it could be done in O(n) time/memory or be adapted to handle variations of the question, but get a naive solution working before worrying too much about these things. I often find you see obvious ways for improvement from working out the naive case and you will at least have something to show. This is particularly relevant when applying for a grad role as the interviewer does not necessarily expect the ideal solution.

    Very much agree with this.
    beauf wrote: »
    Is there no library that has a isDate/isTime function to check valid time formats.
    Modify the string so its this format and pass it into such a function.
    I assume you can't do this as you don't have access to such libraries.

    In c# you have DateTime.TryParse() which will indeed tell you whether it's a valid DateTime; I didn't end up using this in my solution and would expect to be asked why if I got to the interview stage.

    Here's my solution for what it's worth (in c#). Knocked it together this evening though admittedly I had been thinking a bit about it the last few days. At first, I tried Talisman's approach of sorting but ran in to a few too edge cases that were difficult to solve. Then I decided to sort descending instead; rather than start by getting the earliest hour, start by getting the latest minute. I *think* this works for all cases.

    Here's the code:

    This class contains most of the logic.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DateValidator
    {
        public class DateValidator
        {
            private const int highestMinuteOrSecondOneValue = 5;
            private const int highestMinuteOrSecondTwoValue = 9;
    
            public int GetLatestMinuteOrSecond(DateResult result)
            {
                result.Numbers = result.Numbers.OrderByDescending(x => x).ToList();
                int latestSecondMinute = result.Numbers[0];
                result.Numbers.Remove(latestSecondMinute);
                int? latestFirstMinute = null;
                foreach(int testValue in result.Numbers)
                {
                    if (testValue <= highestMinuteOrSecondOneValue)
                    {
                        latestFirstMinute = testValue;
                        break;
                    }
                }
                if (latestFirstMinute == null) { latestFirstMinute = highestMinuteOrSecondOneValue + 1; }
                result.Numbers.Remove((int)latestFirstMinute);
                return (int)latestFirstMinute * 10 + latestSecondMinute;
            }
    
            public int GetLatestHour(DateResult result)
            {
                result.Numbers = result.Numbers.OrderByDescending(x => x).ToList();
                int latestSecondHour = result.Numbers[0];
                result.Numbers.Remove(latestSecondHour);
                int latestFirstHour = result.Numbers[0];
                return latestFirstHour * 10 + latestSecondHour;
            }
        }
    }
    

    A class to take numbers in and write results out:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DateValidator
    {
        public class DateResult
        {
            public List<int> Numbers = new List<int>();
    
            public const int MaxHour = 23;
            public const int MaxMinute = 59;
            public const int MaxSecond = 59;
    
            public bool ValidHour;
            public bool ValidMinute;
            public bool ValidSecond;
    
            public int Hour;
            public int Minute;
            public int Second;
    
            public string Message;
    
            public void GetMessage()
            {
                if (Hour > MaxHour)
                    Message = "Cannot get valid hour.";
                else if (Minute > DateResult.MaxMinute)
                    Message = "Cannot get valid minute.";
                else if (Second > DateResult.MaxSecond)
                    Message = "Cannot get valid second.";
                else
                    Message = new DateTime(1, 1, 1, Hour, Minute, Second).ToLongTimeString();
            }
        }
    }
    

    And the program that calls it:
    using DateValidator;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DateValidatorConsole
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<DateResult> results = new List<DateResult>();
                results.Add(GetResult(new List<int>() { 0, 0, 0, 7, 8, 9 }));
                results.Add(GetResult(new List<int>() { 2, 4, 5, 9, 5, 9 }));
                results.Add(GetResult(new List<int>() { 0, 0, 0, 0, 0, 1 }));
                results.Add(GetResult(new List<int>() { 2, 3, 5, 9, 5, 9 }));
                results.Add(GetResult(new List<int>() { 0, 0, 2, 2, 5, 6 }));
                results.Add(GetResult(new List<int>() { 0, 0, 5, 9, 5, 9 }));
                results.Add(GetResult(new List<int>() { 1, 8, 3, 2, 6, 4 }));
                results.Add(GetResult(new List<int>() { 8, 4, 7, 1, 8, 6 }));
                results.Add(GetResult(new List<int>() { 8, 9, 0, 4, 0, 0 }));
                foreach (DateResult result in results)
                {
                    Console.WriteLine(result.Message);
                }
                Console.Read();
            }
    
            static private DateResult GetResult(List<int> numbers)
            {
                DateValidator.DateValidator validator = new DateValidator.DateValidator();
                DateResult result = new DateResult { Numbers = numbers };
                result.Second = validator.GetLatestMinuteOrSecond(result);
                result.Minute = validator.GetLatestMinuteOrSecond(result);
                result.Hour = validator.GetLatestHour(result);
                result.GetMessage();
                return result;
            }
        }
    }
    

    And the results:

    471153.png

    Actually, I think I spot a problem with the GetLatestMinutesOrSeconds() method now. Oh well, I'm back on my Mac now and can't be bothered.

    If I were doing this for real I'd also refactor and write unit tests.


  • Closed Accounts Posts: 22,651 ✭✭✭✭beauf


    smacl wrote: »
    Don't think so. To compute the average journey time from any one potential location, you need to compute the journey time between than location and every other location and then divide by the number of locations minus 1. Given every location is a potential station location this still amounts a high computational complexity, though there are plenty of strong optimisations. Even then, the spec says within 10 minutes which implies maximum allowable response time rather than average.

    You can't use radius either as this doesn't correlate with travel time by road. If you could you could use something like a Voronoi diagram to get areas serviced by a specific station.

    If the question came from Google, could be that it was devised by an American who lived in a city laid out in blocks which is the case with many American cities, and you could just divide into equal areas. Not going to work for many of the major European cities ;)

    The question is lacking the detail required for a complex and/or exact answer.
    So I would assume its not looking for a complex or exact solution.
    Rather looking for a framework of logic that might solve the problem.
    I would assume its looking for an approximate answer.
    Because there's no indication of time of day, traffic volumes, location etc.

    Also I assume you are intended to complete it during the interview time frame.
    So you wouldn't have time for a complex solution.

    But I'm not a programmer and never done these kind of interviews, so I have no idea. But I liked your answer as it opens a whole area I'd never heard of. Some nice reading there.


  • Registered Users Posts: 768 ✭✭✭14ned


    Looks like that fire station problem got people thinking!

    The task was to complete a working implementation in code within the 50 minute segment. I chose Python to make life easy on myself. I basically started down lots of blind alleys, and I remember the interviewer looking bored at one point, I clearly was going to fail the segment badly. Oh well. Never passed a Google interview yet.

    Filling in some detail for some people, I don't remember any one way streets. It wasn't a real city either, more like something from SimCity or GTA, simplified. Yes it used American blocks, roads were like a grid. With hindsight, as beauf said, you could use Pythagoras to find the worst travel time within a circle around a potential firestation, clamp the size to ten minutes at some estimated speed, and then you basically need all the circles to just exactly completely overlap all the space in the city which was a square. But then you'd have solved just the specific problem in front of you, and I got the strong feeling that wasn't what the interviewer was looking for.

    My biggest issue, personally, was coding this thing up into a working solver within 40 minutes. I guess someone strong on graph theory could probably have knocked something together which was totally generic and which solved the problem by weighted edge traversal of a graph of nodes to produce a minimum node graph, as smacl suggested. That would solve any city map, including ones without a neat grid street layout.

    Anyway, water under the bridge. Onwards and upwards!

    Niall


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    14ned wrote: »
    My biggest issue, personally, was coding this thing up into a working solver within 40 minutes. I guess someone strong on graph theory could probably have knocked something together which was totally generic and which solved the problem by weighted edge traversal of a graph of nodes to produce a minimum node graph, as smacl suggested. That would solve any city map, including ones without a neat grid street layout.

    If you were going to take this approach and were familiar with BGL you could put something together reasonably quickly. Personally, I'm not. A breadth first traversal (BFT) modified to terminate when any visited vertex was 10 minutes from the root vertex would do the trick. Initial seed point selection is trickier, but bearing in mind you need to visit the map edges, I'd start by placing a seed point at edge, carry out a BFT, take the two edge points and repeat with those. Given two edge points, carry out a BFT search on each, looking for a common vertex found by both seed points. That is one position we need a fire station. Remove all points visited by a BFT from that fire station and repeat until all points are exhausted. One way streets kills this algorithm as it depends on cost of graph traversal between points being the same in either direction, and there are many other reasons it wouldn't work in the real world.

    Maybe you guys are faster coders, but I'd be chuffed to get this done in a morning. No way is that a 40 minute exercise for this ageing code monkey.


  • Advertisement
  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    Talisman wrote: »
    For old European cities the same principle applies but rather than using the length and width of a block you would need a dataset with the length of each road - the emergency services use the main roads so you focus on them.

    You don't need to get a perfect answer - the primary motivation for such questions is to see how the candidate approaches the problem. They want to see how you think when presented with a problem you haven't seen before. Do you make an attempt to think things through or do you just dive in? In an interview situation your instinct might be to dive straight into writing code but that's a trap. Once you get in to the code there is no turning back, you should tease the problem out first and ask any questions that come to mind no matter how stupid they might seem. By asking questions you are giving the interviewer an insight into your line of thinking and it also gives them an opportunity to lead you to the correct path for solving the problem.

    Sometimes the person who asks the question doesn't have the answer and it's just an exercise to see if they can work a problem through with the candidate, after all you are supposed to work as part of a team.

    True, though one way streets would confound many algorithms, which is most European cities.

    I strongly agree with the mistake of jumping to the code too soon, to me these problems are all about the algorithm design which is also where you carry out the more important opimisations. With this, as someone mentioned earlier in this thread, a TDD based implementation demonstrates the algorithm works.

    I'd also agree with the whole teamwork thing. This thread nicely illustrates the value of bouncing ideas around in terms of not only arriving at a solution to the problem in hand, but also upping everyone's game.

    Good post, BTW.


  • Closed Accounts Posts: 22,651 ✭✭✭✭beauf


    What else have you used the graph libraries for. What sort of problems. I see the examples on line but they are not very specific. I've never even heard of that before. Is that something you would have done in college.


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    beauf wrote: »
    What else have you used the graph libraries for. What sort of problems. I see the examples on line but they are not very specific. I've never even heard of that before. Is that something you would have done in college.

    Any topological problems, computer networks, water transport capacity, electricity transmission, genealogy, etc... To a lesser extent topographies mapped onto topologies, e.g. London underground journey planning and Satnav GPS route mapping. Topographic problems, such as journey planning by road, tend to suffer from many confounding variables and not be entirely reliable. Neural nets also tend to be represented as dynamic graphs, and they are also used heavily in blockchain related protocols such as the Ethereum DAG and IOTA tangle. All the various tree structures you hit in computer science 101 are also basically DAGs.

    Edit: Re college, yep. I studied discrete methods in Kevin street back when dinosaurs still roamed the earth and graph theory was an important module and the basis for a few more.


  • Registered Users Posts: 6,236 ✭✭✭Idleater


    beauf wrote: »
    What else have you used the graph libraries for. What sort of problems. I see the examples on line but they are not very specific. I've never even heard of that before. Is that something you would have done in college.

    I used a (python) graphing tool to arrange a graph of celery tasks that could be run in parallel and combine them when there were dependencies between the streams.


  • Registered Users Posts: 768 ✭✭✭14ned


    smacl wrote: »
    A breadth first traversal (BFT) modified to terminate when any visited vertex was 10 minutes from the root vertex would do the trick. Initial seed point selection is trickier, but bearing in mind you need to visit the map edges, I'd start by placing a seed point at edge, carry out a BFT, take the two edge points and repeat with those. Given two edge points, carry out a BFT search on each, looking for a common vertex found by both seed points. That is one position we need a fire station. Remove all points visited by a BFT from that fire station and repeat until all points are exhausted.

    This seems very plausible. Back when I had just finished my graph theory module at uni I could have coded this up no bother. But it's not exactly knowledge you carry around with you as you get older. Or, rather, it's not knowledge you carry around unless that's your day job.
    Maybe you guys are faster coders, but I'd be chuffed to get this done in a morning. No way is that a 40 minute exercise for this ageing code monkey.

    If you gave me two days, I don't doubt for a second I could resurrect my knowledge from back when I was at uni and produce an optimal answer. But it would take the two days. Cold storage is high latency, as it were. Definitely zero chance on a question not prepared for in advance with 40 minutes to do it.

    Anyway keeping fresh on interviewing no longer matters to me anymore. This morning the contract came through for me leaving contracting, I am returning to permanent to ride out the coming tech bubble collapse. 100% remote for a US finance firm, paid at US wages which is double the max you'd ever get paid here, all routed through my Irish limited company to mitigate taxes, and with Irish public holidays and vacation time which is double what they offered initially. I am very pleased indeed to have landed this role, but I am sad to leave contracting. I really love contracting, I will miss it sorely.

    Niall


  • Registered Users Posts: 6,016 ✭✭✭Talisman


    Getting back to the OP's original problem, I have implemented a solution in Python using my suggestion of sorting the time elements. The main function requires a supporting cast of 3 functions.

    in_range_limit : Returns a boolean indicating whether the provided values are in the required range. Use case is to check if 'hh' is less than 24 and that both 'mm' and 'ss' values are less than 60.

    high_low_range_check : Iterates through the provided list of values and counts the number of low range (0..5) and high range (6..9) digits. Returns the difference between the calculated totals. Use case is to allow the main function to fail early and also optimise the calls to the next function.

    valid_time_str : Determines if the provided arguments are a valid 24 hour time string. Returns the formatted string value or None - Python's null equivalent.
    def earliest_time(*args):
        result = None # Default to Failure
        if (len(args) == 6):
            time_digits = sorted(args)
            if (in_range_limit(time_digits[0], time_digits[1], 24)):
                check_value = high_low_range_check(time_digits)
                a, b, c, d, e, f = time_digits
                if (check_value > 0):
                    result = valid_time_str(a, b, c, d, e, f) or valid_time_str(a, b, c, e, d, f)
                elif (check_value == 0):
                    if (time_digits[0] < 2):
                        result = valid_time_str(a, d, b, e, c, f) or valid_time_str(a, b, c, e, d, f)
        return result
    
    By defaulting the result value to the failure case it's easier to focus on seeking the happy paths in the if statement branches and avoid complications.

    Avoiding the possible complications simplifies things - when I said that creating the time string was trivial I wasn't joking. There are 6 values to choose from but because we are only interested in earliest time string, the smallest value must be in the first position and the largest value must be in the last position. This means that we have only 4 values to play with.

    The check to determine the relative number of the high and low values allows the possibilities to be narrowed down to 2 for each happy path. Ultimately this means the function could be refactored to just 2 lines but I wouldn't do that in an interview situation unless asked about refactoring because there is a trade off.

    Here's the refactored function - the list of values still needs to be sorted and then it's a case of trying the 4 possible valid arrangements in the order that would yield the earliest time first. You could also generate the 4 possible strings, sort them, and return the first one.
    def refactored_earliest_time(*args):
        a, b, c, d, e, f = sorted(args)
        return valid_time_str(a, b, c, d, e, f) or valid_time_str(a, d, b, e, c, f) or valid_time_str(a, b, c, e, d, f) or valid_time_str(a, d, e, b, c, f)
    

    For completeness here are the helper functions - they don't do anything special.
    def in_range_limit(a, b, limit=60):
        return (0 <= (int(a) * 10 + int(b)) < limit)
    
    
    def high_low_range_check(digits_list):
        low_digits, high_digits = 0, 0
        for digit in digits_list:
            if (int(digit) > 5):
                high_digits += 1
            else:
                low_digits += 1
        return (low_digits - high_digits)
    
    
    def valid_time_str(h1, h2, m1, m2, s1, s2):
        output = None
        if (in_range_limit(h1, h2, 24) and in_range_limit(m1, m2) and in_range_limit(s1, s2)):
            output = "".join(str(x) for x in [h1, h2, ":", m1, m2, ":", s1, s2])
        return output
    

    Does it work? I think so.
    >>> print(earliest_time(9, 9, 8, 5, 5, 2)) # Expect None - Should fail
    None
    >>> print(earliest_time(0, 0, 0, 7, 8, 9)) # Expect '07:08:09'
    07:08:09
    >>> print(earliest_time(0, 0, 1, 0, 0, 0)) # Expect '00:00:01'
    00:00:01
    >>> print(earliest_time(9, 3, 5, 9, 2, 5)) # Expect '23:59:59'
    23:59:59
    >>> print(earliest_time(1, 8, 3, 2, 6, 4)) # Expect '12:36:48'
    12:36:48
    >>> print(earliest_time(8, 4, 7, 1, 8, 6)) # Expect None - Should fail
    None
    >>> print(earliest_time(8, 9, 0, 4, 0, 0)) # Expect '00:08:49'
    00:08:49
    >>> print(earliest_time(5, 4, 3, 2, 1, 0)) # Expect '01:23:45'
    01:23:45
    

    Refactored function results:
    >>> print(refactored_earliest_time(9, 9, 8, 5, 5, 2)) # Expect None - Should fail
    None
    >>> print(refactored_earliest_time(0, 0, 0, 7, 8, 9)) # Expect '07:08:09'
    07:08:09
    >>> print(refactored_earliest_time(0, 0, 1, 0, 0, 0)) # Expect '00:00:01'
    00:00:01
    >>> print(refactored_earliest_time(9, 3, 5, 9, 2, 5)) # Expect '23:59:59'
    23:59:59
    >>> print(refactored_earliest_time(1, 8, 3, 2, 6, 4)) # Expect '12:36:48'
    14:26:38
    >>> print(refactored_earliest_time(8, 4, 7, 1, 8, 6)) # Expect None - Should fail
    None
    >>> print(refactored_earliest_time(8, 9, 0, 4, 0, 0)) # Expect '00:08:49'
    04:08:09
    >>> print(refactored_earliest_time(5, 4, 3, 2, 1, 0)) # Expect '01:23:45'
    01:23:45
    
    The takeaway for the OP is to try to think through the problem before heading into the code because once you start hitting problems you'll get frustrated and not be able to perform to your ability. The negative experience will affect you but you need to put it behind you and chalk it up to being a learning experience.

    Practising solving such problems will build up your confidence and help you identify common patterns and the appropriate solutions.


  • Registered Users Posts: 6,016 ✭✭✭Talisman


    14ned wrote: »
    Anyway keeping fresh on interviewing no longer matters to me anymore. This morning the contract came through for me leaving contracting, I am returning to permanent to ride out the coming tech bubble collapse. 100% remote for a US finance firm, paid at US wages which is double the max you'd ever get paid here, all routed through my Irish limited company to mitigate taxes, and with Irish public holidays and vacation time which is double what they offered initially. I am very pleased indeed to have landed this role, but I am sad to leave contracting. I really love contracting, I will miss it sorely.
    Congratulations on the job - That's great to hear.


  • Posts: 17,381 [Deleted User]


    Talisman wrote: »

    Avoiding the possible complications simplifies things - when I said that creating the time string was trivial I wasn't joking. There are 6 values to choose from but because we are only interested in earliest time string, the smallest value must be in the first position and the largest value must be in the last position. This means that we have only 4 values to play with.

    I'm sorry but this is incorrect. We are looking for the earliest time that is not null.

    Take 0 1 5 9 9 9. I don't know python but based on your comment, you would take 1am as the hour resulting in a null as the rest can't be a valid time.

    The lowest time is actually 09:19:59.

    https://playcode.io/230349?tabs=console&script.js&output


  • Closed Accounts Posts: 22,651 ✭✭✭✭beauf


    Also congrats.

    Also thanks for everyone who's taken the time to give such detailed posts. Its pleasure having a grownup conversation for once on boards and in Dev where people tend to give sound bytes.


  • Registered Users Posts: 6,016 ✭✭✭Talisman


    I'm sorry but this is incorrect. We are looking for the earliest time that is not null.

    Take 0 1 5 9 9 9. I don't know python but based on your comment, you would take 1am as the hour resulting in a null as the rest can't be a valid time.

    The lowest time is actually 09:19:59.

    https://playcode.io/230349?tabs=console&script.js&output
    No if you read what I said again I said there are 6 values we only need to concern ourselves with the middle 4.

    0 1 5 9 9 9

    a=0
    b=1
    c=5
    d=9
    e=9
    f=9

    a and f do not need to be shuffled around.

    (a, b, c, d, e, f) -> (0, 1, 5, 9, 9, 9) : Fails
    (a, d, b, e, c, f) -> (0, 9, 1, 9, 5, 9) : '09:19:59'
    (a, b, c, e, d, f) -> (0, 1, 5, 9, 9, 9) : Fails
    (a, d, e, b, c, f) -> (0, 9, 9, 1, 5, 9) : Fails

    >>> print(refactored_earliest_time(0, 1, 5, 9, 9, 9)) # Expect '09:19:59'
    09:19:59
    


  • Advertisement
  • Posts: 17,381 [Deleted User]


    Talisman wrote: »
    No if you read what I said again I said there are 6 values we only need to concern ourselves with the middle 4.

    0 1 5 9 9 9

    a=0
    b=1
    c=5
    d=9
    e=9
    f=9

    a and f do not need to be shuffled around.

    (a, b, c, d, e, f) -> (0, 1, 5, 9, 9, 9) : Fails
    (a, d, b, e, c, f) -> (0, 9, 1, 9, 5, 9) : '09:19:59'
    (a, b, c, e, d, f) -> (0, 1, 5, 9, 9, 9) : Fails
    (a, d, e, b, c, f) -> (0, 9, 9, 1, 5, 9) : Fails

    >>> print(refactored_earliest_time(0, 1, 5, 9, 9, 9)) # Expect '09:19:59'
    09:19:59
    

    Fair enough. Good work.


  • Registered Users Posts: 6,016 ✭✭✭Talisman


    Fair enough. Good work.
    Thanks for questioning me up on it - I need to work on my communication skills. Some times I make the assumption that people will make the same mental leap that I already have and skip explaining what could be a vital step for helping them to bridge the knowledge gap for themselves.


  • Registered Users Posts: 1,582 ✭✭✭DesperateDan


    I think that's a pretty good interview question actually. Multiple solutions, would have even a pro thinking about it for a little, and imagine you have 20 grads all answering the same thing it's going to be pretty easy to choose the best answers and chuck out the eejits.


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    14ned wrote: »
    Anyway keeping fresh on interviewing no longer matters to me anymore. This morning the contract came through for me leaving contracting, I am returning to permanent to ride out the coming tech bubble collapse. 100% remote for a US finance firm, paid at US wages which is double the max you'd ever get paid here, all routed through my Irish limited company to mitigate taxes, and with Irish public holidays and vacation time which is double what they offered initially. I am very pleased indeed to have landed this role, but I am sad to leave contracting. I really love contracting, I will miss it sorely.

    And another congrats. Having been in business for myself for the last thirty years I can sympathise with leaving contracting, but having a decent wage coming in with a potential downturn looming it makes a lot of sense. Remote with zero commute is also a huge benefit.


  • Registered Users Posts: 793 ✭✭✭ImARebel


    14ned wrote: »

    Anyway keeping fresh on interviewing no longer matters to me anymore. This morning the contract came through for me leaving contracting, I am returning to permanent to ride out the coming tech bubble collapse. 100% remote for a US finance firm, paid at US wages which is double the max you'd ever get paid here, all routed through my Irish limited company to mitigate taxes, and with Irish public holidays and vacation time which is double what they offered initially. I am very pleased indeed to have landed this role, but I am sad to leave contracting. I really love contracting, I will miss it sorely.

    Niall

    that sounds like a great job. redundancies happening in our place at the moment.. it's only a matter of time before this (also aging) coder will be told take a hike :(


  • Registered Users Posts: 768 ✭✭✭14ned


    smacl wrote: »
    And another congrats. Having been in business for myself for the last thirty years I can sympathise with leaving contracting, but having a decent wage coming in with a potential downturn looming it makes a lot of sense. Remote with zero commute is also a huge benefit.

    I've been through two downturns now, 2001 and 2010. The difference this coming downturn is I now have small children. They don't do belt tightening well.

    Couldn't agree more about the zero commute (actually it'll be ten minutes, I'll be renting an office in Mallow town). I did a twelve month contract in Dublin last year due to no other choice. That weekly commute from Mallow sucked very badly indeed, plus a further three hour commute daily into Dublin city centre. Definitely very very happy to be away from that.

    Thanks for the congrats everybody!

    Niall


  • Registered Users Posts: 6,016 ✭✭✭Talisman


    14ned wrote: »
    It's about six lines of C or Python code to implement. Both have standard library functions which do all the work. So I'd say a very rudimentary problem to solve.
    It's Friday afternoon and I couldn't resist ... 6 lines of JavaScript:
    function earliest(time_digits) {
        const in_range = (a, b, limit=60) => 0 <= (a * 10 + b) < limit
        const time_str = (h1, h2, m1, m2, s1, s2) => (in_range(h1, h2, 24) && in_range(m1, m2) && in_range(s1, s2)) ? `${h1}${h2}:${m1}${m2}:${s1}${s2}` : null
        const [a, b, c, d, e, f] = time_digits.sort()
        return (time_str(a, b, c, d, e, f) || time_str(a, b, c, e, d, f) || time_str(a, d, b, e, c, f) || time_str(a, b, c, e, d, f))
    }
    

    Should work in all modern browsers.
    earliest([5, 4, 3, 2, 1, 0])
    "01:23:45"
    


  • Registered Users Posts: 6,236 ✭✭✭Idleater


    Talisman wrote: »
    I couldn't resist ... 6 lines of JavaScript:

    If you remove the spaces it'd be more unreadable :-D


  • Registered Users Posts: 14,715 ✭✭✭✭Earthhorse


    To answer the OPs original question, I'd say this was a tough enough task to complete fully as part of multiple tasks in the space of two and a half hours. I'm inclined to think you weren't "meant" to finish it but instead do a good first attempt and then they would pick it apart and see how you stood up to a code review of sorts. I think it took me the guts of two hours to do my solution and I doubt I would perform so well with someone looking over my shoulder.

    In relation to the Google interview question (which I made no attempt to solve :)) there's a former Google interviewer writing a series of blog posts (here's one: https://medium.com/@alexgolec/google-interview-problems-synonymous-queries-36425145387c) examining interview questions that have since been leaked and thus are no longer used. His approach seems fair which is to interact with the candidate and to expect lots of questions before an answer is even attempted. I have no idea if the question posted in this thread is in the series but could be worth gander for those of you interested in such things.


  • Advertisement
  • Banned (with Prison Access) Posts: 186 ✭✭Kickstart1.3


    Took me over an hour to do at home under no pressure, so I'm afraid I might not have done so good under pressure either!!

    https://www.jdoodle.com/embed/v0/W4w

    [php]import java.util.Arrays;
    public class Solution {
    public static void main(String[] args){
    Solution solver = new Solution();
    System.out.println("" + solver.solution(0,0,0,7,8,9));
    }
    public String solution(int A, int B, int C, int D, int E, int F) {
    int temp = 0; Double testNum = 0.0;
    int[] numsArray = new int[]{A,B,C,D,E,F};
    // Sort the Array
    Arrays.sort(numsArray);
    for (int i = 0; i < 6; i++){
    if (numsArray > 5)
    temp++;
    testNum = testNum + numsArray*Math.pow(10.0,5.0-i);
    }
    // Test of high digit count
    if (temp > 3){
    return null;
    }
    // Number is Too Big to be a time
    if ( testNum > 235959){
    return null;
    }
    // Number can be a time, just needs sorting
    if (numsArray[4] > 5){
    temp = numsArray[4];
    numsArray[4] = numsArray[2];
    numsArray[2] = temp;
    }
    if (numsArray[2] > 5){
    temp = numsArray[2];
    numsArray[2] = numsArray[3];
    numsArray[3] = temp;
    }
    if (numsArray[2] > 5){
    temp = numsArray[1];
    numsArray[1] = numsArray[2];
    numsArray[2] = temp;
    }
    if (numsArray[2] > numsArray[4]){
    temp = numsArray[4];
    numsArray[4] = numsArray[2];
    numsArray[2] = temp;
    }
    return ("" + numsArray[0] + numsArray[1] + ":" + numsArray[2] + numsArray[3] + ":" + numsArray[4] + numsArray[5]);
    }
    }[/php]

    (Written in java not php)


Advertisement