PE2 (AY20/21)
Last updated
Last updated
Questions:
Official Answers:
An easy probelm, just break this problem into several small problems and solve it.
The whole idea is to find the max num (index) that provides the biggest "triangle" number smaller than the input n
. And then we start from that triangle number to find its corresponding prime partner. (Cuz the probelms says triangle num should be in decreasing order)
But the overall run time of is a bit tricky. Here our first loop is actually and our second loop is actually one loop inside another loop, so the overal timing is , which is
The idea of replacing the redundant chars in the target string with white spaces and then ignore them in the final print is awesome.
There is an awesome idea here! The use of i
to indicate the start position in the source string we want to search for deals with the moving problem of the string successfully.
Here it is assumed that the length of the target string is longer than or equal to the length of the replace string.
Based on the same assumption above, our dst
is always smaller than or equal to src
Refer to the idea of doing recursion on strings from past year final paper (AY21/22 Q19) I implement a recursive solution as follows:
Note that this function will need some tedious memory management in the main()
function, where we need to read several target strings and replacement strings.
Prof summarises this problem to be a pattern recognition problem. The soul of this problem is the narrow your "searching area". That is, we can start from top-right (a[0][n-1]
)
If a[0][n-1]
is bigger than q
, that means q
cannot exist in the last column, so we narrow our search area by excluding the last column.
If a[0][n-1]
is smaller than q
, that means q
cannot exist in the first row, so we narrow our search area by excluding the first row.
This question also utilizes the awesome use of "move string" when pass it in recursion. The use of each parameter in the fucntion are documented in the code below:
So, for this question, during every iteration, the possible characters we can choose are from 0 to len-k
in the current src
string! And once we have added a character to our sub
string, we move our src
string to the remaining string behind that character.
Whne you allocate the memory for char *sub
, remember to add 1 to k since a string must end with \0
. That is also why you need to add \0
in the base case in the code above.
Somtimes changing the loop condition will change the obvious time complexity, pay attention to the "hidden" time complexity and sometimes this kind of change can be utilised to make your code more effificient.
When you want to improve the complexity of searching/sorting problems, try thinking about how to narrow your "searching area". This will be very useful!
Include my solution and prof's solution to 5. Substring* in PE2 Review.
This is actually a variant of from PE2 (AY22/23)