|
本帖最后由 hbghlyj 于 2022-1-28 07:42 编辑 - catalancount[n_, numdo_] := Module[{},
- (* we have an n x n grid, have n right moves, n up moves *)
- (* we will do this numdo times,
- record how many stay on main diag or below *)
- (* Right is +1, Up is -1, success is all running sums non-
- negative *)
- steplist = {};
- For[j = 1, j <= n, j++, steplist = AppendTo[steplist, 1]];
- For[j = 1, j <= n, j++, steplist = AppendTo[steplist, -1]];
- success = 0;
- For[i = 1, i <= numdo, i++,
- {
- orderedstep = RandomSample[steplist, 2 n]; (*
- this randomly permutes the 2n steps *)
- (* initialize works to 1,
- if ever have a negative running sum make works 0,
- increment success if end with works = 1 *)
- works = 1;
- runningsum = 0;
- For[j = 1, j <= 2 n, j ++,
- {
- runningsum = runningsum + orderedstep[[j]];
- If[ runningsum < 0,
- {
- works = 0;
- j = 2 n + 5;
- }];
- }]; (* end of j loop *)
- If[works > 0, success = success + 1];
- }]; (* end of i loop *)
- Print["Number of successes is ",
- 1.0 (success / numdo) Binomial[2 n, n]];
- ];
复制代码 |
|