Document directory
- Algorithm Analysis
- Some Problems
Guangzhou 4399 interview questions (2)
By Ma Dongliang (cream Loki)
One man's war (http://blog.csdn.net/MDL13412)
Description
Given n items, the probability is P1, P2, p3... Pn. Please design an interface to obtain an item randomly based on the probability.
Algorithm Analysis
The algorithm for this question can be used.Programming PearlAnd then useRand () % Total Interval LengthDetermine the selected item based on the range of the random number. Assume n = 5, P1 = 10, P2 = 40, P3 = 5, P4 = 20, P5 = 25, after converting it into a line segment, as shown in:
Shows how to randomly obtain an item:
The preceding example assumes that the probability is an integer. If the probability is decimal, the number of decimal places to be retained depends on the number of decimal places to be retained.K, Multiply the probability10 ^ KAnd expand the total length of a line segment accordingly.
Prior Conditions of Some Problems
- P1 + p2 +... + Pn = 100%
- 0 <= pI <= 1 (1 <= I <= N)
- N> 0
Scalability
You can directlyIf-else if-...-ElseIf the demand changes greatly or the number of items needs to be modified frequently, this method cannot be used. The solution is dynamic computing, seeTime Complexity vs space complexitySection.
Time Complexity vs space complexity
When using dynamic computing, you can specify an array whose internal storage type isStruct range {int start; int end };In useRand () % Total Interval LengthAfter obtaining the random number, enumerate the intervals in this array to obtain the corresponding items. This scheme can effectively save memory, but after calling rand (), a linear search is required, which is less efficient;
In the real world, this topic generally corresponds to a lottery program. Therefore, this function needs to be called frequently and runs inServerThe memory is not a bottleneck. Therefore, you can use the space for time to optimize the business logic. The algorithm is as follows:
Assume n = 5, P1 = 10, P2 = 40, P3 = 5, P4 = 20, P5 = 25. Then, an array with a length of 100 is allocated to fill the item range1,[10, 50)Fill the interval2,...,[75,100)Fill the interval5(This process only needs to be performed once, and you do not need to fill it again when you call this function later ).Rand () % Total Interval LengthAfter obtaining a random number, you can directlyUse array [random number], For exampleArray [20] = 2The time complexity isO (1).
After the comparison and analysis above, we can conclude that in the real world, the space-for-time solution is the optimal solution.
Summary
When solving such questions, pay attention to the predicate conditions implied in the questions, and pay attention to the ease-of-use of interfaces (for example, the form in which parameters should be passed in/out), as well as the reusability of functions, and the connection between code and business logic.