|
| 1 | +# generator شبه تصادفی |
1 | 2 |
|
2 | | -# Pseudo-random generator |
| 3 | +سناریوهای زیادی وجود دارند که در آن به دیتای تصادفی نیاز است. |
3 | 4 |
|
4 | | -There are many areas where we need random data. |
| 5 | +یکی از آنها تست کردن است. ممکن است ما برای یک تست خوب به دیتای تصادفی نیاز داشته باشیم: متن، عدد و غیره. |
5 | 6 |
|
6 | | -One of them is testing. We may need random data: text, numbers, etc. to test things out well. |
| 7 | +در جاوااسکریپت میتوان از `()Math.random` استفاده کرد. ولی میخواهیم این قابلیت را داشته باشیم که تست را دقیقا با همان دیتا بتوانیم تکرار کنیم. |
7 | 8 |
|
8 | | -In JavaScript, we could use `Math.random()`. But if something goes wrong, we'd like to be able to repeat the test, using exactly the same data. |
| 9 | +برای این منظور "seeded pseudo-random generators" استفاده میشوند. این generatorها یک "seed" -مقدار اولیه- را میگیرند و طبق یک فرمول باقی دنباله را تولید میکنند. در نتیجه "seed" یکسان دنباله یکسانی را تولید میکند و کل دنباله را به راحتی میتوان بازتولید کرد. فقط نیاز است "seed" را به یاد داشته باشیم. |
9 | 10 |
|
10 | | -For that, so called "seeded pseudo-random generators" are used. They take a "seed", the first value, and then generate the next ones using a formula so that the same seed yields the same sequence, and hence the whole flow is easily reproducible. We only need to remember the seed to repeat it. |
11 | | - |
12 | | -An example of such formula, that generates somewhat uniformly distributed values: |
| 11 | +یک مثال از چنین فرمولی که مقادیری با توزیع تقریبا یکنواخت تولید میکند: |
13 | 12 |
|
14 | 13 | ``` |
| 14 | +
|
15 | 15 | next = previous * 16807 % 2147483647 |
| 16 | +
|
16 | 17 | ``` |
17 | 18 |
|
18 | | -If we use `1` as the seed, the values will be: |
| 19 | + |
| 20 | +اگر از `1` به عنوان "seed" استفاده کنیم دنباله به شکل زیر خواهد بود: |
| 21 | + |
19 | 22 | 1. `16807` |
| 23 | + |
20 | 24 | 2. `282475249` |
| 25 | + |
21 | 26 | 3. `1622650073` |
22 | | -4. ...and so on... |
23 | 27 |
|
24 | | -The task is to create a generator function `pseudoRandom(seed)` that takes `seed` and creates the generator with this formula. |
| 28 | +4. ...و به همین ترتیب ادامه مییابد... |
| 29 | + |
| 30 | +تسک، ساختن یک تابع generator با امضای `pseudoRandom(seed)` است که یک "seed" میگیرد و یک generator با فرمول داده شده میسازد. |
25 | 31 |
|
26 | | -Usage example: |
| 32 | +مثلا: |
27 | 33 |
|
28 | 34 | ```js |
| 35 | + |
29 | 36 | let generator = pseudoRandom(1); |
30 | 37 |
|
31 | 38 | alert(generator.next().value); // 16807 |
| 39 | + |
32 | 40 | alert(generator.next().value); // 282475249 |
| 41 | + |
33 | 42 | alert(generator.next().value); // 1622650073 |
| 43 | + |
34 | 44 | ``` |
0 commit comments