For a programming class a while ago we were given a relatively simple task, the essence of which can be boiled down to:
Store an array (not a List) of n Strings where n is always <= m, allowing new strings to be added and old ones to be removed. (In this instance, m was 50)
When discussing this with my friends afterwards, we realised that all three of us had solved it in a different way. My question (out of mere curiosity) is which one of us had the best answer (all things being equal) and why.
Friend A went for implementing what was essentially an ArrayList; creating a new array with a different size and putting all the elements from the original array into the new one with a for
loop(plus or minus the one he was adding/removing).
Friend B simply created an array of length m, removing elements by setting their value to null (e.g. array[13] = null
), and adding elements by scrubbing forward from index 0 until an empty spot was found (this was a for
loop).
Friend C [Me] also created an array of length m, but shifted every following value forward (i.e. reduced their index by 1 with a for
loop) when a string was removed so that n-1 was always the index of the last value (when n > 0), and n was also the index to add new values at (eliminating the for
loop for adding strings).
It's a fairly basic class and they don't care how we did it as long as we did, but we're curious.
edit: I just realised that I left out something which may be important. The problem specified removing strings by value (e.g. removeString("someString")
) rather than index, which made finding the value (and its index) a requirement as well.