Thursday, January 24, 2008

Puzzle

Justin came up with this problem as part of an actual project and it puzzled me the simplicity of the problem and definition of the solution in your head, yet the complexity of the expressiveness in code for the solution, maybe another language would be better suited to solve this problem?

you have an array of the Doc class which has a DocIndex property, for which the property is not set, some elements of the array may be null

//*** small version of the Doc class, just for the puzzle
class Doc {
public int docIndex;
}

Doc[] docs = new Doc[] { new Doc(), new null, null, new Doc() };

then you have an array of ints that represent the indexes that are already taken, e.g.

new int[] { 2, 3, 5, 7, 9 }

your job is to assign the indexes to the Doc[] that are not "taken" (exist in the array)

so, for these examples:



The expected output would be:
existing :
2 3 5 7 9
docs :
0 1 4 6 8

existing :
0 1 2 3 4
docs :
5 6 7 8 9

existing :
5 6 7 8 9
docs :
0 1 2 3 4

what do you think of this problem for a code interview?

1 comment:

choy said...

In F#:
----------------------
#light
let rec assignDocIndex i docs existing = match docs with | [] -> [] | x::xs -> match existing with | y :: ys when y=i -> assignDocIndex y (i+1) xs ys | _ -> i :: assignDocIndex (i+1) xs existing
----------------------
> // usage
- assignDocIndex 0 docs [1;3;8];;
----------------------

The code would look much nicer if I could format it in this comment.