2006-04-11

실습 - 로또 번호 뽑기

간단하게 만들어볼 수 있고, 유용한(?) 사례입니다.
우선, 1부터 45까지의 숫자 중 중복되지 않은 7개의 숫자를 뽑는 경우를 충실하게 재현한 방식입니다.
-- 1부터 45까지의 숫자 중 보너스 번호를 포함해서 7개의 중복되지 않은 숫자를 골라냅니다.
property theBasket : {} as list
property theChosenBalls : {} as list

set theBasket to my fillBasket()
set theBalls to my chooseBalls()

-- 1부터 45까지의 번호를 바구니에 채웁니다.
on fillBasket()
repeat with i from 1 to 45
set theBasket to theBasket & i
end repeat
end fillBasket

-- 보너스번호를 포함해서 7개의 번호를 뽑습니다.
on chooseBalls()
repeat with n from 1 to 7
-- 남아있는 번호 중 하나를 뽑습니다.
set theChosenBall to item (random number from 1 to (count of theBasket)) of theBasket
set theChosenBalls to theChosenBalls & theChosenBall
-- 뽑은 번호를 다시 뽑지 않도록 제거합니다.
my remove(theChosenBall)
end repeat

-- 뽑은 결과를 정리합니다.
my processResult()
end chooseBalls

-- 뽑은 번호를 제거하는 서브루틴입니다.
-- 남은 번호들과 뽑힌 번호를 비교해서, 다른 경우에는 다시 바구니에 넣습니다.
on remove(theChosenBall)
-- 임시 바구니를 만들어 모두 옮깁니다.
set newBasket to theBasket
-- 바구니를 비웁니다. 비교하면서 뽑힌 번호가 아니면 바구니에 채웁니다.
set theBasket to {}

-- 임시바구니에서 번호를 하나씩 꺼내서 뽑힌 번호와 비교합니다.
repeat with m from 1 to (count of newBasket)
-- 뽑힌 번호와 같지 않으면 바구니에 다시 넣습니다.
if (item m of newBasket) is not theChosenBall then
set theBasket to theBasket & (item m of newBasket)
end if
end repeat
end remove

on processResult()
set the result to "Here are the numbers. " & return
set the result to the result & "1st : " & item 1 of theChosenBalls & return
set the result to the result & "2nd : " & item 2 of theChosenBalls & return
set the result to the result & "3rd : " & item 3 of theChosenBalls & return
set the result to the result & "4th : " & item 4 of theChosenBalls & return
set the result to the result & "5th : " & item 5 of theChosenBalls & return
set the result to the result & "6th : " & item 6 of theChosenBalls & return
set the result to the result & "bonus : " & item 7 of theChosenBalls & return
end processResult


몇가지 핸들러도 사용하고 복잡해보이지만, AppleScript에는 contains라는 명령어가 있습니다. list에 들어있는 item이라면 true를 반환하는 명령어입니다. contains를 사용해서 간략하게 줄여보겠습니다. 1부터 45까지의 숫자에서 하나씩 뽑아내고, 이미 들어있다면 다시 뽑는 방식입니다. 위의 예제보다 훨씬 짧습니다.
set theBasket to {}

set i to 0
repeat
set theBall to random number from 1 to 45

if theBasket does not contain theBall then
set theBasket to theBasket & theBall
set i to i + 1
end if

if i >= 7 then exit repeat
end repeat

get theBasket --get은 생략 가능

0 Comments:

댓글 쓰기

<< Home