Difference between revisions of "Simulation"
(Created page with 'Simulation is a technique in programming where all events are processed in the order of occurrence. By translating real world logic into programming code, simulation speeds up ta…') |
(→Problem) |
||
Line 3: | Line 3: | ||
== Example == | == Example == | ||
=== Problem === | === Problem === | ||
− | Given M trees and the number of days each tree takes to grow a fruit, compute the total number of fruits after <math>N</math> days. | + | Given <math>M</math> trees and the number of days each tree takes to grow a fruit, compute the total number of fruits after <math>N</math> days. |
+ | |||
=== Solution === | === Solution === | ||
For each tree <math>i</math>, keep a variable <math>K_i</math> indicating the number of days it takes for the next fruit to grow. Simulate the situation day by day. On each day, decrease <math>K_i</math> by 1 and increase the fruit count by the number of <math>K_i</math>'s that equal zero, and reset these <math>K_i</math>'s. Output the total sum at the end. | For each tree <math>i</math>, keep a variable <math>K_i</math> indicating the number of days it takes for the next fruit to grow. Simulate the situation day by day. On each day, decrease <math>K_i</math> by 1 and increase the fruit count by the number of <math>K_i</math>'s that equal zero, and reset these <math>K_i</math>'s. Output the total sum at the end. |
Latest revision as of 02:51, 8 May 2010
Simulation is a technique in programming where all events are processed in the order of occurrence. By translating real world logic into programming code, simulation speeds up tasks that may otherwise take a long time for human. Simulation does not provide alternative shortcuts to a solution; it simply speeds up the process.
Example[edit]
Problem[edit]
Given trees and the number of days each tree takes to grow a fruit, compute the total number of fruits after days.
Solution[edit]
For each tree , keep a variable indicating the number of days it takes for the next fruit to grow. Simulate the situation day by day. On each day, decrease by 1 and increase the fruit count by the number of 's that equal zero, and reset these 's. Output the total sum at the end.
Analysis[edit]
This solution gives the correct answer, in time. This is fine if is small, but a better technique is required if is large.
Characteristics[edit]
When a problem is logically simple and can be directly done by human, simulation is very likely the solution. When the bounds on variables are small, simulation is a quick, safe, and convincing technique. When run time is a concern, other techniques such as dynamic programming may be required.