2010-06-06 7 views
3

나는 게임을 만들고 현재 math.random 네스를 다뤄야 만합니다. 내가 루아에 강한 아니에요으로루아 : 랜덤 : 백분율

는, 당신은 어떻게

  • 가 주어진 비율로 math.random를 사용하는 알고리즘을 만들 수 있다고 생각합니까?

나는 함수 같은 의미 :

내가 계속하는 방법을 단서가 없다, 나는 완전히 알고리즘

난 당신이 내가 무슨 내 나쁜 설명을 이해 바랍니다 빨아 그러나

function randomChance(chance) 
     -- Magic happens here 
     -- Return either 0 or 1 based on the results of math.random 
end 
randomChance(50) -- Like a 50-50 chance of "winning", should result in something like math.random(1, 2) == 1 (?) 
randomChance(20) -- 20% chance to result in a 1 
randomChance(0) -- Result always is 0 

달성하려는 중

답변

7

인수가 없으면 math.random 함수는 [0,1] 범위의 숫자를 반환합니다.

Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio 
> =math.random() 
0.13153778814317 
> =math.random() 
0.75560532219503 

그래서 단순히 0과 1 사이의 숫자로 "기회"를 변환 : 즉,

> function maybe(x) if math.random() < x then print("yes") else print("no") end end 
> maybe(0.5) 
yes 
> maybe(0.5) 
no 

또는 범위 0-의 int에 대해 비교, 100 random의 결과를 곱 100 :

> function maybe(x) if 100 * math.random() < x then print(1) else print(0) end end                    
> maybe(50) 
0 
> maybe(10) 
0 
> maybe(99) 
1 

또 다른 대안 math.random에 상하한을 전달하는 것이다

> function maybe(x) if math.random(0,100) < x then print(1) else print(0) end end 
> maybe(0) 
0 
> maybe(100) 
1 
+0

, 그래서 일을 : 100의 범위 1에서 100 개 번호를 선택하면 당신은 당신이 원하는 비율을 얻어야한다 101 개의 가능한 숫자 중 하나이므로 어쩌면 함수의 x는 더 이상 백분율이 아니지만 101 개의 확률로 1이됩니다. –

5

여기서는 부동 소수점 숫자를 사용하지 않을 것입니다. 나는 정수 인자와 정수 결과를 가지고 math.random을 사용할 것이다. 인 Math.random가 (0100)가`100 0 사이의 숫자를 반환합니다`것을 명심하시기 바랍니다

function randomChange (percent) -- returns true a given percentage of calls 
    assert(percent >= 0 and percent <= 100) -- sanity check 
    return percent >= math.random(1, 100) -- 1 succeeds 1%, 50 succeeds 50%, 
              -- 100 always succeeds, 0 always fails 
end