2009年3月19日 星期四

亂數應用 - 樂透開獎與撲克牌發牌

image

image

image image

Public Class Form1
    Dim i, n, str1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Randomize()
        'Int(Rnd() * 個數) + 最小值

        '樂透開獎 - 會重覆待修正版
        str1 = ""
        For i = 1 To 7
            n = Int(Rnd() * (42 - 1 + 1)) + 1
            str1 = str1 & n & "  "
        Next i
        MsgBox(str1)

        '樂透開獎 - 不重覆版
        Dim a(42)
        For i = 1 To 42
            a(i) = i
        Next
        For i = 1 To 42
            n = Int(Rnd() * (42 - 1 + 1)) + 1
            Dim t = a(i)
            a(i) = a(n)
            a(n) = t
        Next
        str1 = ""
        For i = 1 To 7
            str1 = str1 & a(i) & "  "
        Next
        MsgBox(str1)

        '撲克牌準備
        Dim b(52, 2)
        For i = 1 To 52
            b(i, 1) = (i - 1) Mod 13 + 1
            If i Mod 4 = 0 Then b(i, 2) = "黑桃"
            If i Mod 4 = 1 Then b(i, 2) = "紅心"
            If i Mod 4 = 2 Then b(i, 2) = "鑽石"
            If i Mod 4 = 3 Then b(i, 2) = "梅花"
        Next
        str1 = ""
        For i = 1 To 52
            str1 = str1 & b(i, 1) & "-" & b(i, 2) & vbNewLine
        Next
        MsgBox(str1)

        '撲克牌洗牌
        For i = 1 To 52
            n = Int(Rnd() * (42 - 1 + 1)) + 1
            Dim t = b(i, 1)
            b(i, 1) = b(n, 1)
            b(n, 1) = t

            t = b(i, 2)
            b(i, 2) = b(n, 2)
            b(n, 2) = t
        Next
        str1 = ""
        For i = 1 To 52
            str1 = str1 & b(i, 1) & "-" & b(i, 2) & vbNewLine
        Next
        MsgBox(str1)
        End
    End Sub
End Class

沒有留言:

張貼留言