Wednesday, October 28, 2009

An Interview Question

At a recent job interview I was asked to write a program to solve the following problem:

You have a sorted array of integer values, you need to generated a sorted array of the results of the results obtained when there values are plugged into the quadratic equation ax^2 + bx + c.

My first thought was that this was a problem best suited to the J programming language. Unfortunately I did not have my handy dandy J dictionary with me, and I do not have it memorized, so I had to wait until I got home to write:

fa =: monad : '/:~(c,b,a)p.y'

A J expert would make this tacit, and therefor shorter, but I'm not that good yet.

Using C++ with the Boost Lambda Library I would write:

std::Vector& fa(std::Vector& x)
{
    std::transform(x.begin(), x.end(), x.begin(), a*_1*_1 + b*_1 + c);
    std::sort(x.begin(),x.end());
    return x;
}

This does all the work in place so it only consumes memory for one array.

It can be made more efficient by taking advantage of the fact that the input array is sorted, so sorting the output array can be done in linear time, but that is left as an exercise for the reader.

I should look into how to do it in Ocaml, Erlang and Oz. But I do not think any of them will be as succinct as J or as efficient as C++. If the polynomial were of higher order it might be worth pursuing an Erlang solution that distributed the evaluation of the polynomial across several machines.

Labels:

3 Comments:

Anonymous Anonymous said...

Erlang:

If the sorted list is in L then:

lists:sort([A*X*X+B*X+C || X <- L])

Wednesday, October 28, 2009 at 4:20:00 PM UTC  
Blogger Ed said...

almost as succinct as J, and a lot easier to remember.

Thanks.

Wednesday, October 28, 2009 at 4:34:00 PM UTC  
Anonymous Anonymous said...

It's great to know you would consider J

I am not an expert programmer in J by any stretch of the imagination, but you had already done most of the heavy work.

To keep all the options open, I created a dyadic function rather than hard coding the a b c into the function. If the left argument (x) were a list of the three values of C B and A and the right argument (y) was the value of X, the explicit version would be:

fax=: dyad : '/:~ x p. y'

tacit is simpler:

fat=: /:~@:p.

cheers

Tuesday, December 29, 2009 at 10:49:00 PM UTC  

Post a Comment

<< Home