Programming Interview Questions: Prime Factorization

This is a first attempt on a series with focus on solving commonly asked programmer interview questions, in this first episode we’ll do prime factorization.

Screencast

And yes, I’ve been made aware of that 21 is not a prime, not easy to code and talk at the same time. :-)

What the interviewers are looking for

It’s not all about the final solution, the interviewers are interested in how you break down larger problems into smaller more comprehensible ones. How you go about solving problems with logical thinking. If the interviewers are any good they’ll try to make you feel comfortable and develop a solution together if you get stuck, the idea is not to grill someone at the whiteboard.

Breaking it down

There’s three partials problems to solve, or four perhaps if we count in to realize that we’re done.

  1. Divide with the lowest possible prime as many times as possible.
  2. Write a method to find the next prime.
  3. Write a method to check if a number is a prime.
  4. Realize we are done when the division gives us 1.

Sometimes the candidate will try to give us a recursive solution because they think that’s what we want to see, it’s not, going down that path usually only complicates things. If the interviewers are fishing for a recursive solution, they’ll probably ask something like:

Do X without using a loop

where X could be to reverse a string for instance. It’s always a good idea to write down test cases and test the solution by hand at the whiteboard.

Code

Here’s the program I developed during the screencast with a couple of optimizations added that I got pointed out when publishing the screencast:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main(string[] args) {

        var number = int.Parse(args[0]);
        var remaining = number;
        var currentPrime = 2;    
        var result = new List();
    
        do {  
            while (remaining % currentPrime == 0) {
                result.Add(currentPrime);
                remaining /= currentPrime;
            }  
        
            currentPrime = nextPrime(currentPrime);
        } while (remaining > 1);
    
        Console.WriteLine(string.Format(
            "{0}s prime factors are: {1}", 
            number, 
            string.Join("*", result.ToArray())));
    }

    private static int nextPrime(int currentPrime)
    {
        var lastPrimeInArray = Primes.Last();
        if (lastPrimeInArray != currentPrime)
            return Primes.First(x => x > currentPrime);
           
        var nextPrime = currentPrime + 2;
        while (!IsPrime(nextPrime)) nextPrime+=2;
        Primes.Add(nextPrime);
        
        return Primes.Last();
    }

    private static bool IsPrime(int nextPrime)
    {
        for (int i = 2; i < nextPrime / 2; i++)
            if (nextPrime % i == 0) return false;
        return true;
    }

    // TODO: Load first 1000 primes from a file
    private static List Primes = new List { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 };
}

Bare in mind, it’s been quite some time since I solved these kind of puzzles, don’t be harsh. :-)

Is this a good interview question?

In my experience it helps to seed out some bad programmers. It can most certainly seed out some candidates with potential as well, but we reasoned that it’s simply worth it rather than hiring a really bad programmer. In the end it’s up to the interviewers to steer and adapt the audition to fully explore the candidates skill set, everyone doesn’t perform well under stress and it’s important to be agile during the interview process.

I don’t think that these kind of tests alone is enough to make a decision weather a candidate should get a job as a programmer or not. We usually combined an algorithmic problem with a business/architectural problem and tried to solve that as well, after all we were in the business of developing enterprise applications and not programming puzzles.

Challenge

Feel free to provide your own solution and suggest optimizations. You don’t have to be a programmer to solve these kind of puzzles, you can do it with a pen and paper. We did this on the whiteboard, so the code didn’t even need to compile. It’s fun!

And as always, until next time, have a nice day!

Angular 2 Material First Look

In this weeks screencast we take a first look at the material components for angular2 that just released their first alpaha, code at https://github.com/ajtowf/ng2_play. We’ll integrate the button and checkbox component into our ng2play repo, the idea is to fully replace bootstrap down the road.

Screencast

Components

There will be breaking changes between alpha releases, first release of angular2-material includes the following components:

To learn more about material deisgn and components for angular, make sure to check out my pluralsight course Angular Material Fundamentals.

Until next time, have a nice day folks!

Angular 2 Lifecycle Hooks

New screencast on Angular 2 beta 9, covering Lifecycle Hooks, get the code at https://github.com/ajtowf/ng2_play.

Screencast

The Lifecycle Hooks

Directive and component instances have a lifecycle as Angular creates, updates, and destroys them. Here’s the complete lifecycle hook interface inventory, all of them available in the angular2/core library and called in the provided order.

  • OnChanges: Calls ngOnChanges – called when an input or output binding value changes
  • OnInit: Calls ngOnInit – after the first ngOnChanges
  • DoCheck: Calls ngDoCheck – developer’s custom change detection
  • AfterContentInit: Calls ngAfterContentInit – after component content initialized
  • AfterContentChecked: Calls ngAfterContentChecked – after every check of component content
  • AfterViewInit: Calls ngAfterViewInit – after component’s view(s) are initialized
  • AfterViewChecked: Calls ngAfterViewChecked – after every check of a component’s view(s)
  • OnDestroy: Calls ngOnDestroy – just before the directive is destroyed.

To learn more about lifecycle hooks, check out the official documentation here.

Until next time, have a nice day folks!

Connection leaks when using async/await with Transactions in WCF

If you’re getting “The current TransactionScope is already complete” from service calls that don’t even consume transactions, you’ll probably want to read/see this.

Screencast and Code

The code can be found on github, https://github.com/ajtowf/dist_transactions_lab, one change I did since the recording is that we don’t create the nhibernate factory with each call, we now use a singleton SessionManager instead. Also we’re adding the convention to the factory to never load lazy so that our Item entity don’t need to have virtual properties, which makes it easier to switch between OR-mapper implementations.

Leaking Connections

In a fairly complex distributed enterprise system we were getting some strange The current TransactionScope is already complete errors. We used transactions frequently but we saw this on calls that wasn’t even supposed to run within an transaction.

After trying almost everything we got a hint from a nhibernate analyzer product that we shouldn’t consume a nhibernate session from multiple threads since it’s not thread safe.

If you use await, that’s exactly what happens. Turns out entity framework has the same problem.

The following code in your service will leak connections if the awaited method or service call uses a database connection with EntityFramework or NHibernate.

    [OperationBehavior(TransactionScopeRequired = true)]
    public async Task CallAsync()
    {
        using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            await _service.WriteAsync();
            ts.Complete();
        }
    }

Why Tasks in the Service Contract at all?

The lone reason for our service contracts being task based is that we use the same interface to implement our client-side proxies, which is neat, but the service doesn’t need use await because of that. This will work for instance:

    [OperationBehavior(TransactionScopeRequired = true)]
    public Task CallAsync()
    {
        // Do synchronous stuff
        return Task.FromResult(true);
    }

or (don’t like this one though)

    [OperationBehavior(TransactionScopeRequired = true)]
    public Task CallAsync()
    {
        // Remember to copy the OperationContext and TranactionScope to inner Task.
        return Task.Run(() =>
        {
            // Do synchronous stuff
        });          
    }

Oh, you don’t want to return a Task if you’re not doing anything async? Do this then:

    [OperationBehavior(TransactionScopeRequired = true)]
    public async Task CallAsync()
    {
        // Do synchronous stuff
    }

What about the warning? Turn it off with #pragma.

     [OperationBehavior(TransactionScopeRequired = true)]
#pragma warning disable 1998
     public async Task CallAsync()
#pragma warning restore 1998
        {            
            // Do synchronous stuff        
        }

You’ll probably want to wrap the entire service class with that pragma disable.

Solution

The main take away here is to simply not use async/await in your service code if you’re awaiting methods or service calls that will use database connections. The following refactoring solves the problem:

    [OperationBehavior(TransactionScopeRequired = true)]
    public Task CallAsync()
    {
        _service.WriteAsync().Wait();
        return Task.FromResult(true);
    }

As always, until next time, have a nice day!