[과제번역] Part1 5.2 숫자형 9번 과제 문제, 해답 번역 #1581 by ggff23r2f2fffsdfds · Pull Request #1583 · javascript-tutorial/ko.javascript.info

@@ -1,6 +1,6 @@ # The simple but wrong solution # 간단하지만 틀린 해답
The simplest, but wrong solution would be to generate a value from `min` to `max` and round it: 가장 간단하지만 틀린 해답은 `min`에서 `max`까지의 값을 생성하고 반올림하는 것입니다.
```js run function randomInteger(min, max) { Expand All @@ -11,28 +11,28 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ```
The function works, but it is incorrect. The probability to get edge values `min` and `max` is two times less than any other. `randomInteger` 함수는 동작하지만, 올바르지 않습니다. 에지값 `min``max`가 나올 확률이 두 배 적습니다.
If you run the example above many times, you would easily see that `2` appears the most often. 위의 예시를 여러 번 실행하면, `2`가 가장 많이 나타나는 것을 알 수 있습니다.
That happens because `Math.round()` gets random numbers from the interval `1..3` and rounds them as follows: `Math.round()``1..3` 구간에서 난수를 가져와 다음과 같이 반올림하기 때문입니다.
```js no-beautify values from 1 ... to 1.4999999999 become 1 values from 1.5 ... to 2.4999999999 become 2 values from 2.5 ... to 2.9999999999 become 3 1 에서 ... 1.4999999999 까지의 값은 1 이 됩니다. 1.5 에서 ... 2.4999999999 까지의 값은 2 가 됩니다. 2.5 에서 ... 2.9999999999 까지의 값은 3 이 됩니다. ```
Now we can clearly see that `1` gets twice less values than `2`. And the same with `3`. 이제 `1`이 `2`보다 두 배 적게 나오는 것을 알 수 있습니다. `3`도 마찬가지입니다.
# The correct solution # 올바른 해답
There are many correct solutions to the task. One of them is to adjust interval borders. To ensure the same intervals, we can generate values from `0.5 to 3.5`, thus adding the required probabilities to the edges: 올바른 해답이 많이 있지만 그중 하나는 구간을 조정하는 것입니다. 동일한 간격을 보장하기 위해서, `0.5 에서 3.5` 사이의 값을 생성하여, 에지값에 필요한 확률을 추가할 수 있습니다.
```js run *!* function randomInteger(min, max) { // now rand is from (min-0.5) to (max+0.5) // rand는 (min-0.5)에서 (max+0.5)까지 입니다. let rand = min - 0.5 + Math.random() * (max - min + 1); return Math.round(rand); } Expand All @@ -41,12 +41,12 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ```
An alternative way could be to use `Math.floor` for a random number from `min` to `max+1`: 다른 방법은 `min`에서 `max+1`까지의 난수에 `Math.floor`를 사용하는 것입니다.
```js run *!* function randomInteger(min, max) { // here rand is from min to (max+1) // rand는 min에서 (max+1)까지 입니다. let rand = min + Math.random() * (max + 1 - min); return Math.floor(rand); } Expand All @@ -55,12 +55,12 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ```
Now all intervals are mapped this way: 모든 구간이 다음과 같이 매핑되었습니다.
```js no-beautify values from 1 ... to 1.9999999999 become 1 values from 2 ... to 2.9999999999 become 2 values from 3 ... to 3.9999999999 become 3 1 ... 에서 1.9999999999 까지의 값은 1 이 됩니다. 2 ... 에서 2.9999999999 까지의 값은 2 가 됩니다. 3 ... 에서 3.9999999999 까지의 값은 3 이 됩니다. ```
All intervals have the same length, making the final distribution uniform. 모든 구간은 같은 길이를 가지고 있고, 최종 분포도 균일합니다.