QUOTE(aznballerlee @ 3 Nov, 2006 - 10:05 PM)

I have a problem with my program .. I want to add a string to an array position, and then
shift the strings after that position to one position after.
prototype: int insert(string a[], int n, string s, int pos, int max);
Here's what my specs say:
1) insert "string s" into array at index "pos".
2) move (n-pos) existing elements starting at "pos"
one space to the rgiht to make room.
3) return element index inserted.
4) return -1 if inserting element would cause array
to have more than max elements.
Hi Az
We all get stuck on different things.
On of the tricks to problem solving is to move the specification list around a little to make it easier to code (provided that the changes don't change the outcome). Specifications are usually written by users that want a specific outcome, they know little about coding and won't know or care if their specification is sequenced for coding the outcome.
The following details must be known
- Max_Dimension of Array
- Current_Count of stored strings
- position to insert
- string to insert
Your interface seems to have all these elements, so lets see what you need to check first. You will see that I have moved the sequence the specification to make it easier to code.
The first test should be to ensure the insertion won't exceed max index, ie if ( n +1 > max). I know that I am
stating the obvious but when we bury your face in a screen and line sof code, we often loose sight of the logical steps to successfully realise an outcome.
Shuffling the data would have to occur before you can insert, the spec says
shuffle to the right, however, that is only the outcome desired, if you think too literally, you may write code that overwrites the strings while shuffling.
Lets look at a simple example using some letters instead of strings
Sample data:
- auejdwipks
- Max Size = 12
- current size = 10
Insertion data 'z' into position 4
This attemp will clearly pass the size test, so we can just work on the way the algorithm should work. Remember that these are C based arrays and start at 0 (offset of -1)
position 4 is the letter j.
If we think like the specification, we can try the idea of
shuffling to the right.
copies over d, which copies over d which... oh... that way will obliterate the strings....
Write an exercise based onthis and see if you can determine the right way to do this.. remember.. think outside the square.